diff --git a/seaweed-volume/src/server/handlers.rs b/seaweed-volume/src/server/handlers.rs index 4919d660c3..7bdedd55de 100644 --- a/seaweed-volume/src/server/handlers.rs +++ b/seaweed-volume/src/server/handlers.rs @@ -64,7 +64,10 @@ struct InflightGuard<'a> { impl<'a> Drop for InflightGuard<'a> { fn drop(&mut self) { - let new_val = self.counter.fetch_sub(self.bytes, Ordering::Relaxed) - self.bytes; + let new_val = self + .counter + .fetch_sub(self.bytes, Ordering::Relaxed) + .wrapping_sub(self.bytes); self.metric.set(new_val); self.notify.notify_waiters(); } @@ -738,15 +741,18 @@ async fn batch_delete_file_ids( } /// `query` with the fields named in `overrides` replaced by their values. -fn override_query_fields(query: &str, overrides: &[(&str, String)]) -> Result { +fn override_query_fields( + query: &str, + overrides: &[(&str, String)], + removed: &[&str], +) -> Result { let mut fields = Vec::new(); for field in query.split('&').filter(|field| !field.is_empty()) { let decoded: Vec<(String, String)> = serde_urlencoded::from_str(field) .map_err(|e| format!("parse replication query: {e}"))?; - if !decoded - .iter() - .any(|(name, _)| overrides.iter().any(|(o, _)| o == name)) - { + if !decoded.iter().any(|(name, _)| { + overrides.iter().any(|(o, _)| o == name) || removed.contains(&name.as_str()) + }) { fields.push(field); } } @@ -848,7 +854,7 @@ async fn do_replicated_request( return Ok(()); } - let new_query = override_query_fields(query, &[("type", "replicate".to_string())])?; + let new_query = override_query_fields(query, &[("type", "replicate".to_string())], &["src"])?; let mut futures = Vec::new(); for loc in remote_locations { @@ -2795,6 +2801,68 @@ fn is_zero_u32(v: &u32) -> bool { *v == 0 } +/// Bounds how long a client write waits for upload budget, whatever +/// -inflightUploadDataTimeout says; Go's volumeClientUploadWaitCap. It stays +/// below the uploading gateway's 10s body deadline floor, so the client gets +/// a 503 before its deadline cuts the request off as a stall. +const VOLUME_CLIENT_UPLOAD_WAIT_CAP: std::time::Duration = std::time::Duration::from_secs(5); + +/// How long a client write waits for upload budget: the configured timeout, +/// at most VOLUME_CLIENT_UPLOAD_WAIT_CAP (also when the timeout is 0). +fn client_upload_wait(configured: std::time::Duration) -> std::time::Duration { + if configured.is_zero() { + return VOLUME_CLIENT_UPLOAD_WAIT_CAP; + } + configured.min(VOLUME_CLIENT_UPLOAD_WAIT_CAP) +} + +/// Go's util.UploadAdmits: a limit of 0 admits, an idle server admits any +/// single upload, otherwise in_flight + size must stay within limit. +fn upload_admits(in_flight: i64, size: i64, limit: i64) -> bool { + limit == 0 || in_flight == 0 || in_flight.saturating_add(size) <= limit +} + +/// Go's VolumeServer.uploadCharge: a known length is charged as-is; an +/// unknown one (chunked transfer) counts as one file, at most half the limit +/// and at least 1 byte, so it is still admitted while half the budget is in use. +fn upload_charge(content_length: Option, file_size_limit: i64, limit: i64) -> i64 { + if let Some(len) = content_length { + return i64::try_from(len).unwrap_or(i64::MAX); + } + let half = (limit / 2).max(1); + match (file_size_limit > 0, limit > 0) { + (true, true) => file_size_limit.min(half), + (true, false) => file_size_limit, + (false, true) => half, + (false, false) => 0, + } +} + +/// The 503 for an upload that gets no budget. Go's uploadRejectCloseThreshold: +/// a large or unknown-length HTTP/1 body is cheaper to drop with the +/// connection than to drain. +fn upload_limit_exceeded( + query: &str, + version: axum::http::Version, + declared_length: Option, +) -> Response { + let mut response = json_error_with_query( + StatusCode::SERVICE_UNAVAILABLE, + "upload limit exceeded", + Some(query), + ); + response + .headers_mut() + .insert(header::RETRY_AFTER, header::HeaderValue::from_static("1")); + if version < axum::http::Version::HTTP_2 && declared_length.is_none_or(|len| len > 256 << 10) { + response.headers_mut().insert( + header::CONNECTION, + header::HeaderValue::from_static("close"), + ); + } + response +} + /// Store an uploaded needle on the local volume — durable (fsync) uploads /// through the per-volume write queue, the rest synchronously — and then /// replicate it if the volume's placement calls for more copies. @@ -2866,60 +2934,79 @@ pub async fn post_handler( .iter() .find(|(name, _)| name == "type") .is_some_and(|(_, value)| value == "replicate"); - let content_length = headers + // Go's operation.IsReplicaForward: a gateway's fan-out write to each + // holder (src=client) is client traffic, not a primary-to-replica forward. + let is_replica_forward = is_replicate + && !query_fields + .iter() + .find(|(name, _)| name == "src") + .is_some_and(|(_, value)| value == "client"); + let limit = state.concurrent_upload_limit; + let declared_length = headers .get(header::CONTENT_LENGTH) .and_then(|v| v.to_str().ok()) - .and_then(|s| s.parse::().ok()) - .unwrap_or(0); - - if !is_replicate && state.concurrent_upload_limit > 0 { - // Wait for inflight bytes to drop below limit, or timeout - let timeout = if state.inflight_upload_data_timeout.is_zero() { - std::time::Duration::from_secs(2) - } else { - state.inflight_upload_data_timeout - }; - let deadline = tokio::time::Instant::now() + timeout; - + .and_then(|s| s.parse::().ok()) + .or_else(|| http_body::Body::size_hint(request.body()).exact()); + let charged = upload_charge(declared_length, state.file_size_limit_bytes, limit); + if !is_replica_forward && limit > 0 { + let deadline = + tokio::time::Instant::now() + client_upload_wait(state.inflight_upload_data_timeout); + let mut waited = false; loop { - let current = state.inflight_upload_bytes.load(Ordering::Relaxed); - if current <= state.concurrent_upload_limit { + // Created before the check, so a release in between still wakes it. + let notified = state.upload_notify.notified(); + // try_update needs 1.95; rust-version is 1.91.1. + #[allow(deprecated)] + let admitted = state.inflight_upload_bytes.fetch_update( + Ordering::AcqRel, + Ordering::Acquire, + |in_flight| { + if upload_admits(in_flight, charged, limit) { + in_flight.checked_add(charged) + } else { + None + } + }, + ); + if let Ok(prev) = admitted { + metrics::INFLIGHT_UPLOAD_SIZE.set(prev + charged); break; } - // Go increments UploadLimitCond on every loop iteration (L184), - // not just on timeout. - metrics::HANDLER_COUNTER - .with_label_values(&[metrics::UPLOAD_LIMIT_COND]) - .inc(); - // Wait for notification or timeout - if tokio::time::timeout_at(deadline, state.upload_notify.notified()) - .await - .is_err() - { - return json_error_with_query( - StatusCode::TOO_MANY_REQUESTS, - "upload limit exceeded", - Some(&query), - ); + if !waited { + waited = true; + metrics::HANDLER_COUNTER + .with_label_values(&[metrics::UPLOAD_LIMIT_COND]) + .inc(); + } + if tokio::time::timeout_at(deadline, notified).await.is_err() { + return upload_limit_exceeded(&query, request.version(), declared_length); } } + } else if limit > 0 { + // A forward the primary already accepted must reach its replicas, so + // it is refused only when the counter cannot hold its size. + #[allow(deprecated)] + let reserved = state.inflight_upload_bytes.fetch_update( + Ordering::AcqRel, + Ordering::Acquire, + |in_flight| in_flight.checked_add(charged), + ); + match reserved { + Ok(prev) => metrics::INFLIGHT_UPLOAD_SIZE.set(prev + charged), + Err(_) => return upload_limit_exceeded(&query, request.version(), declared_length), + } + } else { let new_val = state .inflight_upload_bytes - .fetch_add(content_length, Ordering::Relaxed) - + content_length; + .fetch_add(charged, Ordering::Relaxed) + .wrapping_add(charged); metrics::INFLIGHT_UPLOAD_SIZE.set(new_val); } - - // RAII guard to release upload throttle on any exit path - let _upload_guard = if !is_replicate && state.concurrent_upload_limit > 0 { - Some(InflightGuard { - counter: &state.inflight_upload_bytes, - bytes: content_length, - notify: &state.upload_notify, - metric: &metrics::INFLIGHT_UPLOAD_SIZE, - }) - } else { - None + let _upload_guard = InflightGuard { + counter: &state.inflight_upload_bytes, + bytes: charged, + notify: &state.upload_notify, + metric: &metrics::INFLIGHT_UPLOAD_SIZE, }; let content_type_str = headers @@ -3440,7 +3527,7 @@ pub async fn post_handler( vid.0, Method::POST, &path_clone, - &override_query_fields(&query_clone, &overrides)?, + &override_query_fields(&query_clone, &overrides, &[])?, &replica_headers, Some(replica_body), ) @@ -5471,6 +5558,17 @@ mod tests { ); } + #[test] + fn test_override_query_fields_removes_src() { + let q = override_query_fields( + "%73rc=client&fsync=true&type=x", + &[("type", "replicate".to_string())], + &["src"], + ) + .unwrap(); + assert_eq!(q, "fsync=true&type=replicate"); + } + /// Every URL form the volume server accepts, against what Go's /// `parseURLPath` returns for it (`weed/server/common.go:218-249`): /// the `vid/fid/filename` form leaves the fid alone and takes the @@ -6776,6 +6874,233 @@ mod tests { test_state_with_store(store) } + /// An upload that finds no budget within the wait answers 503 with + /// Retry-After, the same as the Go volume server. + #[tokio::test] + async fn upload_limit_timeout_answers_503_with_retry_after() { + let tmp = tempfile::TempDir::new().unwrap(); + let mut state = volume_test_state(&tmp); + { + let s = Arc::get_mut(&mut state).unwrap(); + s.concurrent_upload_limit = 10; + s.inflight_upload_data_timeout = std::time::Duration::from_millis(50); + } + state.inflight_upload_bytes.store(11, Ordering::Relaxed); + + let request = Request::builder() + .method(Method::POST) + .uri("/1,0123456789abcdef") + .header(header::CONTENT_LENGTH, "4") + .body(Body::from("abcd")) + .unwrap(); + let resp = post_handler(State(state.clone()), request).await; + + assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + resp.headers().get(header::RETRY_AFTER).unwrap(), + &header::HeaderValue::from_static("1") + ); + assert!(resp.headers().get(header::CONNECTION).is_none()); + assert_eq!(state.inflight_upload_bytes.load(Ordering::Relaxed), 11); + } + + /// A gateway's fan-out write (type=replicate&src=client) waits for upload + /// budget like any client write; a primary's own forward does not. + #[tokio::test] + async fn upload_limit_counts_gateway_fan_out_not_replica_forward() { + let tmp = tempfile::TempDir::new().unwrap(); + let mut state = volume_test_state(&tmp); + { + let s = Arc::get_mut(&mut state).unwrap(); + s.concurrent_upload_limit = 10; + s.inflight_upload_data_timeout = std::time::Duration::from_millis(50); + } + state.inflight_upload_bytes.store(11, Ordering::Relaxed); + + let post = |uri: &str| { + Request::builder() + .method(Method::POST) + .uri(uri) + .header(header::CONTENT_LENGTH, "4") + .body(Body::from("abcd")) + .unwrap() + }; + let fan_out = post_handler( + State(state.clone()), + post("/1,0123456789abcdef?type=replicate&src=client"), + ) + .await; + assert_eq!(fan_out.status(), StatusCode::SERVICE_UNAVAILABLE); + + let forward = post_handler( + State(state.clone()), + post("/1,0123456789abcdef?type=replicate"), + ) + .await; + assert_ne!(forward.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(state.inflight_upload_bytes.load(Ordering::Relaxed), 11); + } + + /// A forward whose size the in-flight counter cannot hold is refused + /// instead of wrapping the counter negative. + #[tokio::test] + async fn upload_limit_refuses_a_forward_the_counter_cannot_hold() { + let tmp = tempfile::TempDir::new().unwrap(); + let mut state = volume_test_state(&tmp); + { + let s = Arc::get_mut(&mut state).unwrap(); + s.concurrent_upload_limit = 10; + s.inflight_upload_data_timeout = std::time::Duration::from_millis(50); + } + state.inflight_upload_bytes.store(4 << 20, Ordering::Relaxed); + + let request = |uri: &str| { + Request::builder() + .method(Method::POST) + .uri(uri) + .header(header::CONTENT_LENGTH, i64::MAX.to_string()) + .body(Body::from("abcd")) + .unwrap() + }; + for uri in [ + "/1,0123456789abcdef?type=replicate", + "/1,0123456789abcdef?type=replicate&src=client", + ] { + let resp = post_handler(State(state.clone()), request(uri)).await; + assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE, "{uri}"); + assert_eq!( + state.inflight_upload_bytes.load(Ordering::Relaxed), + 4 << 20, + "{uri}" + ); + } + } + + #[test] + fn upload_charge_matches_go() { + assert_eq!(upload_charge(Some(0), 8 << 20, 10), 0); + assert_eq!(upload_charge(Some(123), 8 << 20, 10), 123); + assert_eq!(upload_charge(None, 8 << 20, 100 << 20), 8 << 20); + assert_eq!(upload_charge(None, 8 << 20, 10 << 20), 5 << 20); + assert_eq!(upload_charge(None, 8 << 20, 1), 1); + assert_eq!(upload_charge(None, 8 << 20, 0), 8 << 20); + assert_eq!(upload_charge(None, 0, 10), 5); + } + + /// A chunked upload without Content-Length still reserves upload budget. + #[tokio::test] + async fn upload_limit_charges_an_unknown_length_upload() { + let tmp = tempfile::TempDir::new().unwrap(); + let mut state = volume_test_state(&tmp); + { + let s = Arc::get_mut(&mut state).unwrap(); + s.concurrent_upload_limit = 10; + s.inflight_upload_data_timeout = std::time::Duration::from_millis(50); + } + state.inflight_upload_bytes.store(6, Ordering::Relaxed); + + let body = Body::from_stream(futures::stream::iter(vec![Ok::<_, std::io::Error>( + bytes::Bytes::from_static(b"abcd"), + )])); + let request = Request::builder() + .method(Method::POST) + .uri("/1,0123456789abcdef") + .body(body) + .unwrap(); + let resp = post_handler(State(state.clone()), request).await; + + assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!( + resp.headers().get(header::CONNECTION).unwrap(), + &header::HeaderValue::from_static("close") + ); + assert_eq!(state.inflight_upload_bytes.load(Ordering::Relaxed), 6); + } + + #[test] + fn upload_admits_matches_go() { + assert!(upload_admits(1 << 40, 1 << 30, 0)); + assert!(upload_admits(6, 4, 10)); + assert!(!upload_admits(8, 4, 10)); + assert!(upload_admits(0, 100, 10)); + assert!(!upload_admits(1, 100, 10)); + assert!(upload_admits(10, 0, 10)); + assert!(!upload_admits(11, i64::MAX, 10)); + } + + /// Admission counts the request's own size: under the limit is not + /// enough when the upload would overshoot it. + #[tokio::test] + async fn upload_limit_refuses_an_upload_that_would_overshoot() { + let tmp = tempfile::TempDir::new().unwrap(); + let mut state = volume_test_state(&tmp); + { + let s = Arc::get_mut(&mut state).unwrap(); + s.concurrent_upload_limit = 10; + s.inflight_upload_data_timeout = std::time::Duration::from_millis(50); + } + state.inflight_upload_bytes.store(8, Ordering::Relaxed); + + let request = Request::builder() + .method(Method::POST) + .uri("/1,0123456789abcdef") + .header(header::CONTENT_LENGTH, "4") + .body(Body::from("abcd")) + .unwrap(); + let resp = post_handler(State(state.clone()), request).await; + + assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(state.inflight_upload_bytes.load(Ordering::Relaxed), 8); + } + + #[tokio::test] + async fn upload_limit_waiter_proceeds_once_budget_is_released() { + let tmp = tempfile::TempDir::new().unwrap(); + let mut state = volume_test_state(&tmp); + { + let s = Arc::get_mut(&mut state).unwrap(); + s.concurrent_upload_limit = 10; + s.inflight_upload_data_timeout = std::time::Duration::from_secs(4); + } + state.inflight_upload_bytes.store(8, Ordering::Relaxed); + + let request = Request::builder() + .method(Method::POST) + .uri("/1,0123456789abcdef") + .header(header::CONTENT_LENGTH, "4") + .body(Body::from("abcd")) + .unwrap(); + let waiter = tokio::spawn(post_handler(State(state.clone()), request)); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert!(!waiter.is_finished()); + state.inflight_upload_bytes.store(0, Ordering::Relaxed); + state.upload_notify.notify_waiters(); + + let resp = tokio::time::timeout(std::time::Duration::from_secs(2), waiter) + .await + .expect("waiter should be admitted once budget is released") + .unwrap(); + assert_ne!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(state.inflight_upload_bytes.load(Ordering::Relaxed), 0); + } + + #[test] + fn client_upload_wait_is_capped() { + use std::time::Duration; + assert_eq!( + client_upload_wait(Duration::ZERO), + VOLUME_CLIENT_UPLOAD_WAIT_CAP + ); + assert_eq!( + client_upload_wait(Duration::from_millis(50)), + Duration::from_millis(50) + ); + assert_eq!( + client_upload_wait(Duration::from_secs(60)), + VOLUME_CLIENT_UPLOAD_WAIT_CAP + ); + } + #[tokio::test] async fn download_limit_local_read_mode_waits_instead_of_proxying() { use crate::storage::super_block::ReplicaPlacement; diff --git a/test/volume_server/http/throttling_test.go b/test/volume_server/http/throttling_test.go index e07c441d85..8aa7d3280f 100644 --- a/test/volume_server/http/throttling_test.go +++ b/test/volume_server/http/throttling_test.go @@ -126,8 +126,11 @@ func TestUploadLimitTimeoutAndReplicateBypass(t *testing.T) { t.Fatalf("normal upload request failed: %v", err) } _ = framework.ReadAllAndClose(t, normalResp) - if normalResp.StatusCode != http.StatusTooManyRequests { - t.Fatalf("normal upload expected 429 while limit blocked, got %d", normalResp.StatusCode) + if normalResp.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("normal upload expected 503 while limit blocked, got %d", normalResp.StatusCode) + } + if got := normalResp.Header.Get("Retry-After"); got == "" { + t.Fatalf("normal upload 503 expected a Retry-After header") } close(unblockFirstUpload) @@ -262,8 +265,11 @@ func TestUploadLimitTimeoutThenRecovery(t *testing.T) { timeoutFID := framework.NewFileID(volumeID, 880802, 0x7A2B3C4E) timeoutResp := framework.UploadBytes(t, &http.Client{Timeout: 10 * time.Second}, clusterHarness.VolumeAdminURL(), timeoutFID, []byte("should-timeout")) _ = framework.ReadAllAndClose(t, timeoutResp) - if timeoutResp.StatusCode != http.StatusTooManyRequests { - t.Fatalf("second upload under blocked pressure expected 429, got %d", timeoutResp.StatusCode) + if timeoutResp.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("second upload under blocked pressure expected 503, got %d", timeoutResp.StatusCode) + } + if got := timeoutResp.Header.Get("Retry-After"); got == "" { + t.Fatalf("second upload 503 expected a Retry-After header") } close(unblockFirstUpload) diff --git a/weed/command/mini.go b/weed/command/mini.go index 4d08d98780..416658bb85 100644 --- a/weed/command/mini.go +++ b/weed/command/mini.go @@ -523,7 +523,7 @@ func initMiniVolumeFlags() { miniOptions.v.concurrentDownloadLimitMB = cmdMini.Flag.Int("volume.concurrentDownloadLimitMB", 0, "limit total concurrent download size; reads over the limit are sent to a replica unless volume.readMode is local") miniOptions.v.pprof = cmdMini.Flag.Bool("volume.pprof", false, "enable pprof http handlers") miniOptions.v.idxFolder = cmdMini.Flag.String("volume.dir.idx", "", "directory to store .idx files") - miniOptions.v.inflightUploadDataTimeout = cmdMini.Flag.Duration("volume.inflightUploadDataTimeout", 60*time.Second, "inflight upload data wait timeout") + miniOptions.v.inflightUploadDataTimeout = cmdMini.Flag.Duration("volume.inflightUploadDataTimeout", 60*time.Second, "how long a client upload waits for room under -volume.concurrentUploadLimitMB before it is rejected with 503 and Retry-After; client writes wait at most 5s, and 0 means that 5s cap; primary-to-replica forwards are never refused") miniOptions.v.inflightDownloadDataTimeout = cmdMini.Flag.Duration("volume.inflightDownloadDataTimeout", 60*time.Second, "inflight download data wait timeout") miniOptions.v.hasSlowRead = cmdMini.Flag.Bool("volume.hasSlowRead", true, "if true, prevents slow reads from blocking other requests") miniOptions.v.readBufferSizeMB = cmdMini.Flag.Int("volume.readBufferSizeMB", 4, "read buffer size in MB") diff --git a/weed/command/server.go b/weed/command/server.go index 86b543baaf..1076d085d4 100644 --- a/weed/command/server.go +++ b/weed/command/server.go @@ -166,7 +166,7 @@ func init() { serverOptions.v.preStopSeconds = cmdServer.Flag.Int("volume.preStopSeconds", 10, "number of seconds between stop send heartbeats and stop volume server") serverOptions.v.pprof = cmdServer.Flag.Bool("volume.pprof", false, "enable pprof http handlers. precludes -memprofile and -cpuprofile") serverOptions.v.idxFolder = cmdServer.Flag.String("volume.dir.idx", "", "directory to store .idx files") - serverOptions.v.inflightUploadDataTimeout = cmdServer.Flag.Duration("volume.inflightUploadDataTimeout", 60*time.Second, "inflight upload data wait timeout of volume servers") + serverOptions.v.inflightUploadDataTimeout = cmdServer.Flag.Duration("volume.inflightUploadDataTimeout", 60*time.Second, "how long a client upload waits for room under -volume.concurrentUploadLimitMB before it is rejected with 503 and Retry-After; client writes wait at most 5s, and 0 means that 5s cap; primary-to-replica forwards are never refused") serverOptions.v.inflightDownloadDataTimeout = cmdServer.Flag.Duration("volume.inflightDownloadDataTimeout", 60*time.Second, "inflight download data wait timeout of volume servers") serverOptions.v.hasSlowRead = cmdServer.Flag.Bool("volume.hasSlowRead", true, " if true, this prevents slow reads from blocking other requests, but large file read P99 latency will increase.") diff --git a/weed/command/volume.go b/weed/command/volume.go index 4f51f954e2..6460711256 100644 --- a/weed/command/volume.go +++ b/weed/command/volume.go @@ -245,7 +245,7 @@ func init() { v.metricsHttpPort = cmdVolume.Flag.Int("metricsPort", 0, "Prometheus metrics listen port") v.metricsHttpIp = cmdVolume.Flag.String("metricsIp", "", "metrics listen ip. If empty, default to same as -ip.bind option.") v.idxFolder = cmdVolume.Flag.String("dir.idx", "", "directory to store .idx files") - v.inflightUploadDataTimeout = cmdVolume.Flag.Duration("inflightUploadDataTimeout", 60*time.Second, "inflight upload data wait timeout of volume servers") + v.inflightUploadDataTimeout = cmdVolume.Flag.Duration("inflightUploadDataTimeout", 60*time.Second, "how long a client upload waits for room under -concurrentUploadLimitMB before it is rejected with 503 and Retry-After; client writes wait at most 5s, and 0 means that 5s cap; primary-to-replica forwards are never refused") v.inflightDownloadDataTimeout = cmdVolume.Flag.Duration("inflightDownloadDataTimeout", 60*time.Second, "inflight download data wait timeout of volume servers") v.hasSlowRead = cmdVolume.Flag.Bool("hasSlowRead", true, " if true, this prevents slow reads from blocking other requests, but large file read P99 latency will increase.") v.readBufferSizeMB = cmdVolume.Flag.Int("readBufferSizeMB", 4, " larger values can optimize query performance but will increase some memory usage,Use with hasSlowRead normally.") diff --git a/weed/operation/replicate_source.go b/weed/operation/replicate_source.go new file mode 100644 index 0000000000..36092ac107 --- /dev/null +++ b/weed/operation/replicate_source.go @@ -0,0 +1,18 @@ +package operation + +import "net/url" + +const ( + // ReplicateSourceParam names the query parameter that says who sent a + // ?type=replicate write. + ReplicateSourceParam = "src" + // ReplicateSourceClient marks a write a gateway fans out to every holder + // itself. A write without it is a volume server forwarding to its replicas. + ReplicateSourceClient = "client" +) + +// IsReplicaForward reports whether the request is a volume server's own +// primary-to-replica forward, as opposed to a gateway's fan-out write. +func IsReplicaForward(q url.Values) bool { + return q.Get("type") == "replicate" && q.Get(ReplicateSourceParam) != ReplicateSourceClient +} diff --git a/weed/operation/upload_auth_preparation_test.go b/weed/operation/upload_auth_preparation_test.go index 825a4c7a8c..ba804e5300 100644 --- a/weed/operation/upload_auth_preparation_test.go +++ b/weed/operation/upload_auth_preparation_test.go @@ -86,7 +86,9 @@ func TestUploadPreparesBeforeAssignment(t *testing.T) { first := len(stored) == 1 mu.Unlock() if first { - w.WriteHeader(http.StatusServiceUnavailable) + // A transient fault retried on the same fid. Not a 503: that + // is an overload, which goes back for a fresh assignment. + w.WriteHeader(http.StatusInternalServerError) _, _ = io.WriteString(w, `{"error":"busy"}`) return } diff --git a/weed/operation/upload_chunked.go b/weed/operation/upload_chunked.go index 67f8c32f33..a202497288 100644 --- a/weed/operation/upload_chunked.go +++ b/weed/operation/upload_chunked.go @@ -51,6 +51,10 @@ type ChunkedUploadOption struct { // Digest names the target filer's digest, so the content and chunk // digests match what that filer holds; empty uses this process's mode. Digest string + + // BodyDeadline opts every chunk write (relay and fan-out) into the body + // deadline; see UploadOption.BodyDeadline. + BodyDeadline bool } var chunkBufferPool = sync.Pool{ @@ -227,6 +231,11 @@ uploadLoop: // A target that fills up, loses its replica peer, or goes away fails // every attempt against the same fid, so ask for a fresh assignment and // retry there rather than losing the whole object to one bad volume. + // Back-pressure (an overload, or a body cut at the body deadline) + // gets one fresh assignment only: a cluster short of upload budget + // or link rate is not helped by being asked again while this chunk + // holds its buffer, and the client is told to slow down instead. + backpressureReassigned := false for attempt := 1; ; attempt++ { uploadResult, uploadResultErr = uploadChunk(ctx, assignResult, buf.Bytes(), prepared, jwt, chunkMd5B64, opt) if uploadResultErr == nil { @@ -240,6 +249,12 @@ uploadLoop: if attempt == chunkAssignAttempts || !ShouldReassignUpload(uploadResultErr) || objectFailed() { break } + if IsUploadBackpressure(uploadResultErr) { + if backpressureReassigned { + break + } + backpressureReassigned = true + } glog.V(2).Infof("re-assigning chunk at offset %d after attempt %d/%d: %v", offset, attempt, chunkAssignAttempts, uploadResultErr) _, assignResult, assignErr = opt.AssignFunc(ctx, 1, uint64(size)) if assignErr != nil { @@ -360,7 +375,7 @@ func uploadChunk(ctx context.Context, assignResult *AssignResult, data []byte, p // chunkUploadOption holds the settings that shape a chunk's bytes, shared by // its preparation and every upload of it. func chunkUploadOption(opt *ChunkedUploadOption) *UploadOption { - return &UploadOption{Cipher: opt.Cipher, MimeType: opt.MimeType, Digest: opt.Digest} + return &UploadOption{Cipher: opt.Cipher, MimeType: opt.MimeType, Digest: opt.Digest, BodyDeadline: opt.BodyDeadline} } // chunkHolders returns the assigned volume plus its replica holders. @@ -394,7 +409,7 @@ func uploadChunkToHolders(ctx context.Context, hosts []string, fid string, prepa outcomes := make(chan outcome, len(hosts)) for _, host := range hosts { go func(host string) { - uploadUrl := fmt.Sprintf("http://%s/%s?type=replicate", host, fid) + uploadUrl := fmt.Sprintf("http://%s/%s?type=replicate&%s=%s", host, fid, ReplicateSourceParam, ReplicateSourceClient) if fsync { uploadUrl += "&fsync=true" } @@ -431,7 +446,10 @@ func uploadChunkToHolders(ctx context.Context, hosts []string, fid string, prepa } if firstErr != nil { // A failed fan-out records no chunk, so roll back the copies that landed - // before the cancel rather than leaking them as orphans. + // before the cancel rather than leaking them as orphans. A holder that + // did not answer (cancelled, the caller gone) may still commit what it + // already received; the chunk loop's cleanup in uploadReaderInChunks + // deletes the fid from every holder after any failed attempt. deleteChunkFromHolders(succeeded, fid, jwt, opt) return nil, firstErr } @@ -453,7 +471,7 @@ func deleteChunkFromHolders(hosts []string, fid string, jwt security.EncodedJwt, // outlives the renewed token can still trigger another renewal. deleteJwt := jwt for _, host := range hosts { - deleteUrl := fmt.Sprintf("http://%s/%s?type=replicate", host, fid) + deleteUrl := fmt.Sprintf("http://%s/%s?type=replicate&%s=%s", host, fid, ReplicateSourceParam, ReplicateSourceClient) body, status, err := util_http.DeleteProxied(deleteUrl, string(deleteJwt)) if status == http.StatusUnauthorized && opt.LookupJwtFunc != nil { lookupCtx, cancel := context.WithTimeout(context.Background(), cleanupJwtLookupTimeout) diff --git a/weed/operation/upload_chunked_test.go b/weed/operation/upload_chunked_test.go index cd54b0489f..36a3ca73bd 100644 --- a/weed/operation/upload_chunked_test.go +++ b/weed/operation/upload_chunked_test.go @@ -8,6 +8,9 @@ import ( "io" "net/http" "net/http/httptest" + "net/url" + "slices" + "strconv" "strings" "sync" "sync/atomic" @@ -15,6 +18,7 @@ import ( "time" "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/stretchr/testify/require" ) // TestUploadReaderInChunksReturnsPartialResultsOnError verifies that when @@ -768,3 +772,323 @@ func TestDeleteChunkFromHoldersRenewsPerHolder(t *testing.T) { t.Fatalf("expected the second holder's retried delete to land, got %d", acceptedDeletes) } } + +// TestUploadChunkToHoldersMarksClientSource verifies that the gateway's own +// fan-out writes are tagged as client traffic, so a volume server can tell +// them apart from a primary-to-replica forward. +func TestUploadChunkToHoldersMarksClientSource(t *testing.T) { + var mu sync.Mutex + var queries []url.Values + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + queries = append(queries, r.URL.Query()) + mu.Unlock() + fmt.Fprintf(w, `{"name":"f","size":11}`) + }) + h1 := httptest.NewServer(handler) + defer h1.Close() + h2 := httptest.NewServer(handler) + defer h2.Close() + + assignResult := &AssignResult{ + Fid: "3,01abcdef", + Url: strings.TrimPrefix(h1.URL, "http://"), + Replicas: []Location{{Url: strings.TrimPrefix(h2.URL, "http://")}}, + } + assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) { + return nil, assignResult, nil + } + _, err := UploadReaderInChunks(context.Background(), strings.NewReader("hello world"), &ChunkedUploadOption{ + ChunkSize: 1024, + AssignFunc: assignFunc, + }) + if err != nil { + t.Fatal(err) + } + + mu.Lock() + defer mu.Unlock() + require.Len(t, queries, 2) + for _, q := range queries { + require.Equal(t, "replicate", q.Get("type")) + require.Equal(t, ReplicateSourceClient, q.Get(ReplicateSourceParam)) + require.False(t, IsReplicaForward(q)) + } +} + +func TestIsReplicaForward(t *testing.T) { + require.True(t, IsReplicaForward(url.Values{"type": {"replicate"}})) + require.False(t, IsReplicaForward(url.Values{"type": {"replicate"}, "src": {"client"}})) + require.False(t, IsReplicaForward(url.Values{})) +} + +// A volume overload is retried on one fresh assignment and then given up, so +// a busy cluster is not hit again and again while the chunk buffer is held. +// A 429 from a volume server that predates the 503 gets the same treatment. +func TestUploadReaderInChunksReassignsOnceOnOverload(t *testing.T) { + for _, status := range []int{http.StatusServiceUnavailable, http.StatusTooManyRequests} { + t.Run(strconv.Itoa(status), func(t *testing.T) { + testUploadReaderInChunksReassignsOnceOnOverload(t, status) + }) + } +} + +func testUploadReaderInChunksReassignsOnceOnOverload(t *testing.T, status int) { + t.Run("relay", func(t *testing.T) { + _, assigns, err := uploadSingleChunk(t, func(ctx context.Context, data []byte, option *UploadOption) (*UploadResult, error) { + return nil, &uploadStatusError{StatusCode: status, err: errors.New("volume server upload limit")} + }) + if !IsUploadOverloaded(err) { + t.Fatalf("expected the overload to reach the caller, got %v", err) + } + if assigns != 2 { + t.Fatalf("expected 2 assignments, got %d", assigns) + } + }) + + t.Run("fan-out", func(t *testing.T) { + var overloadedPosts int32 + overloaded := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + w.WriteHeader(http.StatusAccepted) + return + } + atomic.AddInt32(&overloadedPosts, 1) + w.Header().Set("Retry-After", "1") + w.WriteHeader(status) + fmt.Fprint(w, `{"error":"volume server upload limit"}`) + })) + defer overloaded.Close() + healthy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + w.WriteHeader(http.StatusAccepted) + return + } + w.WriteHeader(http.StatusCreated) + fmt.Fprint(w, `{"name":"chunk","size":4096}`) + })) + defer healthy.Close() + host := func(s *httptest.Server) string { return strings.TrimPrefix(s.URL, "http://") } + + var assigns int32 + _, err := UploadReaderInChunks(context.Background(), bytes.NewReader(bytes.Repeat([]byte("x"), 4096)), &ChunkedUploadOption{ + ChunkSize: 8 * 1024, + Collection: "test", + AssignFunc: func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) { + n := atomic.AddInt32(&assigns, 1) + // Two holders, so uploadChunk takes the fan-out path. + return nil, &AssignResult{ + Fid: fmt.Sprintf("%d,0a0b0c0d", n), + Url: host(healthy), + Replicas: []Location{{Url: host(overloaded)}}, + Count: 1, + }, nil + }, + }) + if !IsUploadOverloaded(err) { + t.Fatalf("expected the overload to reach the caller, got %v", err) + } + if got := atomic.LoadInt32(&assigns); got != 2 { + t.Fatalf("expected 2 assignments, got %d", got) + } + // One POST per assignment: no same-holder retry under the reassign. + if got := atomic.LoadInt32(&overloadedPosts); got != 2 { + t.Fatalf("overloaded holder saw %d POSTs, want 2", got) + } + }) +} + +// hostCountingClient counts the requests an Uploader sends per host, then +// hands them to inner. +type hostCountingClient struct { + inner HTTPClient + mu sync.Mutex + calls map[string]int +} + +func (c *hostCountingClient) Do(req *http.Request) (*http.Response, error) { + c.mu.Lock() + if c.calls == nil { + c.calls = map[string]int{} + } + c.calls[req.URL.Host]++ + c.mu.Unlock() + return c.inner.Do(req) +} + +func (c *hostCountingClient) callsTo(host string) int { + c.mu.Lock() + defer c.mu.Unlock() + return c.calls[host] +} + +// useGlobalUploaderClient points the process-wide Uploader, which the chunk +// loop writes through, at client for one test. Tests that call it must not +// run in parallel. +func useGlobalUploaderClient(t *testing.T, client HTTPClient) { + t.Helper() + u, err := NewUploader() + if err != nil { + t.Fatal(err) + } + orig := u.httpClient + u.httpClient = client + t.Cleanup(func() { u.httpClient = orig }) +} + +// deleteRecorder is a holder that only answers the cleanup DELETEs the chunk +// loop sends, recording each fid; uploads never reach it in these tests. +type deleteRecorder struct { + srv *httptest.Server + mu sync.Mutex + fids []string +} + +func newDeleteRecorder(t *testing.T) *deleteRecorder { + d := &deleteRecorder{} + d.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + d.mu.Lock() + d.fids = append(d.fids, strings.TrimPrefix(r.URL.Path, "/")) + d.mu.Unlock() + } + w.WriteHeader(http.StatusAccepted) + })) + t.Cleanup(d.srv.Close) + return d +} + +func (d *deleteRecorder) host() string { return strings.TrimPrefix(d.srv.URL, "http://") } + +func (d *deleteRecorder) deleted() []string { + d.mu.Lock() + defer d.mu.Unlock() + return append([]string(nil), d.fids...) +} + +// A holder whose link crawls below the body deadline's rate on every attempt +// is back-pressure, like an overload: the chunk gets one fresh assignment, no +// same-holder retry under it, and then the stall reaches the caller (S3 maps +// it to SlowDown) — not three reassigns of three attempts each. +func TestUploadReaderInChunksReassignsOnceOnBodyDeadline(t *testing.T) { + setUploadBodyMinWait(t, 100*time.Millisecond) + + for _, tc := range []struct { + name string + holders int + }{ + {name: "relay", holders: 1}, + {name: "fan-out", holders: 2}, + } { + t.Run(tc.name, func(t *testing.T) { + client := &hostCountingClient{inner: &tricklingHTTPClient{chunk: 1 << 10, interval: 20 * time.Millisecond}} + useGlobalUploaderClient(t, client) + var holders []*deleteRecorder + for i := 0; i < tc.holders; i++ { + holders = append(holders, newDeleteRecorder(t)) + } + + var assigns int32 + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + start := time.Now() + _, err := UploadReaderInChunks(ctx, bytes.NewReader(incompressibleBytes(t, 64<<10)), &ChunkedUploadOption{ + ChunkSize: 128 << 10, + Collection: "test", + BodyDeadline: true, + AssignFunc: func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) { + n := atomic.AddInt32(&assigns, 1) + result := &AssignResult{Fid: fmt.Sprintf("%d,0a0b0c0d", n), Url: holders[0].host(), Count: 1} + for _, h := range holders[1:] { + result.Replicas = append(result.Replicas, Location{Url: h.host()}) + } + return nil, result, nil + }, + }) + elapsed := time.Since(start) + if !errors.Is(err, ErrUploadStalled) || !IsUploadBackpressure(err) { + t.Fatalf("expected the body deadline stall to reach the caller, got %v after %v", err, elapsed) + } + if got := atomic.LoadInt32(&assigns); got != 2 { + t.Fatalf("expected 2 assignments, got %d", got) + } + for i, h := range holders { + if got := client.callsTo(h.host()); got < 1 || got > 2 { + t.Fatalf("holder %d saw %d uploads over 2 assignments, want at most one per assignment", i, got) + } + } + if elapsed >= 5*time.Second { + t.Fatalf("two deadline cuts took %v", elapsed) + } + }) + } +} + +// A caller that goes away after the chunk's body reached the holders must not +// leave the fid behind: a volume commits on a context that ignores the +// cancel, so each holder of the chunk — not only those that answered — gets a +// cleanup DELETE. +func TestUploadReaderInChunksDeletesChunkOnCallerCancel(t *testing.T) { + for _, tc := range []struct { + name string + holders int + }{ + {name: "relay", holders: 1}, + {name: "fan-out", holders: 2}, + } { + t.Run(tc.name, func(t *testing.T) { + gotBody := make(chan struct{}, tc.holders) + var mu sync.Mutex + deleted := map[string][]string{} // host → fids + var hosts []string + for i := 0; i < tc.holders; i++ { + var srv *httptest.Server + srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + mu.Lock() + host := strings.TrimPrefix(srv.URL, "http://") + deleted[host] = append(deleted[host], strings.TrimPrefix(r.URL.Path, "/")) + mu.Unlock() + w.WriteHeader(http.StatusAccepted) + return + } + _, _ = io.Copy(io.Discard, r.Body) + gotBody <- struct{}{} + <-r.Context().Done() + })) + t.Cleanup(srv.Close) + hosts = append(hosts, strings.TrimPrefix(srv.URL, "http://")) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + for i := 0; i < tc.holders; i++ { + <-gotBody + } + cancel() + }() + _, err := UploadReaderInChunks(ctx, strings.NewReader("hello world"), &ChunkedUploadOption{ + ChunkSize: 1024, + Collection: "test", + AssignFunc: func(ctx context.Context, count int, expectedDataSize uint64) (*VolumeAssignRequest, *AssignResult, error) { + result := &AssignResult{Fid: "3,01abcdef", Url: hosts[0], Count: 1} + for _, h := range hosts[1:] { + result.Replicas = append(result.Replicas, Location{Url: h}) + } + return nil, result, nil + }, + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected the caller's cancel to end the upload, got %v", err) + } + mu.Lock() + defer mu.Unlock() + for _, h := range hosts { + if !slices.Contains(deleted[h], "3,01abcdef") { + t.Fatalf("holder %s got no DELETE for the cancelled chunk, deletes=%v", h, deleted) + } + } + }) + } +} diff --git a/weed/operation/upload_content.go b/weed/operation/upload_content.go index d8f92c07ee..05c04833f8 100644 --- a/weed/operation/upload_content.go +++ b/weed/operation/upload_content.go @@ -67,8 +67,16 @@ type UploadOption struct { GenUploadUrl func(host, fileId string) string // if nil → fallback "http://{host}/{fileId}" FilerJwt security.FilerJwtProvider // credential for proxy chunk URLs; nil → process-wide jwt.filer_signing + // BodyDeadline opts this upload into the body deadline (uploadBodyDeadline): + // a body still unsent past it is cut as back-pressure. Gateways that hold a + // client's chunk buffers set it (S3 chunk uploads, the filer's chunk loop); + // other callers (mount, filer.sync, filer.copy, UploadWithRetry) keep the + // stall watchdog only. + BodyDeadline bool + // stallWatchdogDisarmed turns the watchdog off for this upload's later - // attempts once it fired: a re-arm could burn every retry. + // attempts once it fired: a re-arm could burn every retry. The body + // deadline (uploadBodyDeadline), when opted into, still bounds them. stallWatchdogDisarmed bool } @@ -134,17 +142,60 @@ type uploadStatusError struct { StatusCode int refusedBeforeAppend bool expiredBeforeAppend bool - stalled bool // the stall watchdog cancelled this attempt's request + stalled bool // the stall watchdog or the body deadline cancelled this attempt's request + deadlineCut bool // the body deadline, not the watchdog, made that cut err error } func (e *uploadStatusError) Error() string { return e.err.Error() } func (e *uploadStatusError) Unwrap() error { return e.err } +// Is matches ErrUploadStalled for a request the stall watchdog or the body +// deadline cancelled before any response came back. +func (e *uploadStatusError) Is(target error) bool { + return target == ErrUploadStalled && e.StatusCode == 0 && e.stalled +} + +// ErrUploadStalled matches (with errors.Is) an upload the stall watchdog or the +// body deadline cancelled before the volume server answered. Once its retries +// are spent it is load, not a fault: the caller should back off and try again. +var ErrUploadStalled = errors.New("upload stalled") + +// isBodyDeadlineCut reports whether the body deadline cancelled the upload +// before any response came back. Unlike a watchdog cut, which blames one +// wedged conn and is worth a retry on a fresh one, it says the link to that +// holder crawls: asking it again only holds the buffer longer. +func isBodyDeadlineCut(err error) bool { + var se *uploadStatusError + return errors.As(err, &se) && se.StatusCode == 0 && se.deadlineCut +} + +// IsUploadBackpressure reports whether an upload failed because the cluster +// is short of capacity rather than faulty: a volume server refused it for +// lack of upload budget (IsUploadOverloaded), or its body crawled past the +// body deadline. Such an error gets no same-holder retry and at most one +// fresh assignment per chunk; then the client is told to slow down. +func IsUploadBackpressure(err error) bool { + return IsUploadOverloaded(err) || isBodyDeadlineCut(err) +} + +// IsUploadOverloaded reports whether a volume server refused the upload for +// lack of capacity (429 or 503). Retrying the same holder right away only adds +// to its load, so callers give it at most one fresh assignment. +func IsUploadOverloaded(err error) bool { + var se *uploadStatusError + if errors.As(err, &se) { + return se.StatusCode == http.StatusTooManyRequests || se.StatusCode == http.StatusServiceUnavailable + } + return false +} + // ShouldReassignUpload reports whether an upload error means the client should // ask for a fresh volume assignment and retry on another volume. // -// Transport and 5xx failures retain their existing retry policy. A conflict +// Transport and 5xx failures retain their existing retry policy. A 429 is a +// volume server's upload-limit refusal (volume servers before 503 used it), so +// it gets a fresh assignment like the 503 that replaced it. A conflict // requires explicit proof that the upload was refused before append. func ShouldReassignUpload(err error) bool { if err == nil { @@ -157,7 +208,7 @@ func ShouldReassignUpload(err error) bool { } var se *uploadStatusError if errors.As(err, &se) { - return se.StatusCode == 0 || se.StatusCode >= 500 || (se.StatusCode == http.StatusConflict && se.refusedBeforeAppend) || (se.StatusCode == http.StatusUnauthorized && se.expiredBeforeAppend) + return se.StatusCode == 0 || se.StatusCode >= 500 || se.StatusCode == http.StatusTooManyRequests || (se.StatusCode == http.StatusConflict && se.refusedBeforeAppend) || (se.StatusCode == http.StatusUnauthorized && se.expiredBeforeAppend) } return strings.Contains(err.Error(), "transport") } @@ -409,6 +460,14 @@ func (uploader *Uploader) retriedUploadData(ctx context.Context, prepared *prepa if ctx.Err() != nil { return nil, ctx.Err() } + // An overloaded holder, or one whose body crawled past the body + // deadline, is not asked again from here: the caller's reassign loop + // decides whether one fresh assignment is worth it, so retries stay in + // one place and do not multiply while buffers are held. A watchdog cut + // keeps its retry: it blames one wedged conn, and the retry dials anew. + if IsUploadBackpressure(err) { + return nil, err + } var statusErr *uploadStatusError if errors.As(err, &statusErr) { // A marked-expiry 401 is terminal here only for a direct volume @@ -568,6 +627,7 @@ func (uploader *Uploader) doUploadData(ctx context.Context, prepared *preparedUp Digest: option.Digest, ContentCrc32c: prepared.contentCrc32c, BytesBuffer: option.BytesBuffer, + BodyDeadline: option.BodyDeadline, stallWatchdogDisarmed: option.stallWatchdogDisarmed, }) if uploadResult == nil { @@ -601,6 +661,7 @@ func (uploader *Uploader) doUploadData(ctx context.Context, prepared *preparedUp Digest: option.Digest, ContentCrc32c: prepared.contentCrc32c, BytesBuffer: option.BytesBuffer, + BodyDeadline: option.BodyDeadline, stallWatchdogDisarmed: option.stallWatchdogDisarmed, }) if uploadResult == nil { @@ -726,10 +787,49 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction } }) } + // The body deadline, when the caller opted into it (BodyDeadline), bounds + // the send alongside the watchdog when that is armed: whichever fires + // first cancels. It catches what the watchdog cannot — an unproven host, a + // host whose slow mark stretches the watchdog budget, an attempt after the + // watchdog disarmed — and, since a slow link is not one bad conn, it + // leaves fastUploadHosts alone. + // Each arming checks the body it was armed for, so a timer that fires + // across the inner retry's body swap cannot misjudge the fresh body. + var cutByBodyDeadline atomic.Bool + bodyDeadlineFired := func() { + if !uploadDone.CompareAndSwap(false, true) { + return + } + cutByBodyDeadline.Store(true) + glog.WarningfCtx(ctx, "upload %d bytes to %s still sending its body after %v, cancelling", originalDataSize, option.UploadUrl, uploadBodyDeadline(bodySize)) + cancelUpload() + } + // The deadline runs from before httpClient.Do, so it also counts the dial + // and TLS handshake, not only the body's time on the wire. + armBodyDeadline := func(sentAt *atomic.Int64) *time.Timer { + if !option.BodyDeadline { + return nil + } + return time.AfterFunc(uploadBodyDeadline(bodySize), func() { + if sentAt.Load() == 0 { + bodyDeadlineFired() + } + }) + } + stopBodyDeadline := func(t *time.Timer) { + if t != nil { + t.Stop() + } + } + bodyTimer := armBodyDeadline(bodySentAt) + defer func() { stopBodyDeadline(bodyTimer) }() // print("+") started := time.Now() resp, post_err := uploader.httpClient.Do(req) + // A response, or a failure, ends the send: from here the wait is the + // server's, bounded by the transport's response header timeout. + stopBodyDeadline(bodyTimer) defer util_http.CloseResponse(resp) if post_err != nil { if strings.Contains(post_err.Error(), "connection reset by peer") || @@ -753,8 +853,12 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction if stallTimer != nil && !uploadDone.Load() { stallTimer.Reset(uploadStallTimeout(bodySize, mark.(fastHostMark).bps)) } + if !uploadDone.Load() { + bodyTimer = armBodyDeadline(bodySentAt) + } req.Body = &watchdogBody{ReadCloser: newBody, sentAt: bodySentAt} resp, post_err = uploader.httpClient.Do(req) + stopBodyDeadline(bodyTimer) defer util_http.CloseResponse(resp) } else { glog.V(1).InfofCtx(ctx, "skip inner retry for %s: GetBody returned %v", option.UploadUrl, gbErr) @@ -766,7 +870,8 @@ func (uploader *Uploader) upload_content(ctx context.Context, fillBufferFunction } if post_err != nil { stats.UploadErrorCounter.WithLabelValues("0").Inc() - return nil, &uploadStatusError{StatusCode: 0, stalled: reqCtx.Err() != nil && ctx.Err() == nil, err: fmt.Errorf("upload %s %d bytes to %v: %v", option.Filename, originalDataSize, option.UploadUrl, post_err)} + cut := reqCtx.Err() != nil && ctx.Err() == nil + return nil, &uploadStatusError{StatusCode: 0, stalled: cut, deadlineCut: cut && cutByBodyDeadline.Load(), err: fmt.Errorf("upload %s %d bytes to %v: %v", option.Filename, originalDataSize, option.UploadUrl, post_err)} } // Rate is bounded by elapsed-to-response: the server cannot answer before // the body lands, so this can only understate link speed — a drain-time @@ -867,6 +972,29 @@ func uploadStallTimeout(size, bps int64) time.Duration { return uploadStallMinWait } +var ( + // uploadBodyMinWait is the floor of the body deadline, which only uploads + // that set UploadOption.BodyDeadline get: S3 chunk uploads (relay and + // gateway fan-out) and the filer's chunk loop. + // + // Invariant: it stays above the volume server's volumeClientUploadWaitCap + // (5s), so a holder that parks an opted-in body while it waits for upload + // budget answers 503 before the deadline cuts the request off as a stall. + uploadBodyMinWait = 10 * time.Second + // uploadBodyMinBytesPerSec is the slowest rate a body may cross the link + // at, the same floor a volume server's replica forward allows + // (replicaMinBytesPerSec in weed/topology/store_replicate.go). + uploadBodyMinBytesPerSec int64 = 1 << 20 +) + +// uploadBodyDeadline is the most an opted-in upload's body of size bytes may +// take to send, proven host or not: the floor plus the time the body needs at +// uploadBodyMinBytesPerSec. A body still unsent past it holds the caller's +// buffer on a link too slow to be worth waiting on. +func uploadBodyDeadline(size int64) time.Duration { + return uploadBodyMinWait + time.Duration(size*1000/uploadBodyMinBytesPerSec)*time.Millisecond +} + // uploadObservedBps returns the wire rate a completed upload proved on its // host, or 0 when the body was too small to measure. Elapsed-to-response can // only understate the link's speed, which keeps the mark — and the stall diff --git a/weed/operation/upload_content_test.go b/weed/operation/upload_content_test.go index 2e705386d7..6e6202f183 100644 --- a/weed/operation/upload_content_test.go +++ b/weed/operation/upload_content_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "crypto/md5" + crand "crypto/rand" "encoding/base64" "errors" "fmt" @@ -67,6 +68,7 @@ func TestShouldReassignUpload(t *testing.T) { {name: "no response (transport)", err: &uploadStatusError{StatusCode: 0, err: fmt.Errorf("dial tcp: no such host")}, want: true}, {name: "500 replica write failed", err: &uploadStatusError{StatusCode: 500, err: fmt.Errorf("failed to write to replicas")}, want: true}, {name: "503 service unavailable", err: &uploadStatusError{StatusCode: 503, err: fmt.Errorf("busy")}, want: true}, + {name: "429 upload limit (volume servers before 503)", err: &uploadStatusError{StatusCode: http.StatusTooManyRequests, err: fmt.Errorf("upload limit")}, want: true}, {name: "proven conflict", err: &uploadStatusError{StatusCode: http.StatusConflict, refusedBeforeAppend: true, err: errors.New("read only")}, want: true}, {name: "unmarked conflict", err: &uploadStatusError{StatusCode: http.StatusConflict, err: errors.New("read only")}, want: false}, {name: "400 bad request", err: &uploadStatusError{StatusCode: 400, err: fmt.Errorf("bad needle")}, want: false}, @@ -1036,3 +1038,406 @@ func TestUploadWithRetryForeverStopsOnReadOnlyVerdict(t *testing.T) { t.Fatal("RetryForever kept retrying a read-only verdict") } } + +func TestIsUploadOverloaded(t *testing.T) { + testCases := []struct { + name string + err error + want bool + }{ + {name: "429", err: &uploadStatusError{StatusCode: http.StatusTooManyRequests, err: errors.New("slow down")}, want: true}, + {name: "503", err: &uploadStatusError{StatusCode: http.StatusServiceUnavailable, err: errors.New("upload limit")}, want: true}, + {name: "wrapped 503", err: fmt.Errorf("upload chunk: %w", &uploadStatusError{StatusCode: http.StatusServiceUnavailable, err: errors.New("upload limit")}), want: true}, + {name: "500", err: &uploadStatusError{StatusCode: http.StatusInternalServerError, err: errors.New("disk full")}, want: false}, + {name: "no response", err: &uploadStatusError{StatusCode: 0, err: errors.New("dial tcp: refused")}, want: false}, + {name: "plain error", err: errors.New("503 service unavailable"), want: false}, + {name: "nil", err: nil, want: false}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if got := IsUploadOverloaded(tc.err); got != tc.want { + t.Fatalf("IsUploadOverloaded(%v) = %v, want %v", tc.err, got, tc.want) + } + }) + } +} + +// Only a request the stall watchdog cancelled before any response arrived is +// a stall; a dial failure has the same status 0 and is not. +func TestUploadStalledMatchesErrUploadStalled(t *testing.T) { + testCases := []struct { + name string + err error + want bool + }{ + {name: "stalled before a response", err: &uploadStatusError{StatusCode: 0, stalled: true, err: errors.New("context canceled")}, want: true}, + {name: "wrapped stall", err: fmt.Errorf("upload chunk: %w", &uploadStatusError{StatusCode: 0, stalled: true, err: errors.New("context canceled")}), want: true}, + {name: "dial failure", err: &uploadStatusError{StatusCode: 0, err: errors.New("dial tcp: refused")}, want: false}, + {name: "stalled reading a response", err: &uploadStatusError{StatusCode: http.StatusCreated, stalled: true, err: errors.New("context canceled")}, want: false}, + {name: "plain error", err: errors.New("stalled"), want: false}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if got := errors.Is(tc.err, ErrUploadStalled); got != tc.want { + t.Fatalf("errors.Is(%v, ErrUploadStalled) = %v, want %v", tc.err, got, tc.want) + } + }) + } +} + +// An overloaded holder is not hammered again from the same caller while it +// holds the chunk buffer: the overload goes straight back to the one place +// that decides on a reassign. Other failures keep their same-URL retries. +func TestRetriedUploadDataDoesNotRetryOverload(t *testing.T) { + testCases := []struct { + name string + status int + wantPosts int32 + }{ + {name: "503 overload", status: http.StatusServiceUnavailable, wantPosts: 1}, + {name: "429 overload", status: http.StatusTooManyRequests, wantPosts: 1}, + {name: "500 keeps its retries", status: http.StatusInternalServerError, wantPosts: 3}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var posts int32 + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&posts, 1) + w.Header().Set("Retry-After", "1") + w.WriteHeader(tc.status) + fmt.Fprint(w, `{"error":"volume server upload limit"}`) + })) + defer holder.Close() + + _, err := newUploader(http.DefaultClient).UploadData(context.Background(), []byte("hello"), &UploadOption{ + UploadUrl: holder.URL + "/3,01637037d6", + Filename: "test.bin", + }) + if err == nil { + t.Fatal("expected the upload to fail") + } + if got := atomic.LoadInt32(&posts); got != tc.wantPosts { + t.Fatalf("holder saw %d POSTs, want %d", got, tc.wantPosts) + } + }) + } +} + +// tricklingHTTPClient drains the request body chunk bytes per interval, the +// way a degraded link does, and answers 201 once it has it all. It honours the +// request ctx between reads, as a transport aborts a cancelled write. With +// resetFirstAfter set, the first call instead drains at once, holds that long +// and fails with a connection reset, which triggers the inner rewind retry. +type tricklingHTTPClient struct { + chunk int + interval time.Duration + resetFirstAfter time.Duration + calls int32 +} + +func (c *tricklingHTTPClient) Do(req *http.Request) (*http.Response, error) { + defer req.Body.Close() + if atomic.AddInt32(&c.calls, 1) == 1 && c.resetFirstAfter > 0 { + _, _ = io.Copy(io.Discard, req.Body) + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case <-time.After(c.resetFirstAfter): + } + return nil, errors.New("write tcp: connection reset by peer") + } + buf := make([]byte, c.chunk) + for { + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case <-time.After(c.interval): + } + if _, err := io.ReadFull(req.Body, buf); err != nil { + break + } + } + return &http.Response{ + StatusCode: http.StatusCreated, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"size":1}`)), + }, nil +} + +// setUploadBodyMinWait shrinks the body deadline floor for one test. Tests +// that call it must not run in parallel. +func setUploadBodyMinWait(t *testing.T, d time.Duration) { + orig := uploadBodyMinWait + uploadBodyMinWait = d + t.Cleanup(func() { uploadBodyMinWait = orig }) +} + +// incompressibleBytes returns n random bytes, so the upload is not gzipped +// down to a body too small to trickle. +func incompressibleBytes(t *testing.T, n int) []byte { + b := make([]byte, n) + if _, err := crand.Read(b); err != nil { + t.Fatal(err) + } + return b +} + +func TestUploadBodyDeadlineScalesWithSize(t *testing.T) { + if d := uploadBodyDeadline(0); d != uploadBodyMinWait { + t.Fatalf("uploadBodyDeadline(0) = %v, want %v", d, uploadBodyMinWait) + } + if d := uploadBodyDeadline(10 << 20); d != uploadBodyMinWait+10*time.Second { + t.Fatalf("uploadBodyDeadline(10MiB) = %v, want %v", d, uploadBodyMinWait+10*time.Second) + } +} + +// A host that never proved a rate gets no stall watchdog, but a body crawling +// far below the minimum rate is still cut, as a stall the caller can reassign. +func TestUploadBodyDeadlineCutsTrickleToUnprovenHost(t *testing.T) { + setUploadBodyMinWait(t, 100*time.Millisecond) + + client := &tricklingHTTPClient{chunk: 1 << 10, interval: 50 * time.Millisecond} + uploader := newUploader(client) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + start := time.Now() + _, err := uploader.UploadData(ctx, incompressibleBytes(t, 64<<10), &UploadOption{ + UploadUrl: "http://slow-host:8080/1,deadbeef", + MaxAttempts: 1, + BodyDeadline: true, + }) + elapsed := time.Since(start) + if err == nil { + t.Fatalf("a trickling body must be cut at the body deadline, got success after %v", elapsed) + } + if elapsed >= time.Second { + t.Fatalf("body deadline cut the upload after %v, want under 1s", elapsed) + } + if !ShouldReassignUpload(err) { + t.Fatalf("a body deadline cut must be reassignable: %v", err) + } + if !errors.Is(err, ErrUploadStalled) { + t.Fatalf("a body deadline cut must read as a stall: %v", err) + } +} + +// slowCommitHTTPClient drains the request body at once, then takes commitFor +// to answer 201, giving up as a transport would if the request ctx is +// cancelled while it commits. +type slowCommitHTTPClient struct { + commitFor time.Duration +} + +func (c *slowCommitHTTPClient) Do(req *http.Request) (*http.Response, error) { + _, _ = io.Copy(io.Discard, req.Body) + _ = req.Body.Close() + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case <-time.After(c.commitFor): + } + return &http.Response{ + StatusCode: http.StatusCreated, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(`{"size":1}`)), + }, nil +} + +// Once the body is sent the wait is the server's commit, bounded by the +// transport's response header timeout, not by the body deadline. +func TestUploadBodyDeadlineAllowsSlowCommit(t *testing.T) { + setUploadBodyMinWait(t, 100*time.Millisecond) + + client := &slowCommitHTTPClient{commitFor: 300 * time.Millisecond} + uploader := newUploader(client) + + result, err := uploader.UploadData(context.Background(), incompressibleBytes(t, 64<<10), &UploadOption{ + UploadUrl: "http://slow-host:8080/1,deadbeef", + MaxAttempts: 1, + BodyDeadline: true, + }) + if err != nil || result.RetryCount != 0 { + t.Fatalf("a slow commit after the body is sent must not be cut: result=%+v err=%v", result, err) + } +} + +// A host marked at a slow rate gets a stall budget eight times that slow, so +// the body deadline is what bounds it — and it leaves the mark alone, since +// only the watchdog blames a pooled conn. +func TestUploadBodyDeadlineCutsSlowProvenHost(t *testing.T) { + setUploadBodyMinWait(t, 100*time.Millisecond) + + const host = "slow-host:8080" + const size = 300 << 10 + slowMark := fastHostMark{at: time.Now().UnixNano(), bps: 100 << 10} + if budget := uploadStallTimeout(size, slowMark.bps); budget < 10*time.Second { + t.Fatalf("test setup: watchdog budget %v must dwarf the body deadline", budget) + } + client := &tricklingHTTPClient{chunk: 1 << 10, interval: 50 * time.Millisecond} + uploader := newUploader(client) + uploader.fastUploadHosts.Store(host, slowMark) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + start := time.Now() + _, err := uploader.UploadData(ctx, incompressibleBytes(t, size), &UploadOption{ + UploadUrl: "http://" + host + "/1,deadbeef", + MaxAttempts: 1, + BodyDeadline: true, + }) + elapsed := time.Since(start) + if !errors.Is(err, ErrUploadStalled) { + t.Fatalf("a slow host's trickle must be cut as a stall at the body deadline, got %v after %v", err, elapsed) + } + if elapsed >= time.Second { + t.Fatalf("body deadline cut the upload after %v, want under 1s", elapsed) + } + if mark, ok := uploader.fastUploadHosts.Load(host); !ok || mark.(fastHostMark) != slowMark { + t.Fatalf("the body deadline must not touch the host's rate mark, got %+v (present=%v)", mark, ok) + } +} + +// The inner connection-reset retry sends a fresh body, which gets its own +// deadline: the first attempt's deadline expired while its body was already +// sent, so without a re-arm the retry would trickle unbounded. +func TestUploadBodyDeadlineRearmsOnConnectionReset(t *testing.T) { + setUploadBodyMinWait(t, 50*time.Millisecond) + + client := &tricklingHTTPClient{chunk: 1 << 10, interval: 20 * time.Millisecond, resetFirstAfter: 200 * time.Millisecond} + uploader := newUploader(client) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + start := time.Now() + _, err := uploader.UploadData(ctx, incompressibleBytes(t, 64<<10), &UploadOption{ + UploadUrl: "http://slow-host:8080/1,deadbeef", + MaxAttempts: 1, + BodyDeadline: true, + }) + elapsed := time.Since(start) + if got := atomic.LoadInt32(&client.calls); got != 2 { + t.Fatalf("Do calls = %d, want the reset plus its inner retry", got) + } + if !errors.Is(err, ErrUploadStalled) { + t.Fatalf("the inner retry's trickle must be cut at its own deadline, got %v after %v", err, elapsed) + } + if elapsed >= time.Second { + t.Fatalf("inner retry was cut after %v, want under 1s", elapsed) + } +} + +// The body deadline is opt-in: an upload that did not ask for it (mount, +// filer.sync, filer.copy, UploadWithRetry) keeps today's watchdog-only +// behaviour, so a body trickling far below the deadline's rate to an unproven +// host — where no watchdog arms — runs to completion. +func TestUploadWithoutBodyDeadlineIsNotCut(t *testing.T) { + setUploadBodyMinWait(t, 20*time.Millisecond) + + client := &tricklingHTTPClient{chunk: 1 << 10, interval: 10 * time.Millisecond} + uploader := newUploader(client) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + start := time.Now() + result, err := uploader.UploadData(ctx, incompressibleBytes(t, 16<<10), &UploadOption{ + UploadUrl: "http://slow-host:8080/1,deadbeef", + MaxAttempts: 1, + }) + elapsed := time.Since(start) + if err != nil || result.RetryCount != 0 { + t.Fatalf("an opted-out trickle must not be cut: result=%+v err=%v after %v", result, err, elapsed) + } + if deadline := uploadBodyDeadline(16 << 10); elapsed <= deadline { + t.Fatalf("test setup: the trickle took %v, must outlast the %v deadline it would get opted in", elapsed, deadline) + } +} + +// The gateway fan-out writes each holder through retriedUploadData with its +// default attempts. A body deadline cut is back-pressure, not a wedged conn: +// it goes straight back to the chunk loop, which decides on one reassign, so +// a trickling holder is written once per assignment. A watchdog cut keeps its +// same-holder retry on a fresh conn, and the body deadline then bounds that +// retry — still ending as a reassignable stall (S3 SlowDown). +func TestUploadBodyDeadlineStallsEveryFanOutAttempt(t *testing.T) { + setUploadBodyMinWait(t, 50*time.Millisecond) + origStall := uploadStallMinWait + uploadStallMinWait = 20 * time.Millisecond + t.Cleanup(func() { uploadStallMinWait = origStall }) + + testCases := []struct { + name string + proven bool // the host carries a fast mark, so the watchdog arms first + wantCalls int32 + }{ + {name: "unproven holder: one call, cut at the deadline", proven: false, wantCalls: 1}, + {name: "proven holder: watchdog cut retried once, then cut at the deadline", proven: true, wantCalls: 2}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + const host = "holder:8080" + client := &tricklingHTTPClient{chunk: 1 << 10, interval: 20 * time.Millisecond} + uploader := newUploader(client) + if tc.proven { + markHostFast(uploader, host) + } + option := &UploadOption{UploadUrl: fmt.Sprintf("http://%s/3,01637037d6?type=replicate&%s=%s", host, ReplicateSourceParam, ReplicateSourceClient), BodyDeadline: true} + prepared, err := prepareUploadData(incompressibleBytes(t, 64<<10), option) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + start := time.Now() + _, err = uploader.retriedUploadData(ctx, prepared, option) + elapsed := time.Since(start) + if got := atomic.LoadInt32(&client.calls); got != tc.wantCalls { + t.Fatalf("Do calls = %d, want %d", got, tc.wantCalls) + } + if !errors.Is(err, ErrUploadStalled) || !ShouldReassignUpload(err) || !IsUploadBackpressure(err) { + t.Fatalf("a holder trickling to the deadline must end as a reassignable back-pressure stall, got %v after %v", err, elapsed) + } + if _, ok := uploader.fastUploadHosts.Load(host); ok { + t.Fatalf("no fast mark may survive: the watchdog cut clears it and the deadline never sets one") + } + if elapsed >= 2*time.Second { + t.Fatalf("cut attempts took %v, want well under 2s", elapsed) + } + }) + } +} + +// Only a body deadline cut and an overload are back-pressure; a watchdog cut +// (one wedged conn) and other failures keep their retry policy. +func TestIsUploadBackpressure(t *testing.T) { + testCases := []struct { + name string + err error + want bool + }{ + {name: "503 overload", err: &uploadStatusError{StatusCode: http.StatusServiceUnavailable, err: errors.New("limit")}, want: true}, + {name: "429 overload", err: &uploadStatusError{StatusCode: http.StatusTooManyRequests, err: errors.New("limit")}, want: true}, + {name: "body deadline cut", err: &uploadStatusError{StatusCode: 0, stalled: true, deadlineCut: true, err: errors.New("context canceled")}, want: true}, + {name: "wrapped body deadline cut", err: fmt.Errorf("upload chunk: %w", &uploadStatusError{StatusCode: 0, stalled: true, deadlineCut: true, err: errors.New("context canceled")}), want: true}, + {name: "watchdog cut", err: &uploadStatusError{StatusCode: 0, stalled: true, err: errors.New("context canceled")}, want: false}, + {name: "500 fault", err: &uploadStatusError{StatusCode: http.StatusInternalServerError, err: errors.New("disk")}, want: false}, + {name: "plain error", err: errors.New("deadline"), want: false}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if got := IsUploadBackpressure(tc.err); got != tc.want { + t.Fatalf("IsUploadBackpressure(%v) = %v, want %v", tc.err, got, tc.want) + } + }) + } + // Both kinds of cut still read as a stall and stay reassignable. + for _, err := range []error{ + &uploadStatusError{StatusCode: 0, stalled: true, deadlineCut: true, err: errors.New("context canceled")}, + &uploadStatusError{StatusCode: 0, stalled: true, err: errors.New("context canceled")}, + } { + if !errors.Is(err, ErrUploadStalled) || !ShouldReassignUpload(err) { + t.Fatalf("%+v must match ErrUploadStalled and be reassignable", err) + } + } +} diff --git a/weed/s3api/s3api_circuit_breaker.go b/weed/s3api/s3api_circuit_breaker.go index ecdf736831..366f67f6b1 100644 --- a/weed/s3api/s3api_circuit_breaker.go +++ b/weed/s3api/s3api_circuit_breaker.go @@ -106,13 +106,8 @@ func (cb *CircuitBreaker) Limit(f func(w http.ResponseWriter, r *http.Request), if cb.s3a != nil && (action == s3_constants.ACTION_WRITE) && (cb.s3a.option.ConcurrentUploadLimit != 0 || cb.s3a.option.ConcurrentFileUploadLimit != 0) { - // Get content length, default to 0 if not provided - contentLength := r.ContentLength - if contentLength < 0 { - contentLength = 0 - } - - if !cb.waitForUploadSlot(w, r, contentLength) { + charged := cb.uploadCharge(r) + if !cb.waitForUploadSlot(w, r, charged) { return } defer func() { @@ -120,7 +115,7 @@ func (cb *CircuitBreaker) Limit(f func(w http.ResponseWriter, r *http.Request), defer cb.s3a.inFlightDataLimitCond.L.Unlock() // Decrement counters newUploads := atomic.AddInt64(&cb.s3a.inFlightUploads, -1) - newSize := atomic.AddInt64(&cb.s3a.inFlightDataSize, -contentLength) + newSize := atomic.AddInt64(&cb.s3a.inFlightDataSize, -charged) // Update metrics stats.S3InFlightUploadCountGauge.Set(float64(newUploads)) stats.S3InFlightUploadBytesGauge.Set(float64(newSize)) @@ -166,13 +161,37 @@ func (cb *CircuitBreaker) Limit(f func(w http.ResponseWriter, r *http.Request), }, Action(action) } -func (cb *CircuitBreaker) waitForUploadSlot(w http.ResponseWriter, r *http.Request, contentLength int64) bool { +// declaredUploadSize is the body length r declares: Content-Length, or, for an +// aws-chunked body only, X-Amz-Decoded-Content-Length when Content-Length is +// unknown, so a client-controlled header cannot lower what a request that +// declares its length is charged. getRequestDataReader holds an aws-chunked +// body to that length; no other body is decoded, so for one the header proves +// nothing and is ignored. -1 when neither is known. +func declaredUploadSize(r *http.Request) int64 { + declared := r.ContentLength + if declared < 0 && isAwsChunkedUpload(r) { + if decoded, ok := decodedContentLength(r); ok { + declared = decoded + } + } + return declared +} + +// uploadCharge is the bytes r reserves against the in-flight upload budget; +// see util.GatewayUploadCharge. +func (cb *CircuitBreaker) uploadCharge(r *http.Request) int64 { + return util.GatewayUploadCharge(declaredUploadSize(r), int64(cb.s3a.uploadChunkSize()), cb.s3a.option.ConcurrentUploadLimit) +} + +// waitForUploadSlot reserves charged bytes and one upload slot, or writes the +// rejection and returns false. The caller releases exactly charged. +func (cb *CircuitBreaker) waitForUploadSlot(w http.ResponseWriter, r *http.Request, charged int64) bool { s3a := cb.s3a s3a.inFlightDataLimitCond.L.Lock() err := util.WaitUntil(r.Context(), s3a.inFlightDataLimitCond, s3a.option.InflightUploadDataTimeout, func() bool { inFlightDataSize := atomic.LoadInt64(&s3a.inFlightDataSize) - if s3a.option.ConcurrentUploadLimit != 0 && inFlightDataSize > s3a.option.ConcurrentUploadLimit { - glog.V(4).Infof("wait because inflight data %d > %d", inFlightDataSize, s3a.option.ConcurrentUploadLimit) + if !util.UploadAdmits(inFlightDataSize, charged, s3a.option.ConcurrentUploadLimit) { + glog.V(4).Infof("wait because inflight data %d + %d > %d", inFlightDataSize, charged, s3a.option.ConcurrentUploadLimit) return false } inFlightUploads := atomic.LoadInt64(&s3a.inFlightUploads) @@ -185,7 +204,7 @@ func (cb *CircuitBreaker) waitForUploadSlot(w http.ResponseWriter, r *http.Reque if err == nil { // Increment counters newUploads := atomic.AddInt64(&s3a.inFlightUploads, 1) - newSize := atomic.AddInt64(&s3a.inFlightDataSize, contentLength) + newSize := atomic.AddInt64(&s3a.inFlightDataSize, charged) // Update metrics stats.S3InFlightUploadCountGauge.Set(float64(newUploads)) stats.S3InFlightUploadBytesGauge.Set(float64(newSize)) @@ -215,6 +234,15 @@ func (cb *CircuitBreaker) waitForUploadSlot(w http.ResponseWriter, r *http.Reque func (cb *CircuitBreaker) limit(r *http.Request, bucket string, action string) (rollback []func(), errCode s3err.ErrorCode) { + // The byte counters count what the request declares, as they always have, + // so a bucket bytes limit still rejects one PUT larger than it. An unknown + // length counts one chunk rather than -1, which would decrement them; the + // same value is added and rolled back. + requestBytes := max(r.ContentLength, 0) + if cb.s3a != nil { + requestBytes = util.CountedUploadSize(declaredUploadSize(r), int64(cb.s3a.uploadChunkSize())) + } + //bucket simultaneous request count bucketCountRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(bucket, action, s3_constants.LimitTypeCount), 1, s3err.ErrTooManyRequest) if bucketCountRollBack != nil { @@ -225,7 +253,7 @@ func (cb *CircuitBreaker) limit(r *http.Request, bucket string, action string) ( } //bucket simultaneous request content bytes - bucketContentLengthRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(bucket, action, s3_constants.LimitTypeBytes), r.ContentLength, s3err.ErrRequestBytesExceed) + bucketContentLengthRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(bucket, action, s3_constants.LimitTypeBytes), requestBytes, s3err.ErrRequestBytesExceed) if bucketContentLengthRollBack != nil { rollback = append(rollback, bucketContentLengthRollBack) } @@ -243,7 +271,7 @@ func (cb *CircuitBreaker) limit(r *http.Request, bucket string, action string) ( } //global simultaneous request content bytes - globalContentLengthRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(action, s3_constants.LimitTypeBytes), r.ContentLength, s3err.ErrRequestBytesExceed) + globalContentLengthRollBack, errCode := cb.loadCounterAndCompare(s3_constants.Concat(action, s3_constants.LimitTypeBytes), requestBytes, s3err.ErrRequestBytesExceed) if globalContentLengthRollBack != nil { rollback = append(rollback, globalContentLengthRollBack) } diff --git a/weed/s3api/s3api_circuit_breaker_test.go b/weed/s3api/s3api_circuit_breaker_test.go index 0749d5e9d0..5814c542ae 100644 --- a/weed/s3api/s3api_circuit_breaker_test.go +++ b/weed/s3api/s3api_circuit_breaker_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + "github.com/gorilla/mux" "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" @@ -313,12 +314,21 @@ func TestLimitUploadSlotWait(t *testing.T) { t.Run("freed bytes admit every waiter that fits", func(t *testing.T) { cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 100, InflightUploadDataTimeout: time.Minute}) + // A large upload is charged at most half the budget, so two of them + // fill it and the waiters below have to wait for a release. release := holdUploadSlot(t, cb, 1000) + releaseOther := holdUploadSlot(t, cb, 1000) + defer releaseOther() + if got := atomic.LoadInt64(&cb.s3a.inFlightDataSize); got != 100 { + t.Fatalf("in-flight %d, want the budget full at 100", got) + } var admitted sync.WaitGroup + var entered atomic.Int32 admitted.Add(2) proceed := make(chan struct{}) h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { + entered.Add(1) admitted.Done() <-proceed }, s3_constants.ACTION_WRITE) @@ -331,6 +341,9 @@ func TestLimitUploadSlotWait(t *testing.T) { }() } time.Sleep(50 * time.Millisecond) + if n := entered.Load(); n != 0 { + t.Fatalf("%d waiters entered a full budget", n) + } release() bothIn := make(chan struct{}) @@ -378,3 +391,160 @@ func TestLimitUploadSlotRejectsStalledBody(t *testing.T) { t.Fatalf("got %d close=%v, want 503 with Connection: close", resp.StatusCode, resp.Close) } } + +// putThroughLimit sends req through a write-limited handler and reports the +// status and the in-flight bytes seen while the handler ran (-1 if it did not). +func putThroughLimit(cb *CircuitBreaker, req *http.Request) (code int, body string, inFlight int64) { + inFlight = -1 + h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { + inFlight = atomic.LoadInt64(&cb.s3a.inFlightDataSize) + }, s3_constants.ACTION_WRITE) + rec := httptest.NewRecorder() + h(rec, req) + return rec.Code, rec.Body.String(), inFlight +} + +func TestLimitUploadSlotNoOvershoot(t *testing.T) { + cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 10, InflightUploadDataTimeout: 50 * time.Millisecond}) + cb.s3a.inFlightDataSize = 8 + code, body, _ := putThroughLimit(cb, putRequest(context.Background(), 4)) + if code != http.StatusServiceUnavailable || !strings.Contains(body, "SlowDown") { + t.Fatalf("got %d %q, want 503 SlowDown", code, body) + } + if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 8 { + t.Fatalf("in-flight bytes %d, want 8", n) + } +} + +func TestLimitUploadSlotChargesUnknownLength(t *testing.T) { + const limit = 1 << 20 + newCB := func(inFlight int64) *CircuitBreaker { + cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: limit, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond}) + cb.s3a.inFlightDataSize = inFlight + return cb + } + unknown := func() *http.Request { + req := putRequest(context.Background(), 1) + req.ContentLength = -1 + return req + } + + // an unknown length is charged half the budget, not 0 and not a 4 MiB chunk + cb := newCB(600 << 10) + if code, _, _ := putThroughLimit(cb, unknown()); code != http.StatusServiceUnavailable { + t.Fatalf("got %d, want 503", code) + } + cb = newCB(0) + code, _, inFlight := putThroughLimit(cb, unknown()) + if code != http.StatusOK || inFlight != limit/2 { + t.Fatalf("idle: got %d in-flight %d, want 200 and %d", code, inFlight, limit/2) + } + if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 0 { + t.Fatalf("in-flight bytes %d after release, want 0", n) + } +} + +func TestLimitUploadSlotUsesDecodedLengthOnlyWhenUnknown(t *testing.T) { + newCB := func() *CircuitBreaker { + return newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 1 << 30, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond}) + } + req := putRequest(context.Background(), 1) + req.ContentLength = 5000 + req.Header.Set("X-Amz-Decoded-Content-Length", "4096") + if _, _, inFlight := putThroughLimit(newCB(), req); inFlight != 5000 { + t.Fatalf("known length: in-flight %d, want 5000", inFlight) + } + req = putRequest(context.Background(), 1) + req.ContentLength = -1 + req.Header.Set("X-Amz-Content-Sha256", streamingUnsignedPayload) + req.Header.Set("X-Amz-Decoded-Content-Length", "4096") + if _, _, inFlight := putThroughLimit(newCB(), req); inFlight != 4096 { + t.Fatalf("unknown length, aws-chunked: in-flight %d, want 4096", inFlight) + } + // Only an aws-chunked body is held to the header, so on any other body it + // cannot lower the charge below the one chunk an unknown length costs. + req = putRequest(context.Background(), 1) + req.ContentLength = -1 + req.Header.Set("X-Amz-Decoded-Content-Length", "0") + if _, _, inFlight := putThroughLimit(newCB(), req); inFlight != 4<<20 { + t.Fatalf("unknown length, plain body: in-flight %d, want one 4 MiB chunk", inFlight) + } +} + +func TestLimitUploadSlotAdmitsHugeObjectBesideSmallOnes(t *testing.T) { + cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 64 << 20, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond}) + cb.s3a.inFlightDataSize = 32 << 20 + req := putRequest(context.Background(), 1) + req.ContentLength = 5 << 30 + code, _, inFlight := putThroughLimit(cb, req) + if code != http.StatusOK || inFlight != 48<<20 { + t.Fatalf("got %d in-flight %d, want 200 and %d", code, inFlight, 48<<20) + } +} + +// The breaker's byte counters keep their meaning: what the request declares, +// with an unknown length counted as one chunk — not the upload budget's +// charge, which caps at four chunks and at half the budget. +func TestLimitBucketBytesCounterSymmetricForUnknownLength(t *testing.T) { + for _, tc := range []struct { + name string + contentLength int64 + want int64 + }{ + {name: "unknown length counts one chunk", contentLength: -1, want: 4 << 20}, + {name: "declared length counts in full", contentLength: 64 << 20, want: 64 << 20}, + } { + t.Run(tc.name, func(t *testing.T) { + // A 1 MiB budget charges either request 512 KiB; the counter must not. + cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 1 << 20, MaxMB: 4}) + cb.Enabled = true + key := s3_constants.Concat(s3_constants.ACTION_WRITE, s3_constants.LimitTypeBytes) + cb.limitations[key] = 1 << 40 + req := putRequest(context.Background(), 1) + req.ContentLength = tc.contentLength + var during, budget int64 + h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { + during = atomic.LoadInt64(cb.counters[key]) + budget = atomic.LoadInt64(&cb.s3a.inFlightDataSize) + }, s3_constants.ACTION_WRITE) + h(httptest.NewRecorder(), req) + if during != tc.want { + t.Fatalf("counter during request %d, want %d", during, tc.want) + } + if budget != 512<<10 { + t.Fatalf("upload budget charge %d, want %d", budget, 512<<10) + } + if n := atomic.LoadInt64(cb.counters[key]); n != 0 { + t.Fatalf("counter after request %d, want 0", n) + } + }) + } +} + +// A bucket bytes limit still rejects one PUT that declares more than it +// allows, even though the upload budget charges that PUT far less. +func TestLimitBucketBytesRejectsDeclaredOversizedPut(t *testing.T) { + cb := newUploadLimitedCircuitBreaker(&S3ApiServerOption{ConcurrentUploadLimit: 1 << 30, MaxMB: 4}) + cb.Enabled = true + key := s3_constants.Concat("b", s3_constants.ACTION_WRITE, s3_constants.LimitTypeBytes) + cb.limitations[key] = 16 << 20 + req := mux.SetURLVars(putRequest(context.Background(), 1), map[string]string{"bucket": "b"}) + req.ContentLength = 64 << 20 + ran := false + h, _ := cb.Limit(func(w http.ResponseWriter, r *http.Request) { ran = true }, s3_constants.ACTION_WRITE) + rec := httptest.NewRecorder() + h(rec, req) + if ran { + t.Fatal("a PUT declaring 64 MiB must not pass a 16 MiB bucket bytes limit") + } + want := s3err.GetAPIError(s3err.ErrRequestBytesExceed) + if rec.Code != want.HTTPStatusCode || !strings.Contains(rec.Body.String(), want.Code) { + t.Fatalf("got %d %q, want %d %s", rec.Code, rec.Body.String(), want.HTTPStatusCode, want.Code) + } + if n := atomic.LoadInt64(cb.counters[key]); n != 0 { + t.Fatalf("bucket counter after rejection %d, want 0", n) + } + if n := atomic.LoadInt64(&cb.s3a.inFlightDataSize); n != 0 { + t.Fatalf("upload budget after rejection %d, want 0", n) + } +} diff --git a/weed/s3api/s3api_handlers_failover_test.go b/weed/s3api/s3api_handlers_failover_test.go index 4606d6b23d..c5afc39370 100644 --- a/weed/s3api/s3api_handlers_failover_test.go +++ b/weed/s3api/s3api_handlers_failover_test.go @@ -187,3 +187,48 @@ func TestFailoverDoesNotBlameFilersForTheCallersExpiredBudget(t *testing.T) { t.Errorf("the second filer was tried %d times with no budget left to answer in", n) } } + +// hangingAssignFiler answers AssignVolume only when the caller gives up, +// standing in for a filer still waiting on the master for a volume. +type hangingAssignFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + calls atomic.Int32 +} + +func (f *hangingAssignFiler) AssignVolume(ctx context.Context, _ *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) { + f.calls.Add(1) + <-ctx.Done() + return nil, ctx.Err() +} + +// An S3 client that disconnects while its chunk waits for a volume cancels the +// assignment. That cancel must not count against the filer, or a few clients +// going away would open the circuit on healthy filers, and it must not send the +// same dead request on to the next filer. +func TestAssignUploadVolumeDoesNotBlameFilersForAClientThatLeft(t *testing.T) { + first := &hangingAssignFiler{} + second := &hangingAssignFiler{} + firstAddr := startFakeFiler(t, first) + secondAddr := startFakeFiler(t, second) + s3a := newFailoverTestServer(t, firstAddr, secondAddr) + + // More attempts than the three failures it takes to open the circuit. + for attempt := 0; attempt < 5; attempt++ { + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(50*time.Millisecond, cancel) + _, err := s3a.assignUploadVolume(ctx, &filer_pb.AssignVolumeRequest{Count: 1}) + cancel() + if err == nil { + t.Fatalf("attempt %d: want the cancelled assignment surfaced as an error", attempt) + } + } + + for _, addr := range []pb.ServerAddress{firstAddr, secondAddr} { + if s3a.filerClient.ShouldSkipUnhealthyFiler(addr) { + t.Errorf("filer %s was flagged unhealthy because the client went away", addr) + } + } + if n := second.calls.Load(); n != 0 { + t.Errorf("the second filer was asked %d times for a client that had already gone", n) + } +} diff --git a/weed/s3api/s3api_object_handlers_copy_unified.go b/weed/s3api/s3api_object_handlers_copy_unified.go index 6f8d050da4..c47d21a3f5 100644 --- a/weed/s3api/s3api_object_handlers_copy_unified.go +++ b/weed/s3api/s3api_object_handlers_copy_unified.go @@ -6,6 +6,7 @@ import ( "net/http" "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/operation" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" @@ -85,6 +86,13 @@ func (s3a *S3ApiServer) mapCopyErrorToS3Error(err error) s3err.ErrorCode { return s3err.ErrAccessDenied } + // A destination volume short of upload budget, or a chunk write that + // stalled through its retries, is load the client should back off from: + // SlowDown, as for PutObject, not a 500 it cannot tell from a fault. + if operation.IsUploadOverloaded(err) || errors.Is(err, operation.ErrUploadStalled) { + return s3err.ErrTooManyRequest + } + // Check for KMS errors first if kmsErr := MapKMSErrorToS3Error(err); kmsErr != s3err.ErrInvalidRequest { return kmsErr diff --git a/weed/s3api/s3api_object_handlers_extract.go b/weed/s3api/s3api_object_handlers_extract.go index 525a9808f0..3465beb7e4 100644 --- a/weed/s3api/s3api_object_handlers_extract.go +++ b/weed/s3api/s3api_object_handlers_extract.go @@ -130,6 +130,8 @@ func (s3a *S3ApiServer) extractZipObject(w http.ResponseWriter, r *http.Request, s3err.WriteErrorResponse(w, r, s3err.ErrEntityTooLarge) } else if strings.Contains(err.Error(), s3err.ErrMsgContentSha256Mismatch) { s3err.WriteErrorResponse(w, r, s3err.ErrContentSHA256Mismatch) + } else if errors.Is(err, errDecodedLengthExceeded) { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest) } else { s3err.WriteErrorResponse(w, r, s3err.ErrInternalError) } diff --git a/weed/s3api/s3api_object_handlers_put.go b/weed/s3api/s3api_object_handlers_put.go index 567ad47cac..2df3bb8745 100644 --- a/weed/s3api/s3api_object_handlers_put.go +++ b/weed/s3api/s3api_object_handlers_put.go @@ -238,6 +238,8 @@ func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) glog.Errorf("PutObjectHandler: failed to read directory marker content %s/%s: %v", bucket, object, readErr) if strings.Contains(readErr.Error(), s3err.ErrMsgContentSha256Mismatch) { s3err.WriteErrorResponse(w, r, s3err.ErrContentSHA256Mismatch) + } else if errors.Is(readErr, errDecodedLengthExceeded) { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest) } else { s3err.WriteErrorResponse(w, r, s3err.ErrInternalError) } @@ -736,26 +738,15 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader // Create assign function for chunked upload assignFunc := func(ctx context.Context, count int, expectedDataSize uint64) (*operation.VolumeAssignRequest, *operation.AssignResult, error) { - var assignResult *filer_pb.AssignVolumeResponse - err := s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - resp, err := client.AssignVolume(ctx, &filer_pb.AssignVolumeRequest{ - Count: int32(count), - Replication: "", - Collection: collection, - DiskType: "", - DataCenter: s3a.option.DataCenter, - Path: assignPath, - ExpectedDataSize: expectedDataSize, - TtlSec: lifecycleTTLSec, - }) - if err != nil { - return fmt.Errorf("assign volume: %w", err) - } - if err := filer_pb.AssignVolumeResponseError(resp); err != nil { - return fmt.Errorf("assign volume: %w", err) - } - assignResult = resp - return nil + assignResult, err := s3a.assignUploadVolume(ctx, &filer_pb.AssignVolumeRequest{ + Count: int32(count), + Replication: "", + Collection: collection, + DiskType: "", + DataCenter: s3a.option.DataCenter, + Path: assignPath, + ExpectedDataSize: expectedDataSize, + TtlSec: lifecycleTTLSec, }) if err != nil { return nil, nil, err @@ -781,9 +772,12 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader } // Upload with auto-chunking - // Use context.Background() to ensure chunk uploads complete even if HTTP request is cancelled - // This prevents partial uploads and data corruption - chunkResult, err := stages.upload(context.Background(), dataReader, &operation.ChunkedUploadOption{ + // Chunk uploads follow the request context: when the client goes away the + // uploads stop and release their buffers. Orphan cleanup below and the + // metadata commit later run on context.Background(), so an aborted upload + // still has its already-written chunks deleted and a commit in flight is + // never cut short. + chunkResult, err := stages.upload(r.Context(), dataReader, &operation.ChunkedUploadOption{ ChunkSize: chunkSize, SmallFileLimit: smallFileLimit, Collection: collection, @@ -793,9 +787,16 @@ func (s3a *S3ApiServer) putToFiler(r *http.Request, filePath string, dataReader Cipher: s3a.cipher, // encrypt data on volume servers AssignFunc: assignFunc, LookupJwtFunc: s3a.lookupVolumeJwt, + // A body that crawls below the minimum rate is cut and answered as + // SlowDown, so the gateway does not hold chunk buffers on it. + BodyDeadline: true, }) if err != nil { - glog.Errorf("putToFiler: chunked upload failed: %v", err) + if errors.Is(r.Context().Err(), context.Canceled) { + glog.V(1).Infof("putToFiler: chunked upload stopped, client gone: %v", err) + } else { + glog.Errorf("putToFiler: chunked upload failed: %v", err) + } // CRITICAL: Cleanup orphaned chunks before returning error // UploadReaderInChunks now returns partial results even on error, @@ -1890,6 +1891,32 @@ func filerErrorToS3Error(err error) s3err.ErrorCode { } } +// s3AssignVolumeTimeout bounds one AssignVolume RPC; it mirrors operation's +// unexported assignVolumeTimeout. +const s3AssignVolumeTimeout = 30 * time.Second + +// assignUploadVolume asks a filer for a volume for one upload chunk. ctx follows +// the client, so the call is bounded by s3AssignVolumeTimeout too, and the filer +// walk gets the same context: a client that went away is not evidence against +// the filer that was answering, and the next filer is not asked on its behalf. +func (s3a *S3ApiServer) assignUploadVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) { + assignCtx, cancel := context.WithTimeout(ctx, s3AssignVolumeTimeout) + defer cancel() + var assignResult *filer_pb.AssignVolumeResponse + err := s3a.withFilerClient(assignCtx, false, func(client filer_pb.SeaweedFilerClient) error { + resp, err := client.AssignVolume(assignCtx, req) + if err != nil { + return fmt.Errorf("assign volume: %w", err) + } + if err := filer_pb.AssignVolumeResponseError(resp); err != nil { + return fmt.Errorf("assign volume: %w", err) + } + assignResult = resp + return nil + }) + return assignResult, err +} + // mapChunkedUploadErrorToS3Error classifies a failed streaming upload. A truncated // request body (client abort or reverse-proxy timeout) is a request error, so report // IncompleteBody (400) rather than a 500 a reverse proxy would relay as a confusing @@ -1900,8 +1927,10 @@ func filerErrorToS3Error(err error) s3err.ErrorCode { // peer that went away, and a body that arrived short while the peer was still there. // Both surface as the same read error, so without this they are indistinguishable in // logs even though they point at opposite causes — a network path versus a client. -// The upload itself deliberately runs on a background context, so cancellation of -// reqCtx races the read error; a missed signal degrades to IncompleteBody as before. +// The chunk uploads run on reqCtx, so once the peer is gone any upload error +// (including a gRPC Canceled or a transport "context canceled") is the client +// going away, not a fault; that is checked first. Orphan cleanup and the +// metadata commit do not use reqCtx. // // This reads cancellation as "the peer is gone", which is what net/http means by it // today: nothing on the S3 request path cancels reqCtx for its own reasons. Anything @@ -1913,6 +1942,8 @@ func filerErrorToS3Error(err error) s3err.ErrorCode { // quota) is AccessDenied, as in filerErrorToS3Error and mapCopyErrorToS3Error. func mapChunkedUploadErrorToS3Error(reqCtx context.Context, err error) s3err.ErrorCode { switch { + case errors.Is(reqCtx.Err(), context.Canceled): + return s3err.ErrClientDisconnected case errors.Is(err, weed_server.ErrReadOnly): return s3err.ErrAccessDenied case strings.Contains(err.Error(), s3err.ErrMsgContentSha256Mismatch): @@ -1920,10 +1951,13 @@ func mapChunkedUploadErrorToS3Error(reqCtx context.Context, err error) s3err.Err case strings.Contains(err.Error(), s3err.ErrMsgPayloadChecksumMismatch): return s3err.ErrInvalidDigest case errors.Is(err, operation.ErrTruncatedBody): - if errors.Is(reqCtx.Err(), context.Canceled) { - return s3err.ErrClientDisconnected - } return s3err.ErrIncompleteBody + case errors.Is(err, errDecodedLengthExceeded): + return s3err.ErrInvalidRequest + case operation.IsUploadOverloaded(err), errors.Is(err, operation.ErrUploadStalled): + // The volumes are short of upload budget, or a stalled write used up + // its retries: load the client should back off from, not a fault. + return s3err.ErrTooManyRequest default: return s3err.ErrInternalError } diff --git a/weed/s3api/s3api_object_handlers_put_ambiguous_test.go b/weed/s3api/s3api_object_handlers_put_ambiguous_test.go index 60133c35dc..2430665c17 100644 --- a/weed/s3api/s3api_object_handlers_put_ambiguous_test.go +++ b/weed/s3api/s3api_object_handlers_put_ambiguous_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "crypto/md5" + "errors" "fmt" "io" "net" @@ -25,6 +26,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/cluster" "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/operation" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" @@ -45,6 +47,20 @@ type fakeVolumeServer struct { mu sync.Mutex deletedFids []string stored map[string][]byte + // uploadStatus, when set, answers every upload with that status the way + // an over-budget volume server does; uploads counts the POSTs. + uploadStatus int + uploads int + // holdUploads makes an upload read its body, then wait for the request to + // be cancelled; uploadsHeld and uploadsCancelled count them. gotUpload is + // signalled (once per held upload) when the body has been read. + holdUploads bool + uploadsHeld int + uploadsCancelled int + gotUpload chan struct{} + // httpDeletedFids records the fids the gateway's own cleanup DELETEs over + // HTTP (a failed chunk write), as opposed to BatchDelete's orphan cleanup. + httpDeletedFids []string } func (f *fakeVolumeServer) BatchDelete(_ context.Context, req *volume_server_pb.BatchDeleteRequest) (*volume_server_pb.BatchDeleteResponse, error) { @@ -64,11 +80,25 @@ func (f *fakeVolumeServer) deleted() []string { return append([]string(nil), f.deletedFids...) } +func (f *fakeVolumeServer) httpDeleted() []string { + f.mu.Lock() + defer f.mu.Unlock() + return append([]string(nil), f.httpDeletedFids...) +} + func startFakeVolumeServer(t *testing.T) *fakeVolumeServer { t.Helper() v := &fakeVolumeServer{stored: map[string][]byte{}} upload := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fid := strings.TrimPrefix(r.URL.Path, "/") + if r.Method == http.MethodDelete { + v.mu.Lock() + v.httpDeletedFids = append(v.httpDeletedFids, fid) + delete(v.stored, fid) + v.mu.Unlock() + w.WriteHeader(http.StatusAccepted) + return + } if r.Method == http.MethodGet { v.mu.Lock() data, ok := v.stored[fid] @@ -101,8 +131,39 @@ func startFakeVolumeServer(t *testing.T) *fakeVolumeServer { w.WriteHeader(http.StatusOK) return } + v.mu.Lock() + status := v.uploadStatus + if r.Method == http.MethodPost { + v.uploads++ + } else { + status = 0 + } + v.mu.Unlock() + if status != 0 { + w.Header().Set("Retry-After", "1") + w.WriteHeader(status) + io.WriteString(w, `{"error":"volume server upload limit"}`) + return + } data, _ := io.ReadAll(r.Body) v.mu.Lock() + hold := v.holdUploads && r.Method == http.MethodPost + if hold { + v.uploadsHeld++ + } + v.mu.Unlock() + if hold { + select { + case v.gotUpload <- struct{}{}: + default: + } + <-r.Context().Done() + v.mu.Lock() + v.uploadsCancelled++ + v.mu.Unlock() + return + } + v.mu.Lock() v.stored[fid] = data v.mu.Unlock() w.Header().Set("Content-MD5", r.Header.Get("Content-MD5")) @@ -1320,3 +1381,182 @@ func TestTxnConditionHoldsQuotedStoredETag(t *testing.T) { t.Fatalf("a quoted stored ETag must compare equal to the same ETag") } } + +// overloadedUploadError returns what a chunk upload to a holder answering +// status yields, wrapped the way UploadReaderInChunks wraps it. +func overloadedUploadError(t *testing.T, status int) error { + t.Helper() + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Retry-After", "1") + w.WriteHeader(status) + io.WriteString(w, `{"error":"volume server upload limit"}`) + })) + defer holder.Close() + uploader, err := operation.NewUploader() + if err != nil { + t.Fatal(err) + } + _, err = uploader.UploadData(context.Background(), []byte("hello"), &operation.UploadOption{ + UploadUrl: holder.URL + "/3,01637037d6", + MaxAttempts: 1, + }) + if err == nil { + t.Fatalf("upload against a %d holder succeeded", status) + } + return fmt.Errorf("upload chunk: %w", err) +} + +// CopyObject and UploadPartCopy write chunks too: a destination volume short +// of budget, or a stalled chunk write, is SlowDown there as for PutObject. +func TestMapCopyErrorOverloadIsSlowDown(t *testing.T) { + s3a := &S3ApiServer{} + tests := []struct { + name string + err error + want s3err.ErrorCode + }{ + {"volume 503", fmt.Errorf("upload chunk data: %w", overloadedUploadError(t, http.StatusServiceUnavailable)), s3err.ErrTooManyRequest}, + {"volume 429", fmt.Errorf("upload chunk data: %w", overloadedUploadError(t, http.StatusTooManyRequests)), s3err.ErrTooManyRequest}, + {"exhausted stall", fmt.Errorf("upload chunk data: %w", operation.ErrUploadStalled), s3err.ErrTooManyRequest}, + {"volume 500", fmt.Errorf("upload chunk data: %w", overloadedUploadError(t, http.StatusInternalServerError)), s3err.ErrInternalError}, + {"plain error", errors.New("upload chunk data: 503 service unavailable"), s3err.ErrInternalError}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := s3a.mapCopyErrorToS3Error(tt.err); got != tt.want { + t.Errorf("mapCopyErrorToS3Error(%v) = %v, want %v", tt.err, got, tt.want) + } + }) + } +} + +// A volume that refuses the write for lack of budget, or a stall that used up +// its retries, is load the client should back off from: SlowDown, not a 500 +// the client cannot tell from a fault. +func TestMapChunkedUploadErrorOverloadIsSlowDown(t *testing.T) { + // A dial failure is a status-0 error too, but not a stall. + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + closedAddr := lis.Addr().String() + lis.Close() + uploader, err := operation.NewUploader() + if err != nil { + t.Fatal(err) + } + _, dialErr := uploader.UploadData(context.Background(), []byte("hello"), &operation.UploadOption{ + UploadUrl: "http://" + closedAddr + "/3,01637037d6", + MaxAttempts: 1, + }) + if dialErr == nil { + t.Fatal("upload to a closed port succeeded") + } + + tests := []struct { + name string + err error + want s3err.ErrorCode + }{ + {"volume 503", overloadedUploadError(t, http.StatusServiceUnavailable), s3err.ErrTooManyRequest}, + {"volume 429", overloadedUploadError(t, http.StatusTooManyRequests), s3err.ErrTooManyRequest}, + {"exhausted stall", fmt.Errorf("upload chunk: %w", operation.ErrUploadStalled), s3err.ErrTooManyRequest}, + {"volume 500", overloadedUploadError(t, http.StatusInternalServerError), s3err.ErrInternalError}, + {"dial failure", fmt.Errorf("upload chunk: %w", dialErr), s3err.ErrInternalError}, + {"plain error", errors.New("upload chunk: 503 service unavailable"), s3err.ErrInternalError}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := mapChunkedUploadErrorToS3Error(context.Background(), tt.err); got != tt.want { + t.Errorf("mapChunkedUploadErrorToS3Error(%v) = %v, want %v", tt.err, got, tt.want) + } + }) + } +} + +// End to end: every holder over budget answers 503; the PUT answers SlowDown +// after one reassign, not an InternalError after three. +func TestPutToFilerVolumeOverloadAnswersSlowDown(t *testing.T) { + volume := startFakeVolumeServer(t) + volume.mu.Lock() + volume.uploadStatus = http.StatusServiceUnavailable + volume.mu.Unlock() + filerImpl := &ambiguousPutFiler{volume: volume, entries: map[string]*filer_pb.Entry{}, apply: true} + s3a := newPutTestServer(t, startFakeFiler(t, filerImpl)) + + _, code := putTestObject(t, s3a) + if code != s3err.ErrTooManyRequest { + t.Fatalf("putToFiler returned %v, want ErrTooManyRequest (SlowDown)", code) + } + volume.mu.Lock() + uploads := volume.uploads + volume.mu.Unlock() + if uploads != 2 { + t.Fatalf("volume saw %d upload POSTs, want 2 (one per assignment)", uploads) + } +} + +// The client going away must stop the chunk uploads: they follow the request +// context instead of running on, holding buffers, until a volume times out. +func TestPutToFilerClientGoneCancelsChunkUploads(t *testing.T) { + volume := startFakeVolumeServer(t) + volume.mu.Lock() + volume.holdUploads = true + volume.gotUpload = make(chan struct{}, 1) + volume.mu.Unlock() + filerImpl := &ambiguousPutFiler{volume: volume, entries: map[string]*filer_pb.Entry{}, apply: true} + s3a := newPutTestServer(t, startFakeFiler(t, filerImpl)) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + r := httptest.NewRequest(http.MethodPut, "/b/o", nil).WithContext(ctx) + + type result struct { + code s3err.ErrorCode + } + done := make(chan result, 1) + go func() { + _, code, _ := s3a.putToFiler(r, "/buckets/b/o", strings.NewReader("hello world"), "b", "o", 1, 0, nil, false, "") + done <- result{code} + }() + + select { + case <-volume.gotUpload: + case <-time.After(5 * time.Second): + t.Fatal("the volume never received the chunk upload") + } + time.AfterFunc(100*time.Millisecond, cancel) + + select { + case res := <-done: + if res.code != s3err.ErrClientDisconnected { + t.Fatalf("putToFiler returned %v, want ErrClientDisconnected", res.code) + } + case <-time.After(2 * time.Second): + t.Fatal("putToFiler kept running after the client went away") + } + + deadline := time.Now().Add(2 * time.Second) + for { + volume.mu.Lock() + cancelled := volume.uploadsCancelled + volume.mu.Unlock() + if cancelled > 0 { + break + } + if time.Now().After(deadline) { + t.Fatal("the volume never saw the upload being cancelled") + } + time.Sleep(10 * time.Millisecond) + } + + // The volume commits on a context that ignores the cancel, so a body it + // already holds may still land: the cancelled chunk's fid must be deleted + // rather than left as a needle nothing references. + filerImpl.mu.Lock() + assigned := fmt.Sprintf("3,%016x%08x", filerImpl.nextKey, uint32(filerImpl.nextKey)) + filerImpl.mu.Unlock() + if deleted := volume.httpDeleted(); !slices.Contains(deleted, assigned) { + t.Fatalf("the cancelled chunk %s was not deleted, deletes=%v", assigned, deleted) + } +} diff --git a/weed/s3api/s3api_object_handlers_put_error_test.go b/weed/s3api/s3api_object_handlers_put_error_test.go index ade6b661f8..a411710189 100644 --- a/weed/s3api/s3api_object_handlers_put_error_test.go +++ b/weed/s3api/s3api_object_handlers_put_error_test.go @@ -108,11 +108,13 @@ func TestMapChunkedUploadErrorToS3ErrorClientDisconnect(t *testing.T) { want: s3err.ErrIncompleteBody, }, { - // Cancellation must not reclassify faults that are not truncations. - name: "server fault under a canceled context stays InternalError", + // The chunk uploads run on the request context, so any error under + // a canceled one (gRPC Canceled, transport "context canceled") is the + // client going away, not a server fault. + name: "upload error under a canceled context is ClientDisconnected", ctx: canceled, err: errors.New("assign volume: no free volumes"), - want: s3err.ErrInternalError, + want: s3err.ErrClientDisconnected, }, } for _, tt := range tests { diff --git a/weed/s3api/s3api_put_object_helper.go b/weed/s3api/s3api_put_object_helper.go index 579f8e704d..894fc3eb5b 100644 --- a/weed/s3api/s3api_put_object_helper.go +++ b/weed/s3api/s3api_put_object_helper.go @@ -9,6 +9,7 @@ import ( "hash" "io" "net/http" + "strconv" "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" ) @@ -21,12 +22,14 @@ func getRequestDataReader(s3a *S3ApiServer, r *http.Request) (io.ReadCloser, s3e var s3ErrCode s3err.ErrorCode signedSha256 := unwrapSignedPayload(&r.Body) dataReader := r.Body - rAuthType := getRequestAuthType(r) - if rAuthType == authTypeStreamingSigned || rAuthType == authTypeStreamingUnsigned { + if isAwsChunkedUpload(r) { dataReader, s3ErrCode = s3a.iam.newChunkedReader(r) - } - if s3ErrCode != s3err.ErrNone { - return nil, s3ErrCode + if s3ErrCode != s3err.ErrNone { + return nil, s3ErrCode + } + if decoded, ok := decodedContentLength(r); ok { + dataReader = &decodedLengthLimiter{reader: dataReader, remaining: decoded} + } } expected, valid := expectedContentSha256(r) @@ -50,6 +53,62 @@ func getRequestDataReader(s3a *S3ApiServer, r *http.Request) (io.ReadCloser, s3e return dataReader, s3err.ErrNone } +// isAwsChunkedUpload reports whether r's body is aws-chunked encoded, the +// streaming forms getRequestDataReader decodes. +func isAwsChunkedUpload(r *http.Request) bool { + authType := getRequestAuthType(r) + return authType == authTypeStreamingSigned || authType == authTypeStreamingUnsigned +} + +// errDecodedLengthExceeded: an aws-chunked body decoded to more bytes than its +// X-Amz-Decoded-Content-Length declared. +var errDecodedLengthExceeded = errors.New("aws-chunked body is longer than its X-Amz-Decoded-Content-Length") + +// decodedContentLength is the X-Amz-Decoded-Content-Length an aws-chunked +// request declares, when it carries a valid one. +func decodedContentLength(r *http.Request) (int64, bool) { + v := r.Header.Get("X-Amz-Decoded-Content-Length") + if v == "" { + return 0, false + } + decoded, err := strconv.ParseInt(v, 10, 64) + if err != nil || decoded < 0 { + return 0, false + } + return decoded, true +} + +// decodedLengthLimiter stops an aws-chunked body at its declared decoded +// length. The upload budget charges a request of unknown Content-Length by that +// header, so a body that ran past it would hold bytes nobody reserved; it fails +// instead. +type decodedLengthLimiter struct { + reader io.ReadCloser + remaining int64 +} + +func (l *decodedLengthLimiter) Read(p []byte) (int, error) { + if l.remaining <= 0 { + // Everything declared has been read: the body must end here. + var probe [1]byte + n, err := l.reader.Read(probe[:]) + if n > 0 { + return 0, errDecodedLengthExceeded + } + return 0, err + } + if int64(len(p)) > l.remaining { + p = p[:l.remaining] + } + n, err := l.reader.Read(p) + l.remaining -= int64(n) + return n, err +} + +func (l *decodedLengthLimiter) Close() error { + return l.reader.Close() +} + // expectedContentSha256 decodes the x-amz-content-sha256 header when it declares // a payload hash — hex or base64 per SigV4 — so the body can be checked as it // streams. Sentinel values (streaming, unsigned) carry no hash and are skipped; diff --git a/weed/s3api/s3api_put_object_helper_test.go b/weed/s3api/s3api_put_object_helper_test.go index 292ce9dc7c..71f0b64243 100644 --- a/weed/s3api/s3api_put_object_helper_test.go +++ b/weed/s3api/s3api_put_object_helper_test.go @@ -2,9 +2,13 @@ package s3api import ( "bytes" + "context" "crypto/sha256" "encoding/base64" "encoding/hex" + "errors" + "fmt" + "hash/crc32" "io" "net/http" "net/http/httptest" @@ -312,3 +316,55 @@ func TestGetRequestDataReaderEmptyBodyHash(t *testing.T) { t.Fatalf("empty body with empty hash: code=%v", code) } } + +// unsignedChunkedRequest is an anonymous aws-chunked PUT with unknown +// Content-Length, whose body decodes to payload and which declares declared as +// its X-Amz-Decoded-Content-Length. +func unsignedChunkedRequest(payload string, declared string) *http.Request { + checksum := crc32.ChecksumIEEE([]byte(payload)) + sum := []byte{byte(checksum >> 24), byte(checksum >> 16), byte(checksum >> 8), byte(checksum)} + body := fmt.Sprintf("%x\r\n%s\r\n0\r\n\r\nx-amz-checksum-crc32:%s\r\n\r\n", len(payload), payload, base64.StdEncoding.EncodeToString(sum)) + req := httptest.NewRequest(http.MethodPut, "/bucket/key", strings.NewReader(body)) + req.ContentLength = -1 + req.Header.Set("X-Amz-Content-Sha256", streamingUnsignedPayload) + req.Header.Set("X-Amz-Trailer", "x-amz-checksum-crc32") + req.Header.Set("Content-Encoding", "aws-chunked") + req.Header.Set("X-Amz-Decoded-Content-Length", declared) + return req +} + +// The upload budget charges an aws-chunked request of unknown Content-Length +// by its X-Amz-Decoded-Content-Length, so the body is held to it: a client +// cannot declare a few bytes and stream gigabytes past its reservation. +func TestGetRequestDataReaderHoldsAwsChunkedBodyToDecodedLength(t *testing.T) { + s3a := &S3ApiServer{iam: &IdentityAccessManagement{}} + + t.Run("matches", func(t *testing.T) { + reader, code := getRequestDataReader(s3a, unsignedChunkedRequest("hello world", "11")) + if code != s3err.ErrNone { + t.Fatalf("getRequestDataReader: %v", code) + } + got, err := io.ReadAll(reader) + if err != nil || string(got) != "hello world" { + t.Fatalf("got %q, %v", got, err) + } + }) + + t.Run("longer than declared", func(t *testing.T) { + reader, code := getRequestDataReader(s3a, unsignedChunkedRequest("hello world", "5")) + if code != s3err.ErrNone { + t.Fatalf("getRequestDataReader: %v", code) + } + got, err := io.ReadAll(reader) + if !errors.Is(err, errDecodedLengthExceeded) { + t.Fatalf("want errDecodedLengthExceeded, got %q, %v", got, err) + } + if len(got) > 5 { + t.Fatalf("read %d bytes past a declared 5", len(got)) + } + wrapped := fmt.Errorf("upload chunk: read chunk at offset 0: %w", err) + if code := mapChunkedUploadErrorToS3Error(context.Background(), wrapped); code != s3err.ErrInvalidRequest { + t.Fatalf("mapped to %v, want ErrInvalidRequest", code) + } + }) +} diff --git a/weed/s3api/s3err/error_handler.go b/weed/s3api/s3err/error_handler.go index 17822de6dd..037794f088 100644 --- a/weed/s3api/s3err/error_handler.go +++ b/weed/s3api/s3err/error_handler.go @@ -60,6 +60,11 @@ func WriteErrorResponseWithMessage(w http.ResponseWriter, r *http.Request, error errorResponse.Message = message } drainRequestBody(w, r) + if apiError.Code == "SlowDown" { + // Tell the client how long to back off, so an SDK that honours it + // waits instead of retrying straight into the overload. + w.Header().Set("Retry-After", "1") + } WriteXMLResponse(w, r, apiError.HTTPStatusCode, errorResponse) PostLog(r, apiError.HTTPStatusCode, errorCode) } diff --git a/weed/s3api/s3err/error_handler_test.go b/weed/s3api/s3err/error_handler_test.go index 2e611dfe89..04675f7201 100644 --- a/weed/s3api/s3err/error_handler_test.go +++ b/weed/s3api/s3err/error_handler_test.go @@ -144,3 +144,24 @@ func (d *drainCheckingResponseWriter) SetReadDeadline(t time.Time) error { d.readDeadlines = append(d.readDeadlines, t) return nil } + +// A SlowDown tells the client to back off; Retry-After says for how long, so +// SDKs that honour it wait instead of retrying straight into the overload. +func TestSlowDownResponseCarriesRetryAfter(t *testing.T) { + for _, tc := range []struct { + code ErrorCode + want string + }{ + {ErrTooManyRequest, "1"}, + {ErrRequestBytesExceed, "1"}, + {ErrInternalError, ""}, + } { + req := httptest.NewRequest(http.MethodPut, "/bucket/object", nil) + rr := httptest.NewRecorder() + WriteErrorResponse(rr, req, tc.code) + assert.Equal(t, GetAPIError(tc.code).HTTPStatusCode, rr.Code) + // Result() holds what was sent: a header set after WriteHeader would + // show in rr.Header() but never reach the client. + assert.Equal(t, tc.want, rr.Result().Header.Get("Retry-After"), "Retry-After for %s", GetAPIError(tc.code).Code) + } +} diff --git a/weed/server/filer_server_handlers.go b/weed/server/filer_server_handlers.go index c68f55299b..95d46f1707 100644 --- a/weed/server/filer_server_handlers.go +++ b/weed/server/filer_server_handlers.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "math" "net/http" "net/url" "path" @@ -100,7 +101,8 @@ func (fs *FilerServer) filerHandler(w http.ResponseWriter, r *http.Request) { case http.MethodPost, http.MethodPut: // wait until in flight data is less than the limit contentLength := getContentLength(r) - if !fs.waitForUploadSlot(w, r, contentLength) { + charged := fs.uploadCharge(r) + if !fs.waitForUploadSlot(w, r, charged) { return } defer func() { @@ -108,7 +110,7 @@ func (fs *FilerServer) filerHandler(w http.ResponseWriter, r *http.Request) { defer fs.inFlightDataLimitCond.L.Unlock() // Decrement counters newUploads := atomic.AddInt64(&fs.inFlightUploads, -1) - newSize := atomic.AddInt64(&fs.inFlightDataSize, -contentLength) + newSize := atomic.AddInt64(&fs.inFlightDataSize, -charged) // Update metrics stats.FilerInFlightUploadCountGauge.Set(float64(newUploads)) stats.FilerInFlightUploadBytesGauge.Set(float64(newSize)) @@ -130,12 +132,54 @@ func (fs *FilerServer) filerHandler(w http.ResponseWriter, r *http.Request) { } } -func (fs *FilerServer) waitForUploadSlot(w http.ResponseWriter, r *http.Request, contentLength int64) bool { +const ( + // filerDefaultChunkSizeMB is the filer's -maxMB default, used for the + // upload charge when -maxMB is not positive. + filerDefaultChunkSizeMB = 4 + // filerMaxChunkSizeMB keeps the chunk size within an int32, as + // requestChunkSize does. + filerMaxChunkSizeMB = math.MaxInt32 / (1024 * 1024) // 2047 +) + +// uploadCharge is the bytes r reserves against the in-flight upload budget. +// +// A chunked upload holds at most its chunk buffers; see util.GatewayUploadCharge. +// The chunk is the one the upload loop will cut: the request's ?maxMB, else +// -maxMB, as requestChunkSize resolves it, and the filer default when neither is +// positive, so the charge never collapses to 0. +// +// A POST stored inside the filer entry (?saveInside=true, or under /etc) is +// read into memory whole (doPostAutoChunk), so with a limit set it is charged +// its whole declared length, at most the whole budget, and an unknown length is +// charged the whole budget: it then runs only on an idle filer, the one place a +// body of any size can be buffered without overshooting. A PUT there still goes +// through the chunk loop and is charged by chunks. With no limit the charge +// only feeds the gauge, so the chunk-based one is kept. +func (fs *FilerServer) uploadCharge(r *http.Request) int64 { + limit := fs.option.ConcurrentUploadLimit + query := r.URL.Query() + chunk := int64(fs.requestChunkSize(query)) + if chunk <= 0 { + chunk = filerDefaultChunkSizeMB << 20 + } + chunk = min(chunk, filerMaxChunkSizeMB<<20) + if limit > 0 && r.Method == http.MethodPost && (query.Get("saveInside") == "true" || strings.HasPrefix(r.URL.Path, "/etc")) { + if r.ContentLength >= 0 { + return min(r.ContentLength, limit) + } + return limit + } + return util.GatewayUploadCharge(r.ContentLength, chunk, limit) +} + +// waitForUploadSlot reserves charged bytes and one upload slot, or writes the +// rejection and returns false. The caller releases exactly charged. +func (fs *FilerServer) waitForUploadSlot(w http.ResponseWriter, r *http.Request, charged int64) bool { fs.inFlightDataLimitCond.L.Lock() err := util.WaitUntil(r.Context(), fs.inFlightDataLimitCond, fs.option.InflightUploadDataTimeout, func() bool { inFlightDataSize := atomic.LoadInt64(&fs.inFlightDataSize) - if fs.option.ConcurrentUploadLimit != 0 && inFlightDataSize > fs.option.ConcurrentUploadLimit { - glog.V(4).Infof("wait because inflight data %d > %d", inFlightDataSize, fs.option.ConcurrentUploadLimit) + if !util.UploadAdmits(inFlightDataSize, charged, fs.option.ConcurrentUploadLimit) { + glog.V(4).Infof("wait because inflight data %d + %d > %d", inFlightDataSize, charged, fs.option.ConcurrentUploadLimit) return false } inFlightUploads := atomic.LoadInt64(&fs.inFlightUploads) @@ -148,7 +192,7 @@ func (fs *FilerServer) waitForUploadSlot(w http.ResponseWriter, r *http.Request, if err == nil { // Increment counters newUploads := atomic.AddInt64(&fs.inFlightUploads, 1) - newSize := atomic.AddInt64(&fs.inFlightDataSize, contentLength) + newSize := atomic.AddInt64(&fs.inFlightDataSize, charged) // Update metrics stats.FilerInFlightUploadCountGauge.Set(float64(newUploads)) stats.FilerInFlightUploadBytesGauge.Set(float64(newSize)) @@ -170,7 +214,8 @@ func (fs *FilerServer) waitForUploadSlot(w http.ResponseWriter, r *http.Request, } err = fmt.Errorf("reject because no upload slot freed within %v", fs.option.InflightUploadDataTimeout) glog.V(1).Infof("too many requests from %s: %v", r.RemoteAddr, err) - writeJsonError(w, r, http.StatusTooManyRequests, err) + w.Header().Set("Retry-After", "1") + writeJsonError(w, r, http.StatusServiceUnavailable, err) return false } diff --git a/weed/server/filer_server_handlers_upload_slot_test.go b/weed/server/filer_server_handlers_upload_slot_test.go index a81f82aa39..418876b877 100644 --- a/weed/server/filer_server_handlers_upload_slot_test.go +++ b/weed/server/filer_server_handlers_upload_slot_test.go @@ -4,6 +4,7 @@ import ( "bufio" "context" "io" + "math" "net" "net/http" "net/http/httptest" @@ -31,15 +32,15 @@ func TestFilerWaitForUploadSlot(t *testing.T) { return fs } - t.Run("times out with 429", func(t *testing.T) { + t.Run("times out with 503 and Retry-After", func(t *testing.T) { fs := newFiler(100 * time.Millisecond) rec := httptest.NewRecorder() start := time.Now() if fs.waitForUploadSlot(rec, filerPutRequest(context.Background()), 4) { t.Fatal("upload admitted without a free slot") } - if rec.Code != http.StatusTooManyRequests { - t.Fatalf("got %d, want 429", rec.Code) + if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "1" { + t.Fatalf("got %d Retry-After %q, want 503 and 1", rec.Code, rec.Header().Get("Retry-After")) } if elapsed := time.Since(start); elapsed < 100*time.Millisecond { t.Fatalf("rejected after %v, before the wait timeout", elapsed) @@ -49,7 +50,7 @@ func TestFilerWaitForUploadSlot(t *testing.T) { } }) - t.Run("stalled body still gets the 429", func(t *testing.T) { + t.Run("stalled body still gets the 503", func(t *testing.T) { fs := newFiler(100 * time.Millisecond) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if fs.waitForUploadSlot(w, r, r.ContentLength) { @@ -70,8 +71,8 @@ func TestFilerWaitForUploadSlot(t *testing.T) { if err != nil { t.Fatalf("no reply while the body is unsent: %v", err) } - if resp.StatusCode != http.StatusTooManyRequests || !resp.Close { - t.Fatalf("got %d close=%v, want 429 with Connection: close", resp.StatusCode, resp.Close) + if resp.StatusCode != http.StatusServiceUnavailable || !resp.Close || resp.Header.Get("Retry-After") != "1" { + t.Fatalf("got %d close=%v, want 503 with Retry-After and Connection: close", resp.StatusCode, resp.Close) } }) @@ -97,3 +98,149 @@ func TestFilerWaitForUploadSlot(t *testing.T) { } }) } + +func newLimitedFiler(limit, inFlight int64) *FilerServer { + return &FilerServer{ + option: &FilerOption{ConcurrentUploadLimit: limit, MaxMB: 4, InflightUploadDataTimeout: 50 * time.Millisecond}, + inFlightDataLimitCond: sync.NewCond(new(sync.Mutex)), + inFlightDataSize: inFlight, + } +} + +func TestFilerUploadSlotNoOvershoot(t *testing.T) { + fs := newLimitedFiler(10, 8) + rec := httptest.NewRecorder() + if fs.waitForUploadSlot(rec, filerPutRequest(context.Background()), 4) { + t.Fatal("upload admitted beyond the limit") + } + if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "1" { + t.Fatalf("got %d Retry-After %q, want 503 and 1", rec.Code, rec.Header().Get("Retry-After")) + } + if fs.inFlightDataSize != 8 { + t.Fatalf("in-flight bytes %d, want 8", fs.inFlightDataSize) + } +} + +func TestFilerUploadSlotChargesUnknownLength(t *testing.T) { + const limit = 1 << 20 + unknown := func() *http.Request { + req := filerPutRequest(context.Background()) + req.ContentLength = -1 + return req + } + fs := newLimitedFiler(limit, 600<<10) + rec := httptest.NewRecorder() + if fs.waitForUploadSlot(rec, unknown(), fs.uploadCharge(unknown())) { + t.Fatal("unknown-length upload admitted beside 600 KiB in flight") + } + if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "1" { + t.Fatalf("got %d Retry-After %q, want 503 and 1", rec.Code, rec.Header().Get("Retry-After")) + } + fs = newLimitedFiler(limit, 0) + if !fs.waitForUploadSlot(httptest.NewRecorder(), unknown(), fs.uploadCharge(unknown())) || fs.inFlightDataSize != limit/2 { + t.Fatalf("idle: in-flight %d, want admitted with %d", fs.inFlightDataSize, limit/2) + } +} + +func TestFilerUploadSlotAdmitsHugeObjectBesideSmallOnes(t *testing.T) { + fs := newLimitedFiler(64<<20, 32<<20) + req := filerPutRequest(context.Background()) + req.ContentLength = 5 << 30 + if !fs.waitForUploadSlot(httptest.NewRecorder(), req, fs.uploadCharge(req)) || fs.inFlightDataSize != 48<<20 { + t.Fatalf("in-flight %d, want admitted with 48 MiB", fs.inFlightDataSize) + } +} + +// A filer started with -maxMB 0 still charges a chunk for an unknown length +// and caps a known one at four chunks: the chunk size is clamped as S3 does, +// so the charge never collapses to 0 and admits without counting. +func TestFilerUploadChargeClampsNonPositiveMaxMB(t *testing.T) { + for _, maxMB := range []int{0, -1} { + fs := &FilerServer{option: &FilerOption{MaxMB: maxMB}} + req := filerPutRequest(context.Background()) + req.ContentLength = -1 + if got := fs.uploadCharge(req); got != filerDefaultChunkSizeMB<<20 { + t.Fatalf("maxMB %d, unknown length: charge %d, want %d", maxMB, got, filerDefaultChunkSizeMB<<20) + } + req.ContentLength = 5 << 30 + if got := fs.uploadCharge(req); got != 4*filerDefaultChunkSizeMB<<20 { + t.Fatalf("maxMB %d, 5 GiB: charge %d, want %d", maxMB, got, 4*filerDefaultChunkSizeMB<<20) + } + } + fs := &FilerServer{option: &FilerOption{MaxMB: 1 << 20}} + req := filerPutRequest(context.Background()) + req.ContentLength = -1 + if got := fs.uploadCharge(req); got != filerMaxChunkSizeMB<<20 { + t.Fatalf("huge maxMB: charge %d, want %d", got, int64(filerMaxChunkSizeMB)<<20) + } +} + +// A request's ?maxMB sets the chunk the upload loop cuts, so it sets the charge +// too: four 64 MiB buffers are not four 4 MiB ones. +func TestFilerUploadChargeFollowsRequestMaxMB(t *testing.T) { + fs := newLimitedFiler(1<<30, 0) + req := httptest.NewRequest(http.MethodPut, "/dir/file?maxMB=64", strings.NewReader("data")) + req.ContentLength = 256 << 20 + if got := fs.uploadCharge(req); got != 4*64<<20 { + t.Fatalf("256 MiB with maxMB=64: charge %d, want %d", got, 4*64<<20) + } + req.ContentLength = -1 + if got := fs.uploadCharge(req); got != 64<<20 { + t.Fatalf("unknown length with maxMB=64: charge %d, want %d", got, 64<<20) + } +} + +// An upload stored inside the filer entry is buffered whole, so it reserves its +// whole length; two such uploads that together exceed the budget do not run +// side by side. +func TestFilerUploadChargeCoversInlineUploads(t *testing.T) { + const limit = 64 << 20 + for _, target := range []string{"/dir/file?saveInside=true", "/etc/config.toml"} { + t.Run(target, func(t *testing.T) { + fs := newLimitedFiler(limit, 0) + req := httptest.NewRequest(http.MethodPost, target, strings.NewReader("data")) + req.ContentLength = 80 << 20 + // The whole body, capped at the whole budget: over the budget it + // runs only on an idle filer either way. + if got := fs.uploadCharge(req); got != limit { + t.Fatalf("80 MiB inline: charge %d, want the whole budget %d", got, limit) + } + req.ContentLength = 40 << 20 + if got := fs.uploadCharge(req); got != 40<<20 { + t.Fatalf("40 MiB inline: charge %d, want the whole body", got) + } + req.ContentLength = 80 << 20 + // Alone it is admitted, as any oversized request is on an idle filer. + if !fs.waitForUploadSlot(httptest.NewRecorder(), req, fs.uploadCharge(req)) { + t.Fatal("an oversized inline upload was refused on an idle filer") + } + second := httptest.NewRequest(http.MethodPost, target, strings.NewReader("data")) + second.ContentLength = 80 << 20 + if fs.waitForUploadSlot(httptest.NewRecorder(), second, fs.uploadCharge(second)) { + t.Fatal("a second 80 MiB inline upload was admitted beside the first") + } + + req.ContentLength = -1 + if got := fs.uploadCharge(req); got != limit { + t.Fatalf("unknown-length inline: charge %d, want the whole budget %d", got, limit) + } + // A size near MaxInt64 is charged the whole budget, so the + // in-flight counter cannot wrap. + req.ContentLength = math.MaxInt64 + if got := fs.uploadCharge(req); got != limit { + t.Fatalf("huge inline: charge %d, want the whole budget %d", got, limit) + } + }) + } +} + +// A PUT to an inline path still goes through the chunk loop, so it is charged by +// chunks: charged its whole body it would only run on an idle filer. +func TestFilerUploadChargeKeepsChunksForInlinePut(t *testing.T) { + fs := newLimitedFiler(64<<20, 0) + req := httptest.NewRequest(http.MethodPut, "/etc/config.toml", strings.NewReader("data")) + req.ContentLength = 1 << 30 + if got := fs.uploadCharge(req); got != 4*4<<20 { + t.Fatalf("1 GiB PUT under /etc: charge %d, want four 4 MiB chunks", got) + } +} diff --git a/weed/server/filer_server_handlers_write_upload.go b/weed/server/filer_server_handlers_write_upload.go index 6330e74330..bdd74ce8e2 100644 --- a/weed/server/filer_server_handlers_write_upload.go +++ b/weed/server/filer_server_handlers_write_upload.go @@ -231,6 +231,9 @@ func (fs *FilerServer) doUpload(ctx context.Context, urlLocation string, limited PairMap: pairMap, Jwt: auth, Md5: contentMd5, + // The chunk loop holds the client's chunk buffer: a crawling link is + // cut and handed back as back-pressure rather than waited on. + BodyDeadline: true, } uploader, err := operation.NewUploader() @@ -258,12 +261,7 @@ func (fs *FilerServer) dataToChunkWithSSE(ctx context.Context, r *http.Request, var uploadResult *operation.UploadResult var failedFileChunks []*filer_pb.FileChunk - // Each attempt assigns anew, so also retry the errors a fresh volume dodges: - // a target gone read-only or full mid-write 5xxs until the master notices. - shouldRetry := func(err error) bool { - return util.IsTransientError(err) || operation.ShouldReassignUpload(err) - } - err := util.RetryOnError("filerDataToChunk", shouldRetry, func() error { + err := util.RetryOnError("filerDataToChunk", newChunkUploadRetryGate(), func() error { // assign one file id for one chunk fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(ctx, so, uint64(len(data))) if uploadErr != nil { @@ -320,3 +318,24 @@ func (fs *FilerServer) dataToChunkWithSSE(ctx context.Context, r *http.Request, return []*filer_pb.FileChunk{chunk}, nil } + +// newChunkUploadRetryGate decides, for one chunk, whether another attempt +// (with a fresh assignment) is worth it. +func newChunkUploadRetryGate() func(error) bool { + backpressureRetried := false + // Each attempt assigns anew, so also retry the errors a fresh volume dodges: + // a target gone read-only or full mid-write 5xxs until the master notices. + // Back-pressure (an overload, or a body cut at the body deadline) gets one + // fresh assignment only: retrying a cluster short of upload budget or link + // rate every second while holding the chunk adds to the load. + return func(err error) bool { + if operation.IsUploadBackpressure(err) { + if backpressureRetried { + return false + } + backpressureRetried = true + return true + } + return util.IsTransientError(err) || operation.ShouldReassignUpload(err) + } +} diff --git a/weed/server/filer_server_handlers_write_upload_test.go b/weed/server/filer_server_handlers_write_upload_test.go new file mode 100644 index 0000000000..39e342f301 --- /dev/null +++ b/weed/server/filer_server_handlers_write_upload_test.go @@ -0,0 +1,63 @@ +package weed_server + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/operation" +) + +// chunkUploadError returns what the filer's chunk upload yields against a +// volume answering status. +func chunkUploadError(t *testing.T, status int) error { + t.Helper() + holder := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Retry-After", "1") + w.WriteHeader(status) + io.WriteString(w, `{"error":"volume server upload limit"}`) + })) + defer holder.Close() + uploader, err := operation.NewUploader() + if err != nil { + t.Fatal(err) + } + _, err = uploader.UploadData(context.Background(), []byte("hello"), &operation.UploadOption{ + UploadUrl: holder.URL + "/3,01637037d6", + MaxAttempts: 1, + }) + if err == nil { + t.Fatalf("upload against a %d volume succeeded", status) + } + return err +} + +// The filer's per-chunk loop assigns anew on each attempt. An overloaded +// cluster gets one fresh assignment and then the error, rather than a retry +// every second until RetryWaitTime while the chunk buffer is held. Other +// reassignable failures keep today's retries. +func TestChunkUploadRetryGateReassignsOnceOnOverload(t *testing.T) { + overload := chunkUploadError(t, http.StatusServiceUnavailable) + fault := chunkUploadError(t, http.StatusInternalServerError) + + shouldRetry := newChunkUploadRetryGate() + if !shouldRetry(overload) { + t.Fatal("first overload should get one fresh assignment") + } + if shouldRetry(overload) { + t.Fatal("second overload should give up") + } + + shouldRetry = newChunkUploadRetryGate() + for i := 0; i < 5; i++ { + if !shouldRetry(fault) { + t.Fatalf("500 attempt %d: want retry as before", i+1) + } + } + if shouldRetry(fmt.Errorf("mismatching cookie")) { + t.Fatal("a permanent error must not retry") + } +} diff --git a/weed/server/volume_server_handlers.go b/weed/server/volume_server_handlers.go index 69d5bdeb8a..39df9331ac 100644 --- a/weed/server/volume_server_handlers.go +++ b/weed/server/volume_server_handlers.go @@ -2,13 +2,16 @@ package weed_server import ( "context" + "errors" "fmt" + "math" "net/http" "strconv" "strings" "sync/atomic" "time" + "github.com/seaweedfs/seaweedfs/weed/operation" "github.com/seaweedfs/seaweedfs/weed/storage/needle" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/version" @@ -136,74 +139,152 @@ func (vs *VolumeServer) waitForDownloadSlot(w http.ResponseWriter, r *http.Reque return false } -// checkUploadLimit handles upload concurrency limiting with timeout. +// volumeClientUploadWaitCap bounds how long a client write (anything except a +// volume server's own primary-to-replica forward) waits for upload budget, +// whatever -inflightUploadDataTimeout says. // -// This function implements upload throttling to prevent overwhelming the volume server -// with too many concurrent uploads. It excludes replication traffic from limits. -// -// Returns: -// - true: Request should proceed with upload processing (no limit, within limit, -// or successfully waited for capacity) -// - false: Request failed (timeout or cancellation), error response already sent -// -// Special Handling: -// - Replication requests (type=replicate) bypass upload limits -// - No upload limit configured (concurrentUploadLimit=0) allows all uploads -func (vs *VolumeServer) checkUploadLimit(w http.ResponseWriter, r *http.Request) bool { - // exclude the replication from the concurrentUploadLimitMB - if vs.concurrentUploadLimit == 0 || r.URL.Query().Get("type") == "replicate" { - return true +// Invariant: it stays below operation.uploadBodyMinWait (10s), so the volume +// server answers 503 before the uploading client's body deadline cuts the +// request off as a stall. Only gateway chunk uploads that opt in +// (UploadOption.BodyDeadline: S3 chunk writes and the filer's chunk loop) carry +// that deadline; other clients keep the stall watchdog only. +const volumeClientUploadWaitCap = 5 * time.Second + +// uploadRejectCloseThreshold is the body size above which a rejected HTTP/1 +// upload is answered with Connection: close. Smaller bodies are cheaper to +// drain than a new connection is to dial, so they keep the pooled connection. +const uploadRejectCloseThreshold = 256 << 10 + +// errUploadUncountable refuses even a replica forward: its size would wrap +// inFlightUploadDataSize negative and let later uploads past admission. +var errUploadUncountable = errors.New("upload size overflows the in-flight upload counter") + +// uploadCharge returns the bytes an upload reserves against +// concurrentUploadLimit. A known length is charged as-is. An unknown length +// (chunked transfer) counts as one chunk, fileSizeLimitBytes, but at most half +// the budget (and at least 1 byte): charged the whole limit, a chunked upload +// would only be admitted on an idle server; charged half, it is admitted while +// at most half the budget is in use. Counting the bytes it actually sends is +// left to a later phase. +func (vs *VolumeServer) uploadCharge(r *http.Request) int64 { + unknownCharge := vs.fileSizeLimitBytes + if vs.concurrentUploadLimit > 0 { + unknownCharge = min(unknownCharge, max(vs.concurrentUploadLimit/2, 1)) } - - inFlightUploadDataSize := atomic.LoadInt64(&vs.inFlightUploadDataSize) - stats.VolumeServerInFlightUploadSize.Set(float64(inFlightUploadDataSize)) - - if inFlightUploadDataSize <= vs.concurrentUploadLimit { - return true - } - - return vs.waitForUploadSlot(w, r) + return util.CountedUploadSize(r.ContentLength, unknownCharge) } -// waitForUploadSlot waits for available upload capacity with timeout. +// clientUploadWait is how long a client write waits for upload budget: +// -inflightUploadDataTimeout, at most volumeClientUploadWaitCap (also when +// the timeout is 0). +func (vs *VolumeServer) clientUploadWait() time.Duration { + if vs.inflightUploadDataTimeout > 0 && vs.inflightUploadDataTimeout < volumeClientUploadWaitCap { + return vs.inflightUploadDataTimeout + } + return volumeClientUploadWaitCap +} + +// waitForUploadSlot reserves charged bytes of upload budget for r. // // Returns: -// - true: Upload capacity became available, request should proceed -// - false: Request failed (timeout or cancellation), error response already sent +// - true: charged bytes were added to inFlightUploadDataSize; the caller +// owns them and must give them back with releaseUploadSlot(charged). +// - false: nothing was reserved and the response was already written. +// +// Admission: +// - concurrentUploadLimit == 0: counted without a lock, never refused. +// - Primary-to-replica forwards (operation.IsReplicaForward): counted under +// the lock, never refused, so a write the primary already accepted always +// reaches its replicas. +// - Everything else, including a gateway's ?type=replicate&src=client +// fan-out: waits up to clientUploadWait until util.UploadAdmits, then +// reserves before the lock is released. // // HTTP Status Codes: -// - 429 Too Many Requests: Wait timeout exceeded -// - 499 Client Closed Request: Request cancelled by client -func (vs *VolumeServer) waitForUploadSlot(w http.ResponseWriter, r *http.Request) bool { - var timerUpload *time.Timer - inFlightUploadDataSize := atomic.LoadInt64(&vs.inFlightUploadDataSize) - - for inFlightUploadDataSize > vs.concurrentUploadLimit { - if timerUpload == nil { - timerUpload = time.NewTimer(vs.inflightUploadDataTimeout) - defer timerUpload.Stop() - } - - glog.V(4).Infof("wait because inflight upload data %d > %d", inFlightUploadDataSize, vs.concurrentUploadLimit) - stats.VolumeServerHandlerCounter.WithLabelValues(stats.UploadLimitCond).Inc() - - switch util.WaitWithTimeout(r.Context(), vs.inFlightUploadDataLimitCond, timerUpload) { - case http.StatusTooManyRequests: - err := fmt.Errorf("reject because inflight upload data %d > %d, and wait timeout", - inFlightUploadDataSize, vs.concurrentUploadLimit) - glog.V(1).Infof("too many requests: %v", err) - writeJsonError(w, r, http.StatusTooManyRequests, err) - return false - case util.HttpStatusCancelled: - glog.V(1).Infof("request cancelled from %s: %v", r.RemoteAddr, r.Context().Err()) - writeJsonError(w, r, util.HttpStatusCancelled, r.Context().Err()) - return false - } - - inFlightUploadDataSize = atomic.LoadInt64(&vs.inFlightUploadDataSize) - stats.VolumeServerInFlightUploadSize.Set(float64(inFlightUploadDataSize)) +// - 503 Service Unavailable with Retry-After: no budget within the wait. +// The body is never read; an HTTP/1 connection carrying a large or +// unknown-length body is closed rather than drained. +// - 499 Client Closed Request: the client went away while waiting. +func (vs *VolumeServer) waitForUploadSlot(w http.ResponseWriter, r *http.Request, charged int64) bool { + if vs.concurrentUploadLimit == 0 { + inFlight := atomic.AddInt64(&vs.inFlightUploadDataSize, charged) + stats.VolumeServerInFlightUploadSize.Set(float64(inFlight)) + return true } - return true + + limit := vs.concurrentUploadLimit + var inFlight int64 + var err error + vs.inFlightUploadDataLimitCond.L.Lock() + if !operation.IsReplicaForward(r.URL.Query()) { + admits := func() bool { + inFlight = atomic.LoadInt64(&vs.inFlightUploadDataSize) + return util.UploadAdmits(inFlight, charged, limit) + } + if !admits() { + glog.V(4).Infof("wait because inflight upload data %d + %d > %d", inFlight, charged, limit) + stats.VolumeServerHandlerCounter.WithLabelValues(stats.UploadLimitCond).Inc() + err = util.WaitUntil(r.Context(), vs.inFlightUploadDataLimitCond, vs.clientUploadWait(), admits) + } + } + if err == nil { + inFlight = atomic.LoadInt64(&vs.inFlightUploadDataSize) + if charged > math.MaxInt64-inFlight { + err = errUploadUncountable + } else { + inFlight = atomic.AddInt64(&vs.inFlightUploadDataSize, charged) + } + } + // Set under the lock, so a concurrent release cannot leave the gauge on + // an older value than the counter. + stats.VolumeServerInFlightUploadSize.Set(float64(inFlight)) + vs.inFlightUploadDataLimitCond.L.Unlock() + + if err == nil { + return true + } + + if r.Context().Err() != nil { + glog.V(1).Infof("request cancelled from %s: %v", r.RemoteAddr, r.Context().Err()) + writeJsonError(w, r, util.HttpStatusCancelled, r.Context().Err()) + return false + } + w.Header().Set("Retry-After", "1") + if r.ProtoMajor == 1 { + if r.ContentLength < 0 || r.ContentLength > uploadRejectCloseThreshold { + w.Header().Set("Connection", "close") + } else if r.ContentLength > 0 { + // net/http drains an unread body before it writes the reply's + // headers, so a client withholding a small body would hold this + // 503 back until it sent one. Full duplex skips that drain: the + // reply goes out now, and the body is drained after it, which + // keeps the connection once the body arrives. Only net/http's own + // writer drains, so a writer without full duplex needs nothing. + _ = http.NewResponseController(w).EnableFullDuplex() + } + } + if err != errUploadUncountable { + err = fmt.Errorf("reject because inflight upload data %d + %d > %d, and wait timeout", + inFlight, charged, limit) + } + glog.V(1).Infof("too many requests: %v", err) + writeJsonError(w, r, http.StatusServiceUnavailable, err) + return false +} + +// releaseUploadSlot gives back charged bytes reserved by waitForUploadSlot +// and wakes the uploads waiting for budget. +func (vs *VolumeServer) releaseUploadSlot(charged int64) { + if vs.concurrentUploadLimit == 0 { + inFlight := atomic.AddInt64(&vs.inFlightUploadDataSize, -charged) + stats.VolumeServerInFlightUploadSize.Set(float64(inFlight)) + return + } + vs.inFlightUploadDataLimitCond.L.Lock() + inFlight := atomic.AddInt64(&vs.inFlightUploadDataSize, -charged) + stats.VolumeServerInFlightUploadSize.Set(float64(inFlight)) + vs.inFlightUploadDataLimitCond.Broadcast() + vs.inFlightUploadDataLimitCond.L.Unlock() } // handleGetRequest processes GET/HEAD requests with download limiting. @@ -224,29 +305,16 @@ func (vs *VolumeServer) handleGetRequest(w http.ResponseWriter, r *http.Request) // handleUploadRequest processes PUT/POST requests with upload limiting. // -// This function manages the complete upload request workflow: -// 1. Extracts content length from request headers -// 2. Applies upload concurrency limits with timeout handling -// 3. Tracks in-flight upload data size for monitoring -// 4. Delegates to PostHandler for actual file processing -// 5. Ensures proper cleanup of in-flight counters -// -// The upload limiting logic may reject the request with appropriate HTTP -// status codes (429 for timeout, 499 for cancellation). +// It reserves the request's charge (see uploadCharge) with +// waitForUploadSlot, hands the request to PostHandler, and releases the +// charge when PostHandler returns. A request that gets no budget is answered +// by waitForUploadSlot (503 on timeout, 499 on cancellation). func (vs *VolumeServer) handleUploadRequest(w http.ResponseWriter, r *http.Request) { - contentLength := getContentLength(r) - - if !vs.checkUploadLimit(w, r) { + charged := vs.uploadCharge(r) + if !vs.waitForUploadSlot(w, r, charged) { return } - - atomic.AddInt64(&vs.inFlightUploadDataSize, contentLength) - defer func() { - atomic.AddInt64(&vs.inFlightUploadDataSize, -contentLength) - if vs.concurrentUploadLimit != 0 { - vs.inFlightUploadDataLimitCond.Broadcast() - } - }() + defer vs.releaseUploadSlot(charged) // processes uploads stats.WriteRequest() diff --git a/weed/server/volume_server_handlers_upload_limit_test.go b/weed/server/volume_server_handlers_upload_limit_test.go new file mode 100644 index 0000000000..94a202fc86 --- /dev/null +++ b/weed/server/volume_server_handlers_upload_limit_test.go @@ -0,0 +1,369 @@ +package weed_server + +import ( + "bufio" + "bytes" + "context" + "fmt" + "io" + "math" + "net" + "net/http" + "net/http/httptest" + "strconv" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus/testutil" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/stats" + "github.com/stretchr/testify/require" +) + +func newUploadLimitVolumeServer(limit, inFlight int64, timeout time.Duration) *VolumeServer { + return &VolumeServer{ + concurrentUploadLimit: limit, + inFlightUploadDataSize: inFlight, + inflightUploadDataTimeout: timeout, + inFlightUploadDataLimitCond: sync.NewCond(new(sync.Mutex)), + fileSizeLimitBytes: 1 << 20, + } +} + +// countingBody records how many body bytes the handler read. +type countingBody struct { + data io.Reader + read atomic.Int64 +} + +func (b *countingBody) Read(p []byte) (int, error) { + n, err := b.data.Read(p) + b.read.Add(int64(n)) + return n, err +} + +func (b *countingBody) Close() error { return nil } + +// uploadRequest builds a POST whose body is size bytes; a negative size +// sends an unknown length (as a chunked upload does). +func uploadRequest(ctx context.Context, target string, size int64) (*http.Request, *countingBody) { + n := size + if n < 0 { + n = 1 << 10 + } + body := &countingBody{data: io.LimitReader(zeroReader{}, n)} + r := httptest.NewRequest(http.MethodPost, target, nil).WithContext(ctx) + r.Body = body + r.ContentLength = size + if size >= 0 { + r.Header.Set("Content-Length", strconv.FormatInt(size, 10)) + } + r.Header.Set("Content-Type", "application/octet-stream") + return r, body +} + +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + +func admitUpload(vs *VolumeServer, w http.ResponseWriter, r *http.Request) (bool, int64) { + charged := vs.uploadCharge(r) + return vs.waitForUploadSlot(w, r, charged), charged +} + +func TestUploadLimitRejectsWith503AfterTimeout(t *testing.T) { + for _, tc := range []struct { + name string + size int64 + wantClose bool + }{ + {name: "small body keeps the connection", size: 4, wantClose: false}, + {name: "large body closes the connection", size: 1 << 20, wantClose: true}, + {name: "unknown length closes the connection", size: -1, wantClose: true}, + } { + t.Run(tc.name, func(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 10, 50*time.Millisecond) + r, body := uploadRequest(context.Background(), "/1,0123456789abcdef", tc.size) + w := httptest.NewRecorder() + + ok, _ := admitUpload(vs, w, r) + + require.False(t, ok) + require.Equal(t, http.StatusServiceUnavailable, w.Code) + require.Equal(t, "1", w.Header().Get("Retry-After")) + if tc.wantClose { + require.Equal(t, "close", w.Header().Get("Connection")) + } else { + require.Empty(t, w.Header().Get("Connection")) + } + require.Zero(t, body.read.Load(), "rejected upload must not read the body") + require.Equal(t, int64(10), atomic.LoadInt64(&vs.inFlightUploadDataSize)) + }) + } +} + +func TestUploadLimitRefusesASizeTheCounterCannotHold(t *testing.T) { + for _, target := range []string{ + "/1,0123456789abcdef?type=replicate", + "/1,0123456789abcdef?type=replicate&src=client", + } { + vs := newUploadLimitVolumeServer(10, 4<<20, 50*time.Millisecond) + r, body := uploadRequest(context.Background(), target, math.MaxInt64) + w := httptest.NewRecorder() + + ok, _ := admitUpload(vs, w, r) + + require.False(t, ok, target) + require.Equal(t, http.StatusServiceUnavailable, w.Code, target) + require.Zero(t, body.read.Load(), target) + require.Equal(t, int64(4<<20), atomic.LoadInt64(&vs.inFlightUploadDataSize), target) + } +} + +func TestUploadLimitDoesNotOvershoot(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 8, 50*time.Millisecond) + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef", 4) + w := httptest.NewRecorder() + + ok, _ := admitUpload(vs, w, r) + + require.False(t, ok) + require.Equal(t, http.StatusServiceUnavailable, w.Code) + require.Equal(t, int64(8), atomic.LoadInt64(&vs.inFlightUploadDataSize)) +} + +func TestUploadLimitAdmitsWhenSlotFrees(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 10, 5*time.Second) + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef", 4) + w := httptest.NewRecorder() + + waits := stats.VolumeServerHandlerCounter.WithLabelValues(stats.UploadLimitCond) + baseline := testutil.ToFloat64(waits) + got := make(chan bool, 1) + go func() { + ok, _ := admitUpload(vs, w, r) + got <- ok + }() + // The waiter counts itself under the cond's lock, which it only gives up + // inside cond.Wait: once the count moves, the release below (which takes + // that lock) can only run while the waiter is parked, so it is the + // broadcast that admits it. + parkDeadline := time.Now().Add(5 * time.Second) + for testutil.ToFloat64(waits) == baseline { + if time.Now().After(parkDeadline) { + t.Fatal("the upload never started waiting for a slot") + } + time.Sleep(time.Millisecond) + } + vs.releaseUploadSlot(10) + + select { + case ok := <-got: + require.True(t, ok) + case <-time.After(time.Second): + t.Fatal("waiter missed the released upload slot") + } + require.Equal(t, int64(4), atomic.LoadInt64(&vs.inFlightUploadDataSize)) +} + +func TestUploadLimitAdmitsOversizedWhenIdle(t *testing.T) { + // A 5s wait, so admitted at once and waited out stay far apart under a + // CI-safe bound. + vs := newUploadLimitVolumeServer(10, 0, 5*time.Second) + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef", 100) + w := httptest.NewRecorder() + + start := time.Now() + ok, charged := admitUpload(vs, w, r) + + require.True(t, ok) + require.Less(t, time.Since(start), time.Second) + require.Equal(t, int64(100), charged) + require.Equal(t, int64(100), atomic.LoadInt64(&vs.inFlightUploadDataSize)) +} + +func TestUploadLimitCountsGatewayHolderWrites(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 10, 50*time.Millisecond) + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef?type=replicate&src=client", 4) + w := httptest.NewRecorder() + + ok, _ := admitUpload(vs, w, r) + + require.False(t, ok) + require.Equal(t, http.StatusServiceUnavailable, w.Code) +} + +func TestUploadLimitLetsPrimaryForwardsThrough(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 10, 5*time.Second) + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef?type=replicate", 4) + w := httptest.NewRecorder() + + start := time.Now() + ok, charged := admitUpload(vs, w, r) + + require.True(t, ok) + require.Less(t, time.Since(start), time.Second) + require.Equal(t, int64(4), charged) + require.Equal(t, int64(14), atomic.LoadInt64(&vs.inFlightUploadDataSize)) +} + +func TestUploadLimitChargesUnknownLength(t *testing.T) { + vs := newUploadLimitVolumeServer(1<<30, 0, 50*time.Millisecond) + vs.fileSizeLimitBytes = 64 + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef", -1) + w := httptest.NewRecorder() + + ok, charged := admitUpload(vs, w, r) + + require.True(t, ok) + require.Equal(t, int64(64), charged) + require.Equal(t, int64(64), atomic.LoadInt64(&vs.inFlightUploadDataSize)) +} + +func TestUploadLimitChargesUnknownLengthHalfTheBudget(t *testing.T) { + t.Run("admitted while at most half the budget is in use", func(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 4, 5*time.Second) + vs.fileSizeLimitBytes = 100 + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef", -1) + w := httptest.NewRecorder() + + start := time.Now() + ok, charged := admitUpload(vs, w, r) + + require.True(t, ok) + require.Less(t, time.Since(start), time.Second) + require.Equal(t, int64(5), charged) + require.Equal(t, int64(9), atomic.LoadInt64(&vs.inFlightUploadDataSize)) + }) + t.Run("waits when more than half the budget is in use", func(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 6, 50*time.Millisecond) + vs.fileSizeLimitBytes = 100 + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef", -1) + w := httptest.NewRecorder() + + ok, _ := admitUpload(vs, w, r) + + require.False(t, ok) + require.Equal(t, http.StatusServiceUnavailable, w.Code) + require.Equal(t, int64(6), atomic.LoadInt64(&vs.inFlightUploadDataSize)) + }) + t.Run("limit of one byte still charges one byte", func(t *testing.T) { + vs := newUploadLimitVolumeServer(1, 0, 50*time.Millisecond) + vs.fileSizeLimitBytes = 100 + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef", -1) + + require.Equal(t, int64(1), vs.uploadCharge(r)) + }) +} + +func TestUploadLimitZeroCountsWithoutWaiting(t *testing.T) { + vs := newUploadLimitVolumeServer(0, 1<<40, 50*time.Millisecond) + r, _ := uploadRequest(context.Background(), "/1,0123456789abcdef", 4) + w := httptest.NewRecorder() + + ok, charged := admitUpload(vs, w, r) + require.True(t, ok) + require.Equal(t, int64(1<<40+4), atomic.LoadInt64(&vs.inFlightUploadDataSize)) + + vs.releaseUploadSlot(charged) + require.Equal(t, int64(1<<40), atomic.LoadInt64(&vs.inFlightUploadDataSize)) +} + +func TestUploadLimitClientGoneAnswers499(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 10, 5*time.Second) + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(20*time.Millisecond, cancel) + r, body := uploadRequest(ctx, "/1,0123456789abcdef", 4) + w := httptest.NewRecorder() + + ok, _ := admitUpload(vs, w, r) + + require.False(t, ok) + require.Equal(t, 499, w.Code) + require.Zero(t, body.read.Load()) + require.Equal(t, int64(10), atomic.LoadInt64(&vs.inFlightUploadDataSize)) +} + +func TestUploadLimitClientWaitIsCapped(t *testing.T) { + for _, tc := range []struct { + timeout time.Duration + want time.Duration + }{ + {timeout: 0, want: volumeClientUploadWaitCap}, + {timeout: 50 * time.Millisecond, want: 50 * time.Millisecond}, + {timeout: time.Minute, want: volumeClientUploadWaitCap}, + } { + vs := newUploadLimitVolumeServer(10, 0, tc.timeout) + require.Equal(t, tc.want, vs.clientUploadWait(), "timeout %v", tc.timeout) + } +} + +func TestUploadLimit503ReachesGoClientForLargeBody(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 10, 50*time.Millisecond) + srv := httptest.NewServer(http.HandlerFunc(vs.handleUploadRequest)) + defer srv.Close() + + req, err := http.NewRequest(http.MethodPost, srv.URL+"/1,0123456789abcdef", bytes.NewReader(make([]byte, 8<<20))) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/octet-stream") + + resp, err := srv.Client().Do(req) + require.NoError(t, err, "client must see the 503, not a write error") + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, resp.Body) + require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode) + require.Equal(t, "1", resp.Header.Get("Retry-After")) +} + +// An upload admitted through handleUploadRequest gives its charge back when +// the handler returns, whatever the handler answered, so in-flight returns to +// its baseline. +func TestHandleUploadRequestReleasesItsCharge(t *testing.T) { + for _, limit := range []int64{0, 10} { + vs := newUploadLimitVolumeServer(limit, 3, 5*time.Second) + vs.guard = security.NewGuard(nil, "", 0, "", 0, "", "") + // Not a volume id, so PostHandler answers 400 without a store. + r, _ := uploadRequest(context.Background(), "/notavolume,0123456789abcdef", 4) + w := httptest.NewRecorder() + + vs.handleUploadRequest(w, r) + + require.Equal(t, http.StatusBadRequest, w.Code, "limit %d: the request must reach PostHandler", limit) + require.Equal(t, int64(3), atomic.LoadInt64(&vs.inFlightUploadDataSize), "limit %d", limit) + } +} + +// A rejected HTTP/1 upload with a small body keeps its pooled connection, so +// net/http would drain that body before writing the 503's headers. A client +// that declares a few bytes and withholds them must still get the 503 once the +// admission wait ends, not when it gets round to sending the body. +func TestUploadLimitAnswersAWithheldSmallBodyAtOnce(t *testing.T) { + vs := newUploadLimitVolumeServer(10, 10, 50*time.Millisecond) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w = stats.NewStatusResponseWriter(w) + if ok, charged := admitUpload(vs, w, r); ok { + vs.releaseUploadSlot(charged) + w.WriteHeader(http.StatusCreated) + } + })) + defer srv.Close() + + conn, err := net.Dial("tcp", srv.Listener.Addr().String()) + require.NoError(t, err) + defer conn.Close() + start := time.Now() + _, err = fmt.Fprintf(conn, "POST /1,0123456789abcdef HTTP/1.1\r\nHost: volume\r\nContent-Length: 4\r\n\r\n") + require.NoError(t, err) + require.NoError(t, conn.SetReadDeadline(time.Now().Add(3*time.Second))) + resp, err := http.ReadResponse(bufio.NewReader(conn), nil) + require.NoError(t, err, "no reply while the body was withheld") + defer resp.Body.Close() + require.Equal(t, http.StatusServiceUnavailable, resp.StatusCode) + require.Less(t, time.Since(start), 2*time.Second) + require.Empty(t, resp.Header.Get("Connection"), "a small body keeps the connection") +} diff --git a/weed/util/cond_wait.go b/weed/util/cond_wait.go index 815ceb54af..7a1c6446c3 100644 --- a/weed/util/cond_wait.go +++ b/weed/util/cond_wait.go @@ -2,35 +2,12 @@ package util import ( "context" - "net/http" "sync" "time" ) const HttpStatusCancelled = 499 -func WaitWithTimeout(ctx context.Context, cond *sync.Cond, timer *time.Timer) int { - waitDone := make(chan struct{}) - - go func() { - cond.L.Lock() - defer cond.L.Unlock() - cond.Wait() - defer close(waitDone) - }() - - select { - case <-waitDone: - return http.StatusOK - case <-timer.C: - cond.Broadcast() - return http.StatusTooManyRequests - case <-ctx.Done(): - cond.Broadcast() - return HttpStatusCancelled - } -} - // WaitUntil waits on cond, whose lock the caller holds, until ready returns // true, ctx is done, or timeout elapses; a zero timeout waits without a bound. func WaitUntil(ctx context.Context, cond *sync.Cond, timeout time.Duration, ready func() bool) error { diff --git a/weed/util/upload_admission.go b/weed/util/upload_admission.go new file mode 100644 index 0000000000..607d7fe17e --- /dev/null +++ b/weed/util/upload_admission.go @@ -0,0 +1,27 @@ +package util + +// UploadAdmits reports whether a request of size bytes may start while +// inFlight bytes of uploads are already admitted under limit. +// +// A limit of 0 means unlimited. A request is always admitted when nothing +// else is in flight (inFlight == 0), even if size alone exceeds limit; +// otherwise an oversized request would never start. Otherwise the request +// is admitted only if inFlight+size stays within limit. The sum is never +// formed, so a huge size cannot wrap around and pass the check. +func UploadAdmits(inFlight, size, limit int64) bool { + if limit == 0 || inFlight == 0 { + return true + } + return inFlight <= limit && size <= limit-inFlight +} + +// CountedUploadSize returns the number of bytes an upload charges against +// the admission limit. A known contentLength (>= 0) is charged as-is. An +// unknown length (< 0, e.g. chunked transfer) is charged unknownCharge so +// that such requests still count toward the limit. +func CountedUploadSize(contentLength, unknownCharge int64) int64 { + if contentLength >= 0 { + return contentLength + } + return unknownCharge +} diff --git a/weed/util/upload_admission_test.go b/weed/util/upload_admission_test.go new file mode 100644 index 0000000000..9d3568eae0 --- /dev/null +++ b/weed/util/upload_admission_test.go @@ -0,0 +1,37 @@ +package util + +import ( + "math" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestUploadAdmits(t *testing.T) { + cases := []struct { + name string + inFlight, size, limit int64 + want bool + }{ + {"unlimited", 1 << 40, 1 << 30, 0, true}, + {"fits exactly", 6, 4, 10, true}, + {"would overshoot", 8, 4, 10, false}, + {"oversized alone", 0, 100, 10, true}, + {"oversized behind others", 1, 100, 10, false}, + {"zero size at limit", 10, 0, 10, true}, + {"size that would wrap the sum", 11, math.MaxInt64, 10, false}, + {"max size behind a small upload", 1, math.MaxInt64, 10, false}, + {"already over the limit", 11, 0, 10, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + require.Equal(t, c.want, UploadAdmits(c.inFlight, c.size, c.limit)) + }) + } +} + +func TestCountedUploadSize(t *testing.T) { + require.Equal(t, int64(0), CountedUploadSize(0, 8<<20)) + require.Equal(t, int64(123), CountedUploadSize(123, 8<<20)) + require.Equal(t, int64(8<<20), CountedUploadSize(-1, 8<<20)) +} diff --git a/weed/util/upload_charge.go b/weed/util/upload_charge.go new file mode 100644 index 0000000000..19f55d4457 --- /dev/null +++ b/weed/util/upload_charge.go @@ -0,0 +1,21 @@ +package util + +// GatewayUploadCharge returns the bytes a gateway (S3 or filer) upload reserves +// against its in-flight upload budget. +// +// A request never holds more than its chunk buffers: at most four chunks, the +// per-request cap in the chunked uploader. So a known length is charged +// min(length, 4*chunk), not its declared size, or a multi-GB PUT would wait for +// an idle gateway. An unknown length (chunked transfer) counts as one chunk. +// When the budget limit is positive the charge is also capped at half of it +// (and at least 1 byte), as the volume server does: charged the whole limit, a +// request would only be admitted on an idle server; charged half, it is admitted +// while at most half the budget is in use. With limit 0 the charge is still +// computed, because the byte counters are kept for metrics and circuit breakers. +func GatewayUploadCharge(declared, chunk, limit int64) int64 { + charge := min(CountedUploadSize(declared, chunk), 4*chunk) + if limit > 0 { + charge = min(charge, max(limit/2, 1)) + } + return charge +}