Compare commits

..

2 Commits

Author SHA1 Message Date
Hauser Zhi b71942cf26 fix(admin): report native listing admission independently of GET (#9859)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 21:15:18 +08:00
RustFS ad9b5e29e6 fix(s3,ecstore): mitigate high-concurrency 503 cascades and 500 leaks (#9857)
* fix(s3,ecstore): mitigate high-concurrency 503 cascades and 500 leaks

Eliminate HTTP 500 InternalError leakage under internode RPC saturation, isolate high-concurrency S3 HTTP/503 root causes with machine-parseable telemetry, and mitigate quorum/lock/breaker cascades across distributed 4x4 clusters:

1. S3 503 root-cause attribution & Prometheus telemetry:
   - Propagate `x-rustfs-503-subcause` (via `classify_s3_503_subcause` and `scope_503_subcause` alongside `x-rustfs-error-cause`) across S3 and readiness responses when returning HTTP 503 (`ServiceUnavailable`, `SlowDown`, `SlowDownRead`, `Busy`).
   - Export `rustfs_s3_503_responses_total{code, subcause}` on `/rustfs/v2/metrics` via `rustfs-io-metrics` without per-object cardinality explosion.

2. Eliminate HTTP 500 leaks under transient internode transport pressure:
   - Map `StorageError::BackendUnavailable` and `StorageError::BackendTimeout` to S3 503 `SlowDown` instead of falling through to 500 `InternalError`.
   - Stop evicting shared `tonic::Channel` connections on RPC deadlines or non-broken-transport errors when a peer remains active (`is_host_considered_healthy`), preventing mid-flight `Status::cancelled` collateral damage across concurrent shards and lock batches; map transient `Status::cancelled` on `RemoteDisk` to `DiskError::FaultyRemoteDisk`.
   - Classify `InternodeHttpErrorKind::Unknown` with `operation().is_some()` in `is_unavailable_internode_http_error` and check `UnexpectedEof` / `hyper::Error::is_closed()` / `is_canceled()` after the body-phase guard in `rustfs-rio` `HttpReader` so pre-body pooled keep-alive resets retry cleanly without hiding mid-body stream aborts.

3. Mitigate distributed write-quorum, lock, and circuit-breaker cascades:
   - Enable internode bulk/control gRPC channel isolation by default (`DEFAULT_INTERNODE_CHANNEL_ISOLATION = true`), raise control concurrency (`64 -> 256`), bulk pool size (`2 -> 4`), HTTP/2 stream window (`1 MiB -> 4 MiB`), connection window (`2 MiB -> 16 MiB`), and internode HTTP pool idle capacity (`16 -> 128`, `90s` timeout).
   - Cap distributed lock backoff ceiling (`80ms -> 25ms` base ceiling) and scope anchor-voter pre-acquisition serialization strictly to exclusive writer retries (`attempt > 1`) so first-attempt single-object PUTs run full parallel quorum fanout while contended hot-key writers still prevent livelock.
   - Tune circuit-breaker failure threshold (`5 -> 20`), sliding window (`10s -> 5s`), open cooldown (`5s -> 1s`), and half-open probe concurrency (`3 -> 8`) to stop self-amplifying 5s cluster-wide 503 blackouts after sub-second bursts.

Fixes https://github.com/rustfs/backlog/issues/3402

Signed-off-by: RustFS <hello@rustfs.com>

* fix(ecstore,lock,s3): address PR review findings and add tests

- Split drive-scoped mark_faulty (self.health.completed_ops()) from host-scoped tonic::Channel eviction (host_completed_ops(&self.addr)) in RemoteDisk so sibling progress on the same peer does not keep a stalled drive Online, with regression test sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault.
- Restrict anchor_serialized early return in DistributedLock::acquire_lock_quorum_once_inner strictly to definitive lock contention (is_definitive_lock_contention) so anchor timeouts or open request-breakers fall through to remaining voters, with regression test exclusive_retry_fans_out_to_remaining_voters_when_anchor_times_out_or_breaker_opens.
- Pass LockRequestAdmission into RemoteClient::record_request_timeout and require the active probe_generation before escalating an existing backoff window, with regression test late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe.
- Record rustfs_s3_503_responses_total(ServiceUnavailable, readiness_pending) in service_not_ready_response without double-counting and assert both header and counter in service_not_ready_response_preserves_observable_contract.
- Wire matching ObjectWriteStalled / ObjectReadStalled traffic-stall overlays into ClusterWrite and ClusterRead health reports while keeping StartupFinalizationPending scoped to node readiness.

Signed-off-by: RustFS <hello@rustfs.com>

---------

Signed-off-by: RustFS <hello@rustfs.com>
2026-12-02 20:53:48 +08:00
27 changed files with 1346 additions and 290 deletions
+18 -18
View File
@@ -71,15 +71,15 @@ const _: () = assert!(DEFAULT_INTERNODE_RPC_TCP_NODELAY);
/// unary responses such as `ReadMultiple` and `BatchReadVersion`. Set to 0 to use the
/// `tonic`/`hyper` default. Defaults to 1MiB.
pub const ENV_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024;
/// HTTP/2 initial connection window size (bytes) for internode gRPC client channels.
///
/// Should be >= the stream window so multiple concurrent streams are not starved by the
/// connection-level flow-control window. Set to 0 to fall back to the library default.
/// Defaults to 2MiB.
/// Defaults to 16MiB.
pub const ENV_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 2 * 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
// Compile-time invariant: the connection-level window must be >= the per-stream window, or
// concurrent streams would be starved by the connection-level flow-control budget.
@@ -284,23 +284,23 @@ pub const DEFAULT_INTERNODE_IDEMPOTENT_READ_RETRIES: usize = 1;
/// Enable control/bulk internode gRPC channel isolation.
///
/// Defaults to `false`: this touches lock-RPC transport routing (consistency-sensitive), so it
/// is opt-in and validated against a baseline before rollout. When `false`, bulk RPCs reuse the
/// control channel exactly as before, so the switch is a single-env rollback.
/// Defaults to `true` so bulk `ReadAll`/`WriteAll`/`ReadMultiple`/`BatchReadVersion` transfers
/// use dedicated bulk HTTP/2 channels instead of head-of-line blocking latency-sensitive
/// `Lock`/`UnLock`/`Refresh`/`DiskInfo` control RPCs under high concurrency. Set
/// `RUSTFS_INTERNODE_CHANNEL_ISOLATION=false` for single-env rollback to legacy shared-channel behavior.
pub const ENV_INTERNODE_CHANNEL_ISOLATION: &str = "RUSTFS_INTERNODE_CHANNEL_ISOLATION";
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = false;
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = true;
// Compile-time invariant: isolation is opt-in so the default build behaves exactly as before P1.
const _: () = assert!(!DEFAULT_INTERNODE_CHANNEL_ISOLATION);
// Compile-time invariant: channel isolation defaults on so bulk data RPCs cannot starve lock/quorum RPCs.
const _: () = assert!(DEFAULT_INTERNODE_CHANNEL_ISOLATION);
/// Number of bulk channels maintained per peer when channel isolation is enabled.
///
/// A tonic `Channel` is a single TCP/HTTP2 connection; multiple bulk channels are round-robined
/// to relieve the single-connection throughput ceiling for large transfers. Kept small (default
/// 2) to avoid a connection storm; clamped to at least 1. Set to 1 to isolate bulk onto a single
/// dedicated connection (still separate from control).
/// to relieve the single-connection throughput ceiling for large transfers. Defaults to 4 (matching
/// typical 4-drive-per-node stripes); clamped to at least 1.
pub const ENV_INTERNODE_BULK_CHANNELS: &str = "RUSTFS_INTERNODE_BULK_CHANNELS";
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 2;
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 4;
/// Optional receive-window overrides for isolated bulk channels. When unset, inherit the
/// corresponding `RUSTFS_INTERNODE_RPC_HTTP2_*` setting. Zero selects the library default.
@@ -310,7 +310,7 @@ pub const ENV_INTERNODE_BULK_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_BU
/// Transport admission and pending-buffer limits for isolated bulk channels. These limits
/// apply to the tonic service; complete unary bodies are observed separately by RPC metrics.
pub const ENV_INTERNODE_BULK_CONCURRENCY_LIMIT: &str = "RUSTFS_INTERNODE_BULK_CONCURRENCY_LIMIT";
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 64;
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 128;
pub const ENV_INTERNODE_BULK_BUFFER_SIZE: &str = "RUSTFS_INTERNODE_BULK_BUFFER_SIZE";
pub const DEFAULT_INTERNODE_BULK_BUFFER_SIZE: usize = 1024;
@@ -501,8 +501,8 @@ mod tests {
#[test]
fn internode_rpc_channel_tuning_defaults() {
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 2 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 4 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 16 * 1024 * 1024);
// The nodelay-on and connection-window >= stream-window invariants are enforced at
// compile time next to the constant definitions.
}
@@ -525,8 +525,8 @@ mod tests {
#[test]
fn internode_channel_isolation_defaults_and_env_names() {
// The isolation-off default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 2);
// The isolation-on default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 4);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, 0);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_WAIT_TIMEOUT_MS, 1_000);
assert_eq!(ENV_INTERNODE_CHANNEL_ISOLATION, "RUSTFS_INTERNODE_CHANNEL_ISOLATION");
+1 -1
View File
@@ -482,7 +482,7 @@ pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MIN_SIZE_BYTES: usize = 0;
/// A short wait smooths transient bursts while still returning S3
/// `SlowDown`/503 before body ingest when the node is already saturated.
pub const ENV_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = "RUSTFS_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS";
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250;
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 2_000;
/// Time in milliseconds a multipart UploadPart waits for a foreground write permit.
///
+181 -27
View File
@@ -1484,6 +1484,33 @@ static HOST_TIMEOUT_DEGRADATION: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, HostTimeoutDegradationState>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
static HOST_RPC_PROGRESS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, Arc<std::sync::atomic::AtomicU64>>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
fn host_progress_counter(addr: &str) -> Arc<std::sync::atomic::AtomicU64> {
let mut map = HOST_RPC_PROGRESS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(counter) = map.get(addr) {
return Arc::clone(counter);
}
let counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
map.insert(addr.to_owned(), Arc::clone(&counter));
counter
}
pub(crate) fn host_completed_ops(addr: &str) -> u64 {
let Ok(map) = HOST_RPC_PROGRESS.lock() else {
return 0;
};
map.get(addr)
.map_or(0, |counter| counter.load(std::sync::atomic::Ordering::Acquire))
}
fn record_host_rpc_success(addr: &str) {
host_progress_counter(addr).fetch_add(1, std::sync::atomic::Ordering::AcqRel);
clear_host_timeout_degradation(addr);
}
fn record_host_disk_timeout(addr: &str, endpoint: &str) {
let now = tokio::time::Instant::now();
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
@@ -2506,10 +2533,17 @@ impl RemoteDisk {
/// same host to time out within the correlation window, so a single slow HDD
/// never engages host-level fast-fail while a `SIGSTOP`'d peer holding 4
/// drives fast-fails immediately on subsequent requests.
pub(crate) fn record_straggler_timeout(&self) {
pub(crate) fn record_straggler_timeout_if_stalled(&self, host_completed_before: u64) {
if host_completed_ops(&self.addr) > host_completed_before {
return;
}
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
}
pub(crate) fn host_completed_ops(&self) -> u64 {
host_completed_ops(&self.addr)
}
/// On-demand bounded recovery probe used only when a read is about to fail read quorum due to
/// `FaultyDisk` remote drives (e.g., drives waiting in `Returning` right after a rolling restart).
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
@@ -2520,7 +2554,7 @@ impl RemoteDisk {
else {
return false;
};
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
rustfs_io_metrics::internode_metrics::record_peer_reachable(&self.addr);
self.health
.mark_peer_restarted_online(&self.endpoint, "on_demand_quorum_recovery_probe_success")
@@ -2623,6 +2657,7 @@ impl RemoteDisk {
.unwrap_or_else(|| time::sleep(timeout_duration).deadline())
});
let max_retries = internode_idempotent_read_retries();
let drive_completed_before = self.health.completed_ops();
let mut attempt = 0usize;
loop {
let attempt_timeout = deadline
@@ -2647,7 +2682,9 @@ impl RemoteDisk {
return Err(err);
}
if matches!(err, DiskError::Timeout) && deadline.is_some_and(|deadline| time::Instant::now() >= deadline) {
self.mark_faulty("read_operation_deadline");
if self.health.completed_ops() == drive_completed_before {
self.mark_faulty("read_operation_deadline");
}
return Err(err);
}
attempt += 1;
@@ -2739,37 +2776,61 @@ impl RemoteDisk {
let _waiting_guard = self.health.waiting_guard();
if timeout_duration == Duration::ZERO {
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let operation_result = operation().await;
if operation_result.is_ok() {
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
return operation_result;
}
// Execute operation with timeout
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let result = time::timeout(timeout_duration, operation()).await;
match result {
Ok(operation_result) => {
// Log success; the waiting guard balances every exit path.
if operation_result.is_ok() {
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
operation_result
}
Err(_) => {
self.record_timeout(op, timeout_duration);
if failure_health_action == FailureHealthAction::MarkFailure {
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
self.mark_faulty_and_evict("operation_timeout").await;
self.mark_faulty_with_eviction("operation_timeout", host_stalled).await;
}
Err(DiskError::Timeout)
}
@@ -2790,17 +2851,32 @@ impl RemoteDisk {
self.record_timeout(op, timeout_duration);
return Err(DiskError::Timeout);
}
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
match time::timeout(timeout_duration, operation()).await {
Ok(operation_result) => {
if operation_result.is_ok() {
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
let evict = operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(op, timeout_duration, &operation_result, FailureHealthAction::IgnoreFailure)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
let evict = drive_stalled
&& host_stalled
&& operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
FailureHealthAction::IgnoreFailure,
drive_stalled,
host_stalled,
)
.await;
if evict {
evict_failed_connection_with_reason(
&self.addr,
@@ -2813,12 +2889,16 @@ impl RemoteDisk {
}
Err(_) => {
self.record_timeout(op, timeout_duration);
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
if self.health.completed_ops() == drive_completed_before
&& host_completed_ops(&self.addr) == host_completed_before
{
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
}
Err(DiskError::Timeout)
}
}
@@ -2853,6 +2933,8 @@ impl RemoteDisk {
timeout_duration: Duration,
operation_result: &Result<T>,
failure_health_action: FailureHealthAction,
drive_stalled: bool,
host_stalled: bool,
) {
if let Err(err) = operation_result
&& !err.is_metacache_output_stream_closed()
@@ -2878,8 +2960,8 @@ impl RemoteDisk {
"Remote disk operation returned network-like error"
);
}
if failure_health_action == FailureHealthAction::MarkFailure {
self.mark_faulty_and_evict("operation_network_error").await;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
self.mark_faulty_with_eviction("operation_network_error", host_stalled).await;
}
}
}
@@ -2925,8 +3007,8 @@ impl RemoteDisk {
state != previous_state
}
async fn mark_faulty_and_evict(&self, reason: &'static str) {
if self.mark_faulty(reason) {
async fn mark_faulty_with_eviction(&self, reason: &'static str, evict_connection: bool) {
if self.mark_faulty(reason) && evict_connection {
counter!(
"rustfs_drive_connection_evict_total",
"endpoint" => self.endpoint.to_string(),
@@ -15034,4 +15116,76 @@ mod tests {
"host degradation must clear immediately after a successful RPC"
);
}
#[tokio::test]
async fn sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault() {
async fn make_drive(port: u16, disk_idx: i32) -> RemoteDisk {
let url = url::Url::parse(&format!("http://127.0.0.1:{port}/data{disk_idx}")).expect("endpoint url");
let endpoint = Endpoint {
url,
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx,
};
RemoteDisk::new(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
Arc::new(TcpHttpInternodeDataTransport),
)
.await
.expect("remote disk handle")
}
let stalled_drive = make_drive(59985, 0).await;
let sibling_drive = make_drive(59985, 1).await;
let addr = stalled_drive.addr.clone();
clear_host_timeout_degradation(&addr);
let dummy_channel = tonic::transport::Endpoint::from_static("http://127.0.0.1:59985").connect_lazy();
rustfs_common::cache_connection(addr.clone(), dummy_channel).await;
assert!(rustfs_common::has_cached_connection(&addr).await);
// Start a slow operation on `stalled_drive` while `sibling_drive` on the same host
// completes an RPC before `stalled_drive` times out.
let sibling_ref = &sibling_drive;
let err = stalled_drive
.execute_with_timeout_for_op_and_health_action(
"write_all",
|| async move {
sibling_ref
.execute_with_timeout_for_op_and_health_action(
"read_all",
|| async { Ok::<(), Error>(()) },
Duration::from_secs(1),
FailureHealthAction::MarkFailure,
)
.await
.expect("sibling drive RPC succeeds");
tokio::time::sleep(Duration::from_millis(80)).await;
Ok::<(), Error>(())
},
Duration::from_millis(20),
FailureHealthAction::MarkFailure,
)
.await
.expect_err("stalled drive must time out");
assert!(matches!(err, DiskError::Timeout));
assert_ne!(
stalled_drive.runtime_state(),
RuntimeDriveHealthState::Online,
"sibling drive progress must not suppress mark_faulty on the drive that actually timed out"
);
assert!(
rustfs_common::has_cached_connection(&addr).await,
"host-level progress from sibling drive must suppress shared-channel eviction"
);
rustfs_protos::evict_failed_connection(&addr).await;
clear_host_timeout_degradation(&addr);
}
}
@@ -686,21 +686,34 @@ impl RemoteClient {
}
}
fn record_request_timeout(&self, op: &'static str, deadline: Duration) {
fn record_request_timeout(&self, op: &'static str, deadline: Duration, admission: Option<LockRequestAdmission>) {
if !is_request_breaker_operation(op) {
return;
}
let now = Instant::now();
with_lock_peer_health(&self.addr, |health| {
// Once request backoff is active (`request_backoff_until.is_some()`), only a timeout
// from the currently admitted half-open probe generation may escalate or re-arm the
// backoff window. Straggler timeouts from RPCs admitted before backoff opened
// (`probe_generation: None`) or from a superseded probe generation must not compound
// backoff even if they arrive after `until` has elapsed.
if health.request_backoff_until.is_some() {
let is_active_probe = admission
.and_then(|token| token.probe_generation)
.is_some_and(|generation| health.request_probe_generation == Some(generation));
if !is_active_probe {
return;
}
}
health.request_consecutive_timeouts = health.request_consecutive_timeouts.saturating_add(1);
if health.request_consecutive_timeouts < LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
return;
}
let initial = deadline / 2;
let initial = (deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500));
let next = if health.request_backoff.is_zero() {
initial.max(Duration::from_millis(1))
initial
} else {
health.request_backoff.saturating_mul(2)
};
@@ -1274,7 +1287,7 @@ impl RemoteClient {
let reason = err.to_string();
if err.code() == tonic::Code::DeadlineExceeded {
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1324,7 +1337,7 @@ impl RemoteClient {
// the offline threshold for no benefit. See issue #4567.
let transport_failure = Self::is_transport_failure(&err);
if transport_failure {
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
}
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1412,7 +1425,7 @@ impl RemoteClient {
None => {
let reason = format!("RPC timed out after {deadline:?}");
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1541,7 +1554,7 @@ impl LockClient for RemoteClient {
let mut client = match self.get_client().await {
Ok(client) => client,
Err(err) => {
self.record_request_timeout("lock", rpc_timeout);
self.record_request_timeout("lock", rpc_timeout, admission.admission);
return Err(err);
}
};
@@ -2209,7 +2222,7 @@ mod tests {
reset_lock_peer_health_for_test(addr);
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100));
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
assert!(
@@ -2263,7 +2276,7 @@ mod tests {
});
let first = client.admit_lock_request("lock").expect("first probe should be admitted");
client.record_request_timeout("lock", Duration::from_millis(10));
client.record_request_timeout("lock", Duration::from_millis(10), Some(first));
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(1));
health.request_in_flight = 0;
@@ -2279,6 +2292,46 @@ mod tests {
reset_lock_peer_health_for_test(addr);
}
#[test]
fn late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe() {
let addr = "http://breaker-late-timeout-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
let pre_backoff = client
.admit_lock_request("lock")
.expect("normal pre-backoff RPC should be admitted");
assert!(!pre_backoff.is_probe());
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
let initial_backoff = lock_peer_health_for_test(addr).request_backoff;
assert_eq!(initial_backoff, Duration::from_millis(25));
// Simulate backoff window expiry while the pre-backoff RPC is still finishing.
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(5));
});
// A late timeout from a non-probe RPC (`probe_generation: None`) arriving after `until`
// must NOT double the backoff or block the upcoming half-open probe.
client.record_request_timeout("lock", Duration::from_millis(100), Some(pre_backoff));
client.release_lock_request("lock", Some(pre_backoff));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff);
let probe = client
.admit_lock_request("lock")
.expect("expired backoff must still admit a half-open probe");
assert!(probe.is_probe());
// Only when the active probe itself times out does the backoff escalate.
client.record_request_timeout("lock", Duration::from_millis(100), Some(probe));
client.release_lock_request("lock", Some(probe));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff * 2);
reset_lock_peer_health_for_test(addr);
}
#[test]
fn bounded_acquire_request_matches_transport_deadline() {
let request = test_lock_request(Duration::from_secs(30));
-11
View File
@@ -957,22 +957,11 @@ fn data_usage_contains_bucket(data_usage_info: &DataUsageInfo, bucket: &str) ->
}
fn advance_data_usage_last_update(data_usage_info: &mut DataUsageInfo) {
let previous = data_usage_info.snapshot_identity();
let now = SystemTime::now();
data_usage_info.last_update = Some(match data_usage_info.last_update {
Some(last_update) if last_update >= now => last_update.checked_add(Duration::from_nanos(1)).unwrap_or(now),
_ => now,
});
let current = data_usage_info.snapshot_identity();
// Namespace cleanup advances the root revision without rescanning the surviving buckets.
// Carry only observations bound to the root we read. Their sources and completion times stay intact.
data_usage_info.usage_snapshot_bucket_observations.retain(|_, observation| {
if observation.snapshot_identity != previous {
return false;
}
observation.snapshot_identity = current;
true
});
}
#[cfg(test)]
@@ -119,64 +119,6 @@ fn companion_only_observed_snapshot_does_not_create_a_legacy_quota_baseline() {
);
}
#[tokio::test]
async fn namespace_cleanup_preserves_the_observation_of_an_unrelated_bucket() {
let bucket = "pending-bucket";
let incarnation = uuid::Uuid::from_u128(31);
let original = companion_snapshot(bucket, incarnation);
let observation = &original.usage_snapshot_bucket_observations[bucket];
let store = UsageCasStore::default();
store.state.lock().await.object = Some((serde_json::to_vec(&original).expect("encode usage root"), 1));
remove_bucket_usage_from_object_with_retries(&store, DATA_USAGE_OBJ_NAME_PATH.as_str(), "new-bucket", 0, None, None)
.await
.expect("fence the new bucket's namespace");
let (mut saved, _) = load_data_usage_for_bucket_removal(&store, DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("read updated usage root")
.expect("usage root remains present");
assert!(saved.last_update > original.last_update);
assert_eq!(saved.scanner_cycle, original.scanner_cycle);
assert_eq!(saved.scanner_epoch, original.scanner_epoch);
assert_eq!(saved.buckets_usage[bucket], original.buckets_usage[bucket]);
let retained = &saved.usage_snapshot_bucket_observations[bucket];
assert_eq!(retained.completed_at, observation.completed_at);
assert_eq!(retained.sources, observation.sources);
assert_eq!(
saved.project_bucket_observations_for_admin(&HashMap::from([(bucket.to_string(), incarnation.to_string())])),
1
);
assert_eq!(saved.buckets_usage[bucket].size, observation.usage.size);
assert!(!saved.buckets_usage.contains_key("new-bucket"));
}
#[test]
fn namespace_cleanup_cannot_make_a_mismatched_observation_current() {
let bucket = "pending-bucket";
let incarnation = uuid::Uuid::from_u128(31);
let mut snapshot = companion_snapshot(bucket, incarnation);
let future = SystemTime::now() + Duration::from_secs(3600);
snapshot.last_update = Some(future);
// With a future root timestamp, the namespace fence advances it by one nanosecond.
let next = future + Duration::from_nanos(1);
snapshot
.usage_snapshot_bucket_observations
.get_mut(bucket)
.expect("test observation")
.snapshot_identity
.last_update = Some(next);
advance_data_usage_last_update(&mut snapshot);
assert_eq!(snapshot.last_update, Some(next));
assert_eq!(
snapshot.project_bucket_observations_for_admin(&HashMap::from([(bucket.to_string(), incarnation.to_string())])),
0
);
assert_eq!(snapshot.buckets_usage[bucket].size, 100);
}
#[test]
fn bucket_removal_discards_companions_even_without_a_canonical_entry() {
let mut snapshot = companion_snapshot("bucket", uuid::Uuid::from_u128(31));
+62 -2
View File
@@ -797,6 +797,8 @@ fn get_drive_timeout_health_policy() -> TimeoutHealthPolicy {
pub struct DiskHealthTracker {
/// Atomic timestamp of last successful operation
pub last_success: AtomicI64,
/// Monotonic count of operations that completed successfully on this handle
pub completed_ops: AtomicU64,
/// Atomic timestamp of last operation start
pub last_started: AtomicI64,
/// Atomic disk status (OK or Faulty)
@@ -1239,6 +1241,7 @@ impl DiskHealthTracker {
Self {
last_success: AtomicI64::new(now_nanos),
completed_ops: AtomicU64::new(0),
last_started: AtomicI64::new(now_nanos),
status: AtomicU32::new(DISK_HEALTH_OK),
waiting: AtomicU32::new(0),
@@ -1261,6 +1264,11 @@ impl DiskHealthTracker {
/// Log a successful operation
pub fn log_success(&self) {
self.last_success.store(current_unix_nanos(), Ordering::Relaxed);
self.completed_ops.fetch_add(1, Ordering::AcqRel);
}
pub fn completed_ops(&self) -> u64 {
self.completed_ops.load(Ordering::Acquire)
}
pub fn record_capacity_probe(&self, total: u64, used: u64, free: u64) {
@@ -1398,6 +1406,22 @@ impl DiskHealthTracker {
became_offline
}
/// Record a foreground timeout failure only when no sibling operation on this drive
/// succeeded while the timed-out operation was in flight. Under heavy queue contention,
/// tail-latency timeouts occur while the drive is actively completing other operations;
/// marking such a drive `Suspect`/`Offline` cascades into synthetic write-quorum 503s.
pub fn mark_failure_unless_progressed(
&self,
endpoint: &Endpoint,
reason: &'static str,
completed_before: u64,
) -> Option<bool> {
if self.completed_ops() > completed_before {
return None;
}
Some(self.mark_failure(endpoint, reason))
}
#[allow(dead_code, reason = "asserted by this file's tests (backlog#1823)")]
pub fn mark_offline(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
@@ -1430,6 +1454,7 @@ impl DiskHealthTracker {
self.consecutive_successes.store(0, Ordering::Release);
self.offline_since_unix_secs.store(0, Ordering::Release);
self.waiting.store(0, Ordering::Release);
self.completed_ops.store(0, Ordering::Release);
self.last_success.store(now_nanos, Ordering::Relaxed);
self.last_started.store(now_nanos, Ordering::Relaxed);
self.last_transition_unix_secs.store(now_secs, Ordering::Release);
@@ -2780,6 +2805,7 @@ impl LocalDiskWrapper {
.expect("test timeout lock")
.map_or(timeout_duration, |injected| timeout_duration.min(injected));
// Execute the operation with timeout
let completed_before = self.health.completed_ops();
let result = tokio::time::timeout(timeout_duration, operation).await;
match result {
@@ -2797,9 +2823,13 @@ impl LocalDiskWrapper {
Err(_) => {
self.metrics.record_operation_latency(op, started.elapsed());
self.metrics.record_timeout_error();
// Timeout occurred, mark disk as potentially faulty.
// Timeout occurred; mark disk as potentially faulty only if no sibling I/O
// completed while this operation was waiting.
if timeout_health_action == TimeoutHealthAction::MarkFailure
&& self.health.mark_failure(&self.endpoint(), "operation_timeout")
&& self
.health
.mark_failure_unless_progressed(&self.endpoint(), "operation_timeout", completed_before)
== Some(true)
{
self.spawn_recovery_monitor_if_needed();
}
@@ -6890,6 +6920,36 @@ mod tests {
assert_eq!(wrapper.runtime_state(), RuntimeDriveHealthState::Suspect);
}
#[test]
fn concurrent_progress_prevents_false_faulty_on_queue_timeout() {
let endpoint = Endpoint::try_from("/tmp/concurrent-progress-disk").expect("endpoint should parse");
let health = DiskHealthTracker::new();
let before = health.completed_ops();
// Sibling operation completes while a queued operation is waiting.
health.record_operation_success(&endpoint, "operation_success");
assert!(health.completed_ops() > before);
// Timed-out straggler from the earlier batch must not degrade or fault the active drive.
assert_eq!(health.mark_failure_unless_progressed(&endpoint, "operation_timeout", before), None);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Online);
assert!(!health.is_faulty());
// When no sibling operation completes after `stalled_before`, timeouts degrade normally.
let stalled_before = health.completed_ops();
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(false)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Suspect);
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(true)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Offline);
assert!(health.is_faulty());
}
#[test]
#[serial_test::serial]
fn drive_timeout_health_policy_defaults_to_mark_failure() {
+36 -5
View File
@@ -207,13 +207,16 @@ impl ListReadBudget {
}
}
fn weight(&self, fanout: usize) -> usize {
// Admit a full walk even when its fanout exceeds the configured budget.
fanout.max(1).min(self.capacity)
}
async fn acquire(&self, fanout: usize) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
if self.capacity == 0 {
return Ok(None);
}
// A single walk must remain admissible even when the topology exceeds
// the configured budget. Tokio accepts at most u32::MAX in one grant.
let weight = u32::try_from(fanout.max(1).min(self.capacity)).unwrap_or(u32::MAX);
let weight = u32::try_from(self.weight(fanout)).unwrap_or(u32::MAX);
self.permits
.clone()
.acquire_many_owned(weight)
@@ -491,6 +494,12 @@ impl InstanceContext {
.await
}
pub(crate) fn list_read_budget_has_capacity(&self, fanout: usize) -> Option<bool> {
self.list_read_budget
.get()
.map(|budget| budget.permits.available_permits() >= budget.weight(fanout))
}
/// Build a context bound to a specific lock manager.
///
/// [`bootstrap_ctx`] uses this to alias the process-global lock manager so
@@ -1575,8 +1584,16 @@ mod tests {
#[tokio::test]
async fn list_read_budget_zero_preserves_unbounded_configuration() {
let budget = ListReadBudget::new(0);
assert!(budget.acquire(usize::MAX).await.expect("disabled budget").is_none());
let ctx = InstanceContext::new();
assert_eq!(ctx.list_read_budget_has_capacity(1), None);
ctx.list_read_budget.set(ListReadBudget::new(0)).expect("fresh context");
assert!(
ctx.acquire_list_read_budget(usize::MAX)
.await
.expect("disabled budget")
.is_none()
);
assert_eq!(ctx.list_read_budget_has_capacity(usize::MAX), Some(true));
}
#[tokio::test]
@@ -1611,6 +1628,8 @@ mod tests {
let other = InstanceContext::new();
other.list_read_budget.set(ListReadBudget::new(4)).expect("fresh context");
let held = first.acquire_list_read_budget(4).await.expect("first context");
assert_eq!(same.list_read_budget_has_capacity(4), Some(false));
assert_eq!(other.list_read_budget_has_capacity(4), Some(true));
let mut waiter = std::pin::pin!(same.acquire_list_read_budget(1));
assert!(futures::poll!(&mut waiter).is_pending());
assert!(
@@ -1622,6 +1641,18 @@ mod tests {
);
drop(held);
assert!(waiter.await.expect("shared context resumed").is_some());
assert_eq!(same.list_read_budget_has_capacity(4), Some(true));
}
#[tokio::test]
async fn list_read_budget_reports_capacity_for_the_requested_fanout() {
let ctx = InstanceContext::new();
ctx.list_read_budget.set(ListReadBudget::new(64)).expect("fresh context");
let held = ctx.acquire_list_read_budget(48).await.expect("first walk");
assert_eq!(ctx.list_read_budget_has_capacity(16), Some(true));
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(false));
drop(held);
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(true));
}
#[test]
@@ -1025,6 +1025,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let futures = disks.iter().enumerate().map(|(disk_index, disk)| {
let disk = disk.clone();
let task_opts = opts;
@@ -1157,7 +1164,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout();
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
if let Some(observations) = &mut observations {
observations.push(MetadataFanoutObservation::from_error(
@@ -1270,6 +1277,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let spawn_read_version = |join_set: &mut JoinSet<(usize, disk::error::Result<FileInfo>, Duration)>,
task_ids: &mut [Option<tokio::task::Id>],
index: usize,
@@ -1436,7 +1450,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout();
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
slot.result = Some(Err(DiskError::Timeout));
+17 -4
View File
@@ -1572,6 +1572,18 @@ impl ECStore {
})
}
fn list_read_fanout(&self) -> usize {
self.pools.iter().fold(0usize, |total, pool| {
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
})
}
/// Whether the local budget can fit one full listing walk at the time of sampling.
/// Returns `None` until a listing walk initializes the budget.
pub fn list_read_budget_has_capacity(&self) -> Option<bool> {
self.ctx.list_read_budget_has_capacity(self.list_read_fanout())
}
pub async fn list_path(self: Arc<Self>, o: &ListPathOptions) -> Result<ListPage> {
// tracing::warn!("list_path opt {:?}", &o);
@@ -1625,10 +1637,11 @@ impl ECStore {
if o.transient {
o.create = false;
}
let fanout = self.pools.iter().fold(0usize, |total, pool| {
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
});
o.read_budget = self.ctx.acquire_list_read_budget(fanout).await.map_err(Error::other)?;
o.read_budget = self
.ctx
.acquire_list_read_budget(self.list_read_fanout())
.await
.map_err(Error::other)?;
let log_context = ListPathLogContext::from_options(&o);
+15
View File
@@ -37,6 +37,7 @@ pub type S3HttpCompletionObserverEnabled = fn() -> bool;
const METRIC: &str = "rustfs_s3_http_requests_total";
const LOCK_FAILURE_METRIC: &str = "rustfs_s3_lock_failures_total";
const S3_503_RESPONSES_METRIC: &str = "rustfs_s3_503_responses_total";
const ENTRY_TO_DISPATCH_METRIC: &str = "rustfs_s3_http_entry_to_dispatch_duration_seconds";
const METHODS: [&str; 10] = [
"GET", "PUT", "POST", "DELETE", "HEAD", "OPTIONS", "PATCH", "CONNECT", "TRACE", "OTHER",
@@ -240,6 +241,20 @@ pub fn record_s3_http_lock_failure(resource_class: &'static str, mode: &'static
});
}
/// Record an HTTP 503 S3 refusal classified by S3 error code and bounded subcause.
pub fn record_s3_http_503_response(s3_code: &'static str, subcause: &'static str) {
let op_label = CURRENT_OPERATION
.try_with(|current| operation_label(current.get().operation))
.unwrap_or("unknown");
metrics::counter!(
S3_503_RESPONSES_METRIC,
"op" => op_label,
"code" => s3_code,
"subcause" => subcause
)
.increment(1);
}
/// An external request is counted exactly once: at response headers, at a
/// service error, or when its future is dropped before producing a response.
/// Body-stream failures after headers use the existing streaming metrics.
+208 -7
View File
@@ -1887,7 +1887,14 @@ impl DistributedLock {
// A peer may grant promptly but deliver its response after its local
// contention budget. Keep this round's owners until a response proves
// quorum impossible or the caller's remaining budget expires.
let result = self.acquire_lock_quorum_once(&attempt_request, remaining).await?;
// On Exclusive contention retries (`attempt > 1`), serialize on the
// canonical anchor voter (`clients[0]`) before fanning out to remaining
// voters so N-node local-first split-votes do not livelock across rounds
// while preserving 1-RTT initial fanout and 2s reader-outlast queue time.
let serialize_on_anchor = request.lock_type == LockType::Exclusive && attempt > 1;
let result = self
.acquire_lock_quorum_once_inner(&attempt_request, remaining, serialize_on_anchor)
.await?;
if !result.response.success {
tracing::trace!(
target: "rustfs_lock::namespace_owner",
@@ -1973,10 +1980,21 @@ impl DistributedLock {
/// Quorum-based lock acquisition: success if at least the required quorum succeeds.
/// Collects all individual lock_ids from successful clients and creates an aggregate lock_id.
/// Returns the LockResponse with aggregate lock_id and individual lock mappings.
#[cfg_attr(not(test), allow(dead_code))]
async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> Result<LockAcquireQuorumResult> {
self.acquire_lock_quorum_once_inner(request, quorum_timeout, false).await
}
async fn acquire_lock_quorum_once_inner(
&self,
request: &LockRequest,
quorum_timeout: Duration,
serialize_on_anchor: bool,
) -> Result<LockAcquireQuorumResult> {
let voter_count =
u32::try_from(self.clients.len().max(1)).map_err(|_| LockError::internal("lock voter count exceeds u32"))?;
let required_quorum = self.required_quorum(request.lock_type);
let anchor_serialized = serialize_on_anchor && self.clients.len() > 1;
let attempt_started = Instant::now();
let quorum_deadline = attempt_started.checked_add(quorum_timeout).unwrap_or(attempt_started);
let grant_valid_until = attempt_started.checked_add(request.ttl).unwrap_or(attempt_started);
@@ -1987,18 +2005,19 @@ impl DistributedLock {
fallback_lock_id: request.lock_id.clone(),
};
let mut next_client_index = 0usize;
self.spawn_lock_requests_until(
&mut round.pending,
request,
&mut next_client_index,
let initial_target = if anchor_serialized {
1
} else {
required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len()),
);
.min(self.clients.len())
};
self.spawn_lock_requests_until(&mut round.pending, request, &mut next_client_index, initial_target);
let mut last_failure = None;
let mut last_failure_kind = None;
let mut last_hard_failure_kind = None;
let mut hard_failures = 0usize;
let mut anchor_definitive_contention = false;
let mut retry_at = vec![None; self.clients.len()];
let mut contention_retries = vec![0usize; self.clients.len()];
let start = attempt_started;
@@ -2107,6 +2126,9 @@ impl DistributedLock {
// Only an authoritative no-grant response is safe to retry under
// the same ID. A successful or still-pending voter is never retried.
if is_definitive_lock_contention(&error) {
if idx == 0 {
anchor_definitive_contention = true;
}
contention_retries[idx] = contention_retries[idx].saturating_add(1);
let backoff = LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF
.saturating_mul(contention_retries[idx].try_into().unwrap_or(u32::MAX));
@@ -2263,6 +2285,34 @@ impl DistributedLock {
});
}
// When serializing a contended Exclusive retry on the healthy anchor voter
// (`clients[0]`), yield immediately only if `clients[0]` rejected due to definitive
// lock contention rather than fanning out and split-voting on `clients[1..]`. If
// `clients[0]` granted (`!round.grants.is_empty()`), returned a timeout/backoff/breaker
// failure (`!anchor_definitive_contention`), failed with an RPC error (`hard_failures > 0`),
// or timed out its silent-prefix hedge (`next_client_index > 1`), fall through and fan out
// normally so offline, degraded, or hung anchor nodes never block quorum.
if anchor_serialized
&& anchor_definitive_contention
&& round.grants.is_empty()
&& hard_failures == 0
&& next_client_index == 1
&& round.pending.is_empty()
{
let mut error = format!("Anchor voter contended: 0/{required_quorum} required");
if let Some(last_failure) = last_failure {
error.push_str("; last failure: ");
error.push_str(&last_failure);
}
return Ok(LockAcquireQuorumResult {
response: LockResponse::failure(error, Duration::ZERO),
individual_locks: Vec::new(),
failure_kind: Some(LockAcquireFailureKind::RetryableContention),
quorum_impossible: false,
attempt_timed_out: false,
});
}
let needed = required_quorum.saturating_sub(round.grants.len());
self.spawn_lock_requests_until(
&mut round.pending,
@@ -5053,4 +5103,155 @@ mod tests {
);
drop(results);
}
#[tokio::test]
async fn exclusive_retry_fans_out_to_remaining_voters_when_anchor_times_out_or_breaker_opens() {
#[derive(Debug)]
struct FixedResponseClient {
calls: Arc<std::sync::atomic::AtomicUsize>,
response: LockResponse,
}
#[async_trait::async_trait]
impl LockClient for FixedResponseClient {
async fn acquire_lock(&self, request: &LockRequest) -> crate::Result<LockResponse> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if self.response.success {
Ok(LockResponse::success(
LockInfo {
id: request.lock_id.clone(),
resource: request.resource.clone(),
lock_type: request.lock_type,
status: crate::LockStatus::Acquired,
owner: request.owner.clone(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + request.ttl,
last_refreshed: std::time::SystemTime::now(),
metadata: request.metadata.clone(),
priority: request.priority,
wait_start_time: None,
},
Duration::ZERO,
))
} else {
Ok(self.response.clone())
}
}
async fn release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn refresh(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn force_release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn check_status(&self, _lock_id: &LockId) -> crate::Result<Option<LockInfo>> {
Ok(None)
}
async fn get_stats(&self) -> crate::Result<LockStats> {
Ok(LockStats::default())
}
async fn close(&self) -> crate::Result<()> {
Ok(())
}
async fn is_online(&self) -> bool {
true
}
async fn is_local(&self) -> bool {
false
}
}
for anchor_error in [
"RPC request backoff active for lock on http://127.0.0.1:9000",
"remote lock RPC lock on http://127.0.0.1:9000 timed out after 1s",
] {
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c2_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure(anchor_error, Duration::ZERO),
});
let grant_template = LockResponse::success(
LockInfo {
id: LockId::new(ObjectKey::new("bucket", "key")),
resource: ObjectKey::new("bucket", "key"),
lock_type: LockType::Exclusive,
status: crate::LockStatus::Acquired,
owner: "owner".to_string(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + Duration::from_secs(30),
last_refreshed: std::time::SystemTime::now(),
metadata: Default::default(),
priority: Default::default(),
wait_start_time: None,
},
Duration::ZERO,
);
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: grant_template.clone(),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c2_calls),
response: grant_template,
});
let lock = DistributedLock::new("anchor-breaker-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("quorum attempt must complete");
assert!(
outcome.response.is_success(),
"anchor error `{anchor_error}` must fall through to remaining voters and reach 2/3 quorum"
);
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c2_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
}
// Conversely, definitive contention on the anchor must still short-circuit without
// contacting the remaining voters.
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure("Lock conflict: resource held by other", Duration::ZERO),
});
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: LockResponse::failure("unused", Duration::ZERO),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
response: LockResponse::failure("unused", Duration::ZERO),
});
let lock = DistributedLock::new("anchor-contention-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("contention attempt must complete");
assert!(!outcome.response.is_success());
assert!(matches!(outcome.failure_kind, Some(LockAcquireFailureKind::RetryableContention)));
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 0);
}
}
+15 -10
View File
@@ -102,9 +102,14 @@ async fn accept_peer(listener: TcpListener) -> io::Result<TcpStream> {
Ok(socket)
}
async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, error_resets: Arc<AtomicUsize>) -> io::Result<()> {
async fn delayed_response_peer(
listener: TcpListener,
ready: mpsc::Sender<()>,
error_resets: Arc<AtomicUsize>,
concurrency_limit: usize,
) -> io::Result<()> {
let mut socket = accept_peer(listener).await?;
let mut cancelled = Vec::with_capacity(INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
let mut cancelled = Vec::with_capacity(concurrency_limit);
let mut resets = HashSet::new();
let mut probe = None;
loop {
@@ -118,9 +123,9 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
let credit = u32::try_from(frame.payload.len()).expect("bounded DATA frame").to_be_bytes();
write_frame(&mut socket, WINDOW_UPDATE, 0, 0, &credit).await?;
}
HEADERS if cancelled.len() < INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT => {
HEADERS if cancelled.len() < concurrency_limit => {
cancelled.push(frame.stream);
if cancelled.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
if cancelled.len() == concurrency_limit {
ready.send(()).await.map_err(|_| io::Error::other("test driver stopped"))?;
}
}
@@ -140,7 +145,7 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
_ => {}
}
if let Some(stream) = probe
&& resets.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT
&& resets.len() == concurrency_limit
{
// A raw peer controls bytes already in flight at cancellation. A normal
// server would consume RST_STREAM and suppress these delayed responses.
@@ -155,12 +160,12 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
}
}
async fn assert_cancelled_responses_are_ignored(bulk: bool) {
async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: usize) {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind isolated peer");
let address = format!("http://{}", listener.local_addr().expect("peer address"));
let (ready_tx, mut ready_rx) = mpsc::channel(1);
let error_resets = Arc::new(AtomicUsize::new(0));
let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone()));
let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone(), concurrency_limit));
let cache_key = if bulk {
super::bulk_cache_key(&address, 0)
} else {
@@ -173,7 +178,7 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool) {
let mut client = node_service::node_service_client::NodeServiceClient::new(channel);
for batch in 0..BATCHES {
let mut requests = JoinSet::new();
for _ in 0..INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
for _ in 0..concurrency_limit {
let mut pending_client = client.clone();
requests.spawn(async move { pending_client.read_version(node_service::ReadVersionRequest::default()).await });
}
@@ -203,14 +208,14 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool) {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn cancelled_metadata_responses_keep_the_shared_channel_usable() {
assert_cancelled_responses_are_ignored(false).await;
assert_cancelled_responses_are_ignored(false, INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn cancelled_metadata_responses_keep_the_bulk_channel_usable() {
temp_env::async_with_vars(
[(rustfs_config::ENV_INTERNODE_BULK_CONCURRENCY_LIMIT, Some("64"))],
assert_cancelled_responses_are_ignored(true),
assert_cancelled_responses_are_ignored(true, 64),
)
.await;
}
+14 -11
View File
@@ -3836,7 +3836,7 @@ fn complete_pending_rebuild_on_cache_hit(dial_addr: &str, cache_key: &str) -> bo
}
// Limits transport response futures; client RPC metrics separately cover unary body decoding.
pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 64;
pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 256;
// Quorum reads cancel surplus metadata RPCs in bursts. Keep bounded reset state
// for their in-flight replies through the HTTP/2 grace period without spending
@@ -5929,7 +5929,7 @@ mod tests {
);
assert_eq!(
checked_rpc_window(internode_rpc_http2_stream_window()).expect("control setting"),
Some(1024 * 1024)
Some(rustfs_config::DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE)
);
},
)
@@ -6024,17 +6024,20 @@ mod tests {
#[tokio::test]
async fn get_channel_for_class_bulk_reuses_control_cache_when_isolation_disabled() {
let _test_guard = TLS02_TEST_LOCK.lock().await;
// Isolation defaults off, so a Bulk request must reuse the control channel keyed by the
// bare address and must NOT create a separate bulk-keyed entry (zero behavior change).
let addr = "http://get-channel-isolation-off-test";
let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
cache_connection(addr.to_string(), channel).await;
temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CHANNEL_ISOLATION, Some("false"))], async {
// When isolation is explicitly disabled, a Bulk request must reuse the control channel
// keyed by the bare address and must NOT create a separate bulk-keyed entry.
let addr = "http://get-channel-isolation-off-test";
let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
cache_connection(addr.to_string(), channel).await;
let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await;
assert!(acquired.is_ok());
assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await);
let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await;
assert!(acquired.is_ok());
assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await);
evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await;
evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await;
})
.await;
}
}
+89 -5
View File
@@ -855,6 +855,10 @@ fn classify_transport_error(
return InternodeHttpErrorKind::BodyStreamAborted;
}
if let Some(kind) = find_request_phase_close_in_chain(err) {
return kind;
}
InternodeHttpErrorKind::Unknown
}
@@ -864,8 +868,13 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>() {
match io_err.kind() {
io::ErrorKind::ConnectionRefused => return Some(InternodeHttpErrorKind::ConnectionRefused),
io::ErrorKind::ConnectionReset | io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionAborted => {
io::ErrorKind::ConnectionRefused | io::ErrorKind::AddrNotAvailable => {
return Some(InternodeHttpErrorKind::ConnectionRefused);
}
io::ErrorKind::ConnectionReset
| io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::NotConnected => {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
io::ErrorKind::TimedOut => return Some(InternodeHttpErrorKind::ConnectTimeout),
@@ -875,9 +884,31 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
_ => {}
}
}
if current
.downcast_ref::<hyper::Error>()
.is_some_and(hyper::Error::is_incomplete_message)
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>() {
if hyper_err.is_body_write_aborted() {
return Some(InternodeHttpErrorKind::BodyStreamAborted);
}
if hyper_err.is_incomplete_message() {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
}
source = current.source();
}
None
}
/// Map pooled HTTP/1.1 request-dispatch closes (`is_closed` / `is_canceled` / `UnexpectedEof`)
/// after `is_body` has been checked so response-body truncations retain `BodyStreamAborted`.
fn find_request_phase_close_in_chain(err: &(dyn std::error::Error + 'static)) -> Option<InternodeHttpErrorKind> {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>()
&& io_err.kind() == io::ErrorKind::UnexpectedEof
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>()
&& (hyper_err.is_closed() || hyper_err.is_canceled())
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
@@ -2187,6 +2218,8 @@ mod tests {
io::ErrorKind::ConnectionReset,
io::ErrorKind::BrokenPipe,
io::ErrorKind::ConnectionAborted,
io::ErrorKind::UnexpectedEof,
io::ErrorKind::NotConnected,
] {
let err = WrapperError::new("transport", Some(io_source(io_kind)));
assert_eq!(
@@ -2197,6 +2230,57 @@ mod tests {
}
}
#[test]
fn classify_io_addr_not_available_maps_to_refused() {
let err = WrapperError::new("ephemeral port exhausted", Some(io_source(io::ErrorKind::AddrNotAvailable)));
assert_eq!(
classify_transport_error(&err, false, false, false),
InternodeHttpErrorKind::ConnectionRefused
);
}
#[tokio::test]
async fn early_503_during_streaming_upload_remains_retryable() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("peer listener should bind");
let address = listener.local_addr().expect("peer address should be available");
let peer = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.expect("peer should accept");
let mut buf = [0_u8; 1024];
let _ = socket.read(&mut buf).await.expect("peer should read initial headers");
let _ = socket
.write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.await;
let _ = socket.shutdown().await;
});
let mut writer =
HttpWriter::new(format!("http://{address}/rustfs/rpc/put_file_stream_v1"), Method::PUT, HeaderMap::new())
.await
.expect("internode writer should be created");
let payload = vec![b'x'; 4 * 1024 * 1024];
let mut final_err = None;
if let Err(err) = writer.write_all(&payload).await {
final_err = Some(err);
} else if let Err(err) = writer.shutdown().await {
final_err = Some(err);
}
let error = final_err.expect("early 503 close must fail streaming upload");
let source = error
.get_ref()
.and_then(|source| source.downcast_ref::<InternodeHttpError>())
.expect("streaming failure must preserve InternodeHttpError");
assert!(
source.kind().is_retryable(),
"expected retryable classification on early 503 body abort, got {:?}",
source.kind()
);
peer.await.expect("peer should finish");
}
#[test]
fn classify_io_unreachable_variants() {
for io_kind in [io::ErrorKind::HostUnreachable, io::ErrorKind::NetworkUnreachable] {
+22 -43
View File
@@ -714,44 +714,21 @@ fn summarize_storage_readiness(snapshot: &ClusterReadOnlySnapshot) -> Capability
}
}
fn summarize_listing_readiness(snapshot: &ClusterReadOnlySnapshot) -> CapabilityStatus {
match snapshot
.workload_admission
.entries()
.iter()
.find(|entry| entry.class == WorkloadClass::ForegroundRead)
{
Some(entry) if entry.state == AdmissionState::Open => {
CapabilityStatus::supported().with_reason("foreground read admission is open")
}
Some(entry) => {
let mut reason = format!("foreground read admission is {}", admission_state_label(entry.state));
if let Some(detail) = entry.reason.as_deref() {
reason.push_str(": ");
reason.push_str(detail);
}
CapabilityStatus::unknown().with_reason(reason)
}
None => CapabilityStatus::unknown().with_reason("foreground read admission is not reported"),
}
}
fn summarize_listing_metacache(snapshot: &ClusterReadOnlySnapshot) -> ClusterListingMetacacheStatus {
const HINT: &str = "bucket and prefix attribution is emitted through metacache quorum logs; inspect operation-labelled walk_dir metrics for internode traffic";
let admission = summarize_listing_readiness(snapshot);
let stalls = snapshot.listing_diagnostics.internode_stall_timeouts_total;
let (condition, status) = if admission.state == CapabilityState::Supported {
("healthy", admission)
} else {
(condition_from_capability(&admission), admission)
let diagnostics = snapshot.listing_diagnostics;
let status = match diagnostics.local_budget_has_capacity {
Some(true) => CapabilityStatus::supported().with_reason("local listing budget has capacity"),
Some(false) => CapabilityStatus::unknown().with_reason("local listing budget cannot admit a full walk"),
None => CapabilityStatus::unknown().with_reason("local listing budget is not reported"),
};
ClusterListingMetacacheStatus {
source: "workload_admission+internode_metrics",
condition,
source: "local_listing_budget+internode_metrics",
condition: condition_from_capability(&status),
status,
internode_stall_timeouts_total: stalls,
internode_stall_timeouts_total: diagnostics.internode_stall_timeouts_total,
hint: HINT,
}
}
@@ -1213,6 +1190,7 @@ mod tests {
..Default::default()
},
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: None,
internode_stall_timeouts_total: 2,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot {
@@ -1233,7 +1211,7 @@ mod tests {
assert_eq!(value["components"]["storage"]["source"], "runtime_readiness");
assert_eq!(value["components"]["storage"]["condition"], "degraded");
assert_eq!(value["components"]["peer_health"]["source"], "cluster_peer_health");
assert_eq!(value["components"]["listing"]["source"], "workload_admission+internode_metrics");
assert_eq!(value["components"]["listing"]["source"], "local_listing_budget+internode_metrics");
assert_eq!(value["components"]["listing"]["condition"], "unknown");
assert_eq!(value["components"]["listing"]["internode_stall_timeouts_total"], 2);
assert_eq!(value["pool_meta_write_gate"]["writesReady"], false);
@@ -1309,8 +1287,8 @@ mod tests {
assert_eq!(summary.storage.state, CapabilityState::Supported);
assert_eq!(summary.storage.reason.as_deref(), Some("storage readiness reports ready"));
assert_eq!(summary.peer_health.state, CapabilityState::Unknown);
assert_eq!(summary.listing.state, CapabilityState::Supported);
assert_eq!(summary.listing.reason.as_deref(), Some("foreground read admission is open"));
assert_eq!(summary.listing.state, CapabilityState::Unknown);
assert_eq!(summary.listing.reason.as_deref(), Some("local listing budget is not reported"));
assert_eq!(summary.usage.state, CapabilityState::Unknown);
assert_eq!(summary.usage.reason.as_deref(), Some("no usage cache save result has been reported"));
assert_eq!(summary.rpc_boundary.state, CapabilityState::Supported);
@@ -1342,11 +1320,10 @@ mod tests {
},
rpc_boundary: sample_rpc_boundary_snapshot(),
observability: ObservabilitySnapshot::default(),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![
WorkloadAdmissionSnapshot::new(WorkloadClass::ForegroundRead, AdmissionState::Throttled)
.with_counts(Some(4), Some(8), Some(4))
.with_reason("metacache listing backpressure"),
]),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![WorkloadAdmissionSnapshot::new(
WorkloadClass::ForegroundRead,
AdmissionState::Open,
)]),
runtime_status: ClusterRuntimeStatusSnapshot {
readiness: DependencyReadiness {
storage_ready: false,
@@ -1365,6 +1342,7 @@ mod tests {
..Default::default()
},
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: Some(false),
internode_stall_timeouts_total: 0,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot::default(),
@@ -1383,7 +1361,7 @@ mod tests {
assert_eq!(view.components.listing.status.state, CapabilityState::Unknown);
assert_eq!(
view.components.listing.status.reason.as_deref(),
Some("foreground read admission is throttled: metacache listing backpressure")
Some("local listing budget cannot admit a full walk")
);
assert_eq!(view.components.listing.condition, "unknown");
assert_eq!(view.components.usage.status.state, CapabilityState::Unknown);
@@ -1433,7 +1411,7 @@ mod tests {
}
#[test]
fn cluster_snapshot_listing_component_keeps_historical_stalls_as_evidence() {
fn cluster_snapshot_listing_uses_its_own_budget_while_get_is_saturated() {
let snapshot = ClusterReadOnlySnapshot {
topology: TopologySnapshot::default(),
membership: ClusterMembershipSnapshot::default(),
@@ -1444,7 +1422,7 @@ mod tests {
observability: ObservabilitySnapshot::default(),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![WorkloadAdmissionSnapshot::new(
WorkloadClass::ForegroundRead,
AdmissionState::Open,
AdmissionState::Saturated,
)]),
runtime_status: ClusterRuntimeStatusSnapshot {
readiness: DependencyReadiness::default(),
@@ -1453,6 +1431,7 @@ mod tests {
},
usage_freshness: ClusterUsageFreshnessSnapshot::default(),
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: Some(true),
internode_stall_timeouts_total: 2,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot::default(),
@@ -1461,7 +1440,7 @@ mod tests {
let component = super::summarize_listing_metacache(&snapshot);
assert_eq!(component.status.state, CapabilityState::Supported);
assert_eq!(component.status.reason.as_deref(), Some("foreground read admission is open"));
assert_eq!(component.status.reason.as_deref(), Some("local listing budget has capacity"));
assert_eq!(component.condition, "healthy");
assert_eq!(component.internode_stall_timeouts_total, 2);
}
+2 -2
View File
@@ -777,8 +777,8 @@ impl DefaultAdminUsecase {
}
pub async fn execute_collect_cluster_read_only_snapshot(&self) -> Option<ClusterReadOnlySnapshot> {
let endpoint_pools = current_endpoints_handle()?;
collect_cluster_read_only_snapshot(&endpoint_pools).await
let context = current_app_context()?;
collect_cluster_read_only_snapshot(&context).await
}
pub fn cluster_snapshot_route(&self) -> &'static str {
+18 -17
View File
@@ -13,6 +13,7 @@
// limitations under the License.
use crate::runtime_capabilities::runtime_observability_snapshot;
use crate::runtime_sources::AppContext;
use crate::server::snapshot_dependency_readiness_report;
use crate::shared_types::{DependencyReadiness, DependencyReadinessReport, ReadinessDegradedReason};
use crate::storage_api::cluster::EndpointServerPools;
@@ -24,7 +25,7 @@ use crate::storage_api::cluster::control_plane::{
};
use crate::workload_admission::workload_admission_registry_snapshot;
use rustfs_concurrency::{AdmissionState, WorkloadAdmissionRegistrySnapshot};
use rustfs_io_metrics::internode_metrics::{InternodeMetricsSnapshot, global_internode_metrics};
use rustfs_io_metrics::internode_metrics::InternodeMetricsSnapshot;
use rustfs_scanner_metrics::metrics::{ScannerMetricsReport, global_metrics};
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -102,9 +103,19 @@ impl From<&ScannerMetricsReport> for ClusterUsageFreshnessSnapshot {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ClusterListingDiagnosticsSnapshot {
pub local_budget_has_capacity: Option<bool>,
pub internode_stall_timeouts_total: u64,
}
impl From<InternodeMetricsSnapshot> for ClusterListingDiagnosticsSnapshot {
fn from(snapshot: InternodeMetricsSnapshot) -> Self {
Self {
internode_stall_timeouts_total: snapshot.operation_stall_timeouts_total,
..Self::default()
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClusterPoolMetaWriteGateSnapshot {
pub writes_ready: bool,
@@ -136,14 +147,6 @@ impl Default for ClusterPoolMetaWriteGateSnapshot {
}
}
impl From<InternodeMetricsSnapshot> for ClusterListingDiagnosticsSnapshot {
fn from(snapshot: InternodeMetricsSnapshot) -> Self {
Self {
internode_stall_timeouts_total: snapshot.operation_stall_timeouts_total,
}
}
}
impl ClusterRuntimeReadinessState {
fn from_report(report: &DependencyReadinessReport) -> Self {
if report.readiness.storage_ready
@@ -200,11 +203,14 @@ pub fn cluster_read_only_snapshot_from_control_plane(
}
}
pub async fn collect_cluster_read_only_snapshot(endpoint_pools: &EndpointServerPools) -> Option<ClusterReadOnlySnapshot> {
pub(crate) async fn collect_cluster_read_only_snapshot(context: &AppContext) -> Option<ClusterReadOnlySnapshot> {
let endpoint_pools = context.endpoints().handle()?;
let store = context.object_store();
let runtime_status = ClusterRuntimeStatusSnapshot::from_readiness_report(snapshot_dependency_readiness_report().await);
let mut snapshot = cluster_read_only_snapshot_from_endpoint_pools(endpoint_pools, runtime_status);
let mut snapshot = cluster_read_only_snapshot_from_endpoint_pools(&endpoint_pools, runtime_status);
snapshot.usage_freshness = current_usage_freshness_snapshot().await;
snapshot.listing_diagnostics = current_listing_diagnostics_snapshot();
snapshot.listing_diagnostics = context.internode_metrics().handle().snapshot().into();
snapshot.listing_diagnostics.local_budget_has_capacity = store.list_read_budget_has_capacity();
snapshot.pool_meta_write_gate = current_pool_meta_write_gate_snapshot().await;
Some(snapshot)
}
@@ -217,11 +223,6 @@ async fn current_usage_freshness_snapshot() -> ClusterUsageFreshnessSnapshot {
ClusterUsageFreshnessSnapshot::from(&report)
}
fn current_listing_diagnostics_snapshot() -> ClusterListingDiagnosticsSnapshot {
let metrics = crate::runtime_sources::current_internode_metrics().unwrap_or_else(|| global_internode_metrics().clone());
ClusterListingDiagnosticsSnapshot::from(metrics.snapshot())
}
async fn current_pool_meta_write_gate_snapshot() -> ClusterPoolMetaWriteGateSnapshot {
match crate::runtime_sources::current_object_store_handle() {
Some(store) => {
+248
View File
@@ -591,6 +591,16 @@ fn is_hyper_body_eof(err: &(dyn std::error::Error + 'static)) -> bool {
.is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::UnexpectedEof)
}
fn is_unavailable_internode_http_error(err: &rustfs_rio::InternodeHttpError) -> bool {
err.kind().is_retryable()
|| matches!(
err.kind(),
rustfs_rio::InternodeHttpErrorKind::HttpStatus(status)
if status.is_server_error() || status.as_u16() == 409
)
|| (err.kind() == rustfs_rio::InternodeHttpErrorKind::Unknown && err.context().operation().is_some())
}
/// A nested lock timeout retains its retry advice even when an outer lock
/// failure supplies a less specific cause. Share one bounded source walk.
fn service_unavailable_cause(source: &(dyn std::error::Error + 'static)) -> Option<&'static str> {
@@ -610,6 +620,13 @@ fn service_unavailable_cause(source: &(dyn std::error::Error + 'static)) -> Opti
}
_ => None,
};
if cause.is_none()
&& let Some(internode_err) = error.downcast_ref::<rustfs_rio::InternodeHttpError>()
&& is_unavailable_internode_http_error(internode_err)
&& matches!(internode_err.context().operation(), Some("put_file_stream" | "put_file_capability"))
{
cause = Some("storage_write_quorum");
}
}
None
}
@@ -646,6 +663,130 @@ impl From<ApiError> for rustfs_s3_types::S3Error {
}
}
/// Fine-grained, bounded classification for every HTTP 503 response (`ServiceUnavailable`,
/// `SlowDown`, `SlowDownRead`, `Busy`), emitted via `x-rustfs-503-subcause` at the outer
/// gateway stack edge and counted under `rustfs_s3_503_responses_total` without expanding
/// `rustfs-gateway`'s closed inner `x-rustfs-error-cause` set.
pub(crate) fn classify_s3_503_subcause(
code: &S3ErrorCode,
message: Option<&str>,
headers: Option<&http::HeaderMap>,
source: Option<&(dyn std::error::Error + 'static)>,
) -> &'static str {
if let Some(hdrs) = headers
&& let Some(cause) = hdrs.get("x-rustfs-error-cause").and_then(|v| v.to_str().ok())
{
match cause {
"namespace_lock_timeout" => return "namespace_lock_timeout",
"namespace_lock_unavailable" => return "namespace_lock_unavailable",
"storage_write_quorum" => return "storage_write_quorum",
_ => {}
}
}
if matches!(code, S3ErrorCode::Custom(name) if &**name == SLOW_DOWN_READ_CODE) {
return "storage_read_quorum";
}
if code == &S3ErrorCode::Busy {
return "s3_select_busy";
}
if let Some(src) = source
&& let Some(sub) = classify_503_source_chain(src)
{
return sub;
}
let msg = message.unwrap_or_default();
if code == &S3ErrorCode::SlowDown {
if msg.contains("write concurrency limit reached") || msg.contains("foreground write concurrency") {
return "foreground_write_admission";
}
if msg.contains("disk read concurrency limit reached") {
return "disk_read_permit_exhausted";
}
if msg.contains("Table listing exceeded") {
return "table_list_scan_limit";
}
if msg.contains("cold-fill") || msg.contains("cache") {
return "object_cache_cold_fill_rejected";
}
if headers.and_then(|h| h.get(http::header::RETRY_AFTER)).is_some() {
return "bucket_operation_admission";
}
if msg.contains("Resource requested is unreadable") {
return "storage_slowdown";
}
return "slowdown_other";
}
if msg.contains("quota") || msg.contains("Quota") {
return "quota_usage_unavailable";
}
if msg.contains("server context is not ready") || msg.contains("iam unavailable") {
return "server_not_ready";
}
"service_unavailable_other"
}
fn classify_503_source_chain(source: &(dyn std::error::Error + 'static)) -> Option<&'static str> {
if let Some(lock_or_write_cause) = service_unavailable_cause(source) {
return Some(lock_or_write_cause);
}
error_chain_find(source, |error| {
if let Some(status) = error.downcast_ref::<tonic::Status>() {
if status.code() == tonic::Code::ResourceExhausted
&& status
.metadata()
.get(RPC_ADMISSION_METADATA_KEY)
.is_some_and(|v| v.as_encoded_bytes() == RPC_REPLAY_ADMISSION_METADATA_VALUE.as_bytes())
{
return Some("internode_replay_cache_overflow");
}
if status.code() == tonic::Code::Unavailable {
return Some("internode_rpc_unavailable");
}
}
if error.is::<KmsUnavailableError>() || error.is::<rustfs_kms::KmsError>() {
return Some("kms_unavailable");
}
if error.is::<QuotaError>() {
return Some("quota_usage_unavailable");
}
if error.is::<ServerSideSourceReadError>() {
return Some("server_side_source_read_unavailable");
}
if let Some(internode_err) = error.downcast_ref::<rustfs_rio::InternodeHttpError>()
&& is_unavailable_internode_http_error(internode_err)
{
return Some("internode_rpc_unavailable");
}
if let Some(storage_err) = error.downcast_ref::<StorageError>() {
if storage_err.pool_metadata_failure().is_some() {
return Some("pool_metadata_unavailable");
}
if unreadable_config_refusal(storage_err).is_some() {
return Some("unreadable_bucket_config");
}
return match storage_err {
StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(_, _) => Some("storage_read_quorum"),
StorageError::ErasureWriteQuorum | StorageError::InsufficientWriteQuorum(_, _) => Some("storage_write_quorum"),
StorageError::DiskFull | StorageError::StorageFull => Some("disk_full"),
StorageError::TooManyOpenFiles => Some("too_many_open_files"),
StorageError::Timeout => Some("storage_timeout"),
StorageError::FaultyDisk | StorageError::FaultyRemoteDisk | StorageError::DiskNotFound => {
Some("faulty_or_missing_disk")
}
StorageError::UnsupportedDisk => Some("unsupported_participant_disk"),
StorageError::DeleteRecoveryWorkLimit => Some("delete_recovery_work_limit"),
StorageError::SlowDown => Some("storage_slowdown"),
_ => None,
};
}
None
})
}
/// Carry an owned refusal into a fixture that invokes the pinned transport.
#[cfg(test)]
pub(crate) fn legacy_error_for_test(error: rustfs_s3_types::S3Error) -> s3s::S3Error {
@@ -818,6 +959,21 @@ impl From<StorageError> for ApiError {
source: Some(Box::new(err)),
};
}
if error_chain_find(inner, |cause| {
cause
.downcast_ref::<rustfs_rio::InternodeHttpError>()
.filter(|err| is_unavailable_internode_http_error(err))
.map(|_| ())
})
.is_some()
{
return ApiError {
code: S3ErrorCode::ServiceUnavailable,
message: ApiError::error_code_to_message(&S3ErrorCode::ServiceUnavailable),
source: Some(Box::new(err)),
};
}
}
let code = match &err {
@@ -2610,6 +2766,42 @@ mod tests {
}
}
#[test]
fn internode_http_quorum_failures_map_to_service_unavailable_not_500() {
use crate::storage_api::error::{DiskError, OBJECT_OP_IGNORED_ERRS, reduce_write_quorum_errs};
use rustfs_rio::InternodeHttpErrorKind::{BodyStreamAborted, ConnectionReset, HttpStatus, Unknown};
for kind in [
ConnectionReset,
BodyStreamAborted,
Unknown,
HttpStatus(http::StatusCode::SERVICE_UNAVAILABLE),
HttpStatus(http::StatusCode::INTERNAL_SERVER_ERROR),
] {
let errors = [
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
None,
];
let reduced = reduce_write_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, 3)
.expect("quorum of internode http errors must reduce to a concrete error");
let api_err = ApiError::from(StorageError::from(reduced));
assert_eq!(
api_err.code,
S3ErrorCode::ServiceUnavailable,
"{kind:?} quorum failure should map to 503 ServiceUnavailable"
);
let response = S3Error::from(api_err);
assert_eq!(response.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE));
}
let bad_req = DiskError::from(rustfs_rio::new_test_internode_http_io_error(HttpStatus(http::StatusCode::BAD_REQUEST)));
let errors = [Some(bad_req.clone()), Some(bad_req.clone()), Some(bad_req), None];
let reduced = reduce_write_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, 3).unwrap();
assert_eq!(ApiError::from(StorageError::from(reduced)).code, S3ErrorCode::InternalError);
}
#[test]
fn test_api_error_from_unexpected_eof_maps_to_incomplete_body() {
let io_error = IoError::new(ErrorKind::UnexpectedEof, rustfs_rio::IncompleteBody { remaining: 7 });
@@ -2840,4 +3032,60 @@ mod tests {
assert_eq!(source.to_string(), "source error");
assert!(std::error::Error::source(&ApiError::access_denied()).is_none());
}
#[test]
fn test_classify_s3_503_subcause_covers_slowdown_and_source_chains() {
let slow_write = rustfs_s3_types::S3Error::with_message(
S3ErrorCode::SlowDown,
"foreground write concurrency limit reached, please reduce your request rate",
);
let parts = slow_write.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"foreground_write_admission"
);
let slow_read = rustfs_s3_types::S3Error::from(slow_down_read_api_error(StorageError::ErasureReadQuorum));
let parts = slow_read.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"storage_read_quorum"
);
let replay_overflow = rustfs_s3_types::S3Error::from(ApiError::from(StorageError::Io(IoError::other(
rpc_replay_admission_exhausted_status(),
))));
let parts = replay_overflow.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"internode_replay_cache_overflow"
);
let timeout_err = rustfs_s3_types::S3Error::from(ApiError::from(StorageError::Timeout));
let parts = timeout_err.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"storage_timeout"
);
}
}
@@ -40,6 +40,36 @@ use rustfs_gateway::{
use rustfs_gateway_types::{ETag, ErrorCode, Timestamp, TimestampFormat};
use rustfs_s3_types::S3Error;
use std::borrow::Cow;
use std::cell::Cell;
use std::future::Future;
tokio::task_local! {
static CURRENT_503_SUBCAUSE: Cell<Option<&'static str>>;
}
/// Runs `future` with a task-local slot that captures the fine-grained subcause of any HTTP 503
/// rendered by [`handler_error`] so [`crate::server::gateway_stack::GatewayStack::call`] can
/// emit `x-rustfs-503-subcause` on the outer response without widening the gateway's closed
/// inner `x-rustfs-error-cause` set.
pub(in crate::server) async fn scope_503_subcause<F: Future>(future: F) -> (F::Output, Option<&'static str>) {
CURRENT_503_SUBCAUSE
.scope(Cell::new(None), async move {
let out = future.await;
let subcause = CURRENT_503_SUBCAUSE.try_with(Cell::get).ok().flatten();
(out, subcause)
})
.await
}
fn s3_code_metric_label(code: &rustfs_s3_types::S3ErrorCode) -> &'static str {
match code.as_str() {
"ServiceUnavailable" => "ServiceUnavailable",
"SlowDown" => "SlowDown",
"SlowDownRead" => "SlowDownRead",
"Busy" => "Busy",
_ => "Other503",
}
}
const LOG_COMPONENT_STORAGE: &str = "storage";
const LOG_SUBSYSTEM_OBJECT: &str = "object";
@@ -154,6 +184,16 @@ pub(crate) fn handler_error(error: S3Error) -> HandlerError {
.status
.or_else(|| parts.code.status_code())
.unwrap_or(http::StatusCode::INTERNAL_SERVER_ERROR);
if status == http::StatusCode::SERVICE_UNAVAILABLE {
let subcause = crate::error::classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|err| err as &(dyn std::error::Error + 'static)),
);
rustfs_io_metrics::s3_http_metrics::record_s3_http_503_response(s3_code_metric_label(&parts.code), subcause);
let _ = CURRENT_503_SUBCAUSE.try_with(|slot| slot.set(Some(subcause)));
}
// A declared code compares equal to the custom code of the same spelling and status.
let code = ErrorCode::custom(parts.code.as_str().to_owned(), status);
let headers = parts.headers.unwrap_or_default();
@@ -55,6 +55,7 @@ pub(crate) mod test_support;
pub(super) use self::access::verified_signature;
pub(crate) use self::error::handler_error;
pub(in crate::server) use self::error::scope_503_subcause;
use crate::app::{Answered, RequestEnvelope};
use crate::runtime_sources::{AppContext, ServerContextSlot};
use rustfs_gateway::{Handler, HandlerError, HandlerResult, OperationCodec, Req, Resp, ServiceBuilder};
+10 -1
View File
@@ -405,7 +405,16 @@ impl GatewayStack {
// left unread in a detached task of its own, which takes the body away from
// `EarlyResponseBodyService`, the drain the HTTP/1-2 shutdown accounting owns. The
// adapter's connection verdict is kept.
let mut response = service.call(request).await;
let (mut response, subcause_503) =
crate::server::gateway_handlers::scope_503_subcause(async move { service.call(request).await }).await;
if response.status() == http::StatusCode::SERVICE_UNAVAILABLE
&& let Some(subcause) = subcause_503
{
response.headers_mut().insert(
http::HeaderName::from_static("x-rustfs-503-subcause"),
http::HeaderValue::from_static(subcause),
);
}
if track_plaintext_post_ssec && is_plaintext_ssec_refusal_response(&response) {
report_plaintext_ssec();
}
+101 -21
View File
@@ -75,24 +75,30 @@ pub(crate) async fn collect_probe_readiness(
HealthReadinessSource::ClusterWrite => collect_cluster_write_health_report().await,
HealthReadinessSource::ClusterRead => collect_cluster_read_health_report().await,
};
if probe == HealthProbe::Readiness
&& let Some(object_traffic_health) = object_traffic_health
{
apply_object_traffic_snapshot(&mut report, object_traffic_health.snapshot());
if let Some(object_traffic_health) = object_traffic_health {
apply_object_traffic_snapshot(&mut report, probe, object_traffic_health.snapshot());
}
Some(report)
}
fn apply_object_traffic_snapshot(report: &mut DependencyReadinessReport, snapshot: ObjectTrafficSnapshot) {
if snapshot.read_stalled {
fn apply_object_traffic_snapshot(report: &mut DependencyReadinessReport, probe: HealthProbe, snapshot: ObjectTrafficSnapshot) {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterRead) && snapshot.read_stalled {
let reason = ReadinessDegradedReason::ObjectReadStalled;
report.degraded_reasons.push(reason);
record_readiness_overlay_reason(reason);
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
}
if snapshot.write_stalled {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterWrite) && snapshot.write_stalled {
let reason = ReadinessDegradedReason::ObjectWriteStalled;
report.degraded_reasons.push(reason);
record_readiness_overlay_reason(reason);
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
}
}
@@ -321,21 +327,25 @@ pub(crate) fn build_health_response_parts(
),
};
let readiness_overlay_degraded = degraded_reasons.iter().any(|reason| {
matches!(
reason,
ReadinessDegradedReason::ObjectReadStalled
| ReadinessDegradedReason::ObjectWriteStalled
| ReadinessDegradedReason::StartupFinalizationPending
)
});
if probe == HealthProbe::Readiness && (readiness_overlay_degraded || matches!(kms_ready, Some(false))) {
let startup_pending = degraded_reasons.contains(&ReadinessDegradedReason::StartupFinalizationPending);
let write_stalled = degraded_reasons.contains(&ReadinessDegradedReason::ObjectWriteStalled);
let read_stalled = degraded_reasons.contains(&ReadinessDegradedReason::ObjectReadStalled);
let readiness_overlay_degraded = match probe {
HealthProbe::Readiness => startup_pending || write_stalled || read_stalled || matches!(kms_ready, Some(false)),
HealthProbe::ClusterWrite => write_stalled,
HealthProbe::ClusterRead => read_stalled,
HealthProbe::Liveness => false,
};
if readiness_overlay_degraded {
health = HealthCheckState {
status_code: StatusCode::SERVICE_UNAVAILABLE,
status: "degraded",
ready: false,
};
if matches!(kms_ready, Some(false)) && !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady) {
if probe == HealthProbe::Readiness
&& matches!(kms_ready, Some(false))
&& !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady)
{
degraded_reasons.push(ReadinessDegradedReason::KmsNotReady);
}
}
@@ -716,6 +726,7 @@ mod tests {
let mut report = ready_report();
apply_object_traffic_snapshot(
&mut report,
HealthProbe::Readiness,
ObjectTrafficSnapshot {
read_stalled: true,
write_stalled: false,
@@ -880,4 +891,73 @@ mod tests {
assert_eq!(payload["degradedReasons"], json!([]));
});
}
#[test]
#[serial]
fn cluster_probes_reflect_matching_traffic_stalls_without_startup_admission_overlay() {
with_var(rustfs_config::ENV_HEALTH_MINIMAL_RESPONSE_ENABLE, Some("false"), || {
let mut startup_report = ready_report();
startup_report
.degraded_reasons
.push(ReadinessDegradedReason::StartupFinalizationPending);
// Node readiness waits for S3 admission publication, while cluster probes continue
// reporting cluster quorum readiness before node-local publication.
let readiness = build_health_response_parts(
Method::GET,
HealthProbe::Readiness,
Some(&startup_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(readiness.status_code, StatusCode::SERVICE_UNAVAILABLE);
for probe in [HealthProbe::ClusterWrite, HealthProbe::ClusterRead] {
let parts = build_health_response_parts(Method::GET, probe, Some(&startup_report), "rustfs-endpoint", None, None);
assert_eq!(parts.status_code, StatusCode::OK, "{probe:?}");
}
let mut write_report = ready_report();
apply_object_traffic_snapshot(
&mut write_report,
HealthProbe::ClusterWrite,
ObjectTrafficSnapshot {
read_stalled: true,
write_stalled: true,
},
);
let write_parts = build_health_response_parts(
Method::GET,
HealthProbe::ClusterWrite,
Some(&write_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(write_parts.status_code, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
write_parts.payload.expect("cluster write payload")["degradedReasons"],
json!(["object_write_stalled"])
);
let mut read_report = ready_report();
apply_object_traffic_snapshot(
&mut read_report,
HealthProbe::ClusterRead,
ObjectTrafficSnapshot {
read_stalled: false,
write_stalled: true,
},
);
let read_parts = build_health_response_parts(
Method::GET,
HealthProbe::ClusterRead,
Some(&read_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(read_parts.status_code, StatusCode::OK);
});
}
}
+31
View File
@@ -2971,6 +2971,37 @@ pub(in crate::server) mod tests {
.is_empty()
);
let response = service
.call(
Request::builder()
.method(Method::GET)
.uri(MINIO_HEALTH_CLUSTER_READ_PATH)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster read request"),
)
.await
.expect("cluster read response");
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body = BodyExt::collect(response.into_body())
.await
.expect("cluster read body")
.to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).expect("cluster read JSON");
assert_eq!(payload["ready"], false);
assert_eq!(payload["degradedReasons"], serde_json::json!(["object_read_stalled"]));
let response = service
.call(
Request::builder()
.method(Method::GET)
.uri(MINIO_HEALTH_CLUSTER_PATH)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster write request"),
)
.await
.expect("cluster write response");
assert_eq!(response.status(), StatusCode::OK);
let response = service
.call(
Request::builder()
+36 -1
View File
@@ -179,6 +179,7 @@ fn readiness_pending_dependency(stage: rustfs_common::SystemStage) -> &'static s
fn service_not_ready_response(stage: rustfs_common::SystemStage) -> Response<BoxBody> {
let pending = readiness_pending_dependency(stage);
rustfs_io_metrics::s3_http_metrics::record_s3_http_503_response("ServiceUnavailable", "readiness_pending");
let body: BoxBody = Full::new(Bytes::from(format!("Service not ready: waiting for {pending}")))
.map_err(|never| match never {})
.boxed_unsync();
@@ -197,6 +198,10 @@ fn service_not_ready_response(stage: rustfs_common::SystemStage) -> Response<Box
response
.headers_mut()
.insert(READINESS_PENDING_HEADER, HeaderValue::from_static(pending));
response.headers_mut().insert(
http::HeaderName::from_static("x-rustfs-503-subcause"),
HeaderValue::from_static("readiness_pending"),
);
response
}
@@ -2539,7 +2544,10 @@ mod tests {
#[tokio::test]
async fn service_not_ready_response_preserves_observable_contract() {
let response = service_not_ready_response(rustfs_common::SystemStage::Booting);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let response =
metrics::with_local_recorder(&recorder, || service_not_ready_response(rustfs_common::SystemStage::Booting));
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
@@ -2570,6 +2578,33 @@ mod tests {
.and_then(|value| value.to_str().ok()),
Some("storage_quorum")
);
assert_eq!(
response
.headers()
.get("x-rustfs-503-subcause")
.and_then(|value| value.to_str().ok()),
Some("readiness_pending")
);
let counted = snapshotter
.snapshot()
.into_vec()
.into_iter()
.find_map(|(composite, _, _, value)| {
(composite.key().name() == "rustfs_s3_503_responses_total"
&& composite
.key()
.labels()
.any(|label| label.key() == "code" && label.value() == "ServiceUnavailable")
&& composite
.key()
.labels()
.any(|label| label.key() == "subcause" && label.value() == "readiness_pending"))
.then_some(value)
});
assert!(
matches!(counted, Some(DebugValue::Counter(1))),
"service_not_ready_response must increment rustfs_s3_503_responses_total once"
);
let body = match response.into_body().collect().await {
Ok(body) => body.to_bytes(),
Err(err) => panic!("not-ready body should collect: {err}"),
+1 -1
View File
@@ -1282,7 +1282,7 @@ impl ConcurrencyManager {
match state {
AdmissionState::Disabled => admission.with_reason("disk read permits disabled"),
AdmissionState::Saturated => admission.with_reason("all disk read permits are in use"),
AdmissionState::Saturated => admission.with_reason("all primary disk-backed GET permits are in use"),
_ => admission,
}
}
+102 -34
View File
@@ -315,27 +315,52 @@ macro_rules! log_internode_rpc_response_failure {
}
macro_rules! log_internode_put_file_stage_failure {
($stage:expr, $query:expr, $err:expr) => {
error!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "failed",
status_code = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_stage_failed",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %$err,
"internode rpc request failed"
);
};
($stage:expr, $query:expr, $err:expr) => {{
let err_ref: &(dyn std::error::Error + 'static) = $err;
let status = classify_put_file_stage_status($stage, err_ref);
if status == StatusCode::BAD_REQUEST {
tracing::debug!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "aborted_by_sender",
status_code = status.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_body_aborted",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %err_ref,
"internode put_file stream aborted by sender"
);
} else {
error!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "failed",
status_code = status.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_stage_failed",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %err_ref,
"internode rpc request failed"
);
}
status
}};
}
/// Answers the internode rpc paths itself and hands every other request to
@@ -2110,7 +2135,7 @@ where
cleanup.downcast_ref::<DiskError>(),
Some(DiskError::FileNotFound | DiskError::VolumeNotFound)
) {
log_internode_put_file_stage_failure!("cleanup_staging", query, cleanup);
let _ = log_internode_put_file_stage_failure!("cleanup_staging", query, cleanup.as_ref());
}
return Err((stage, primary));
}
@@ -2223,8 +2248,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(copied) => copied,
Err((stage, e)) => {
let message = put_file_stage_error_message(stage, &query, e.as_ref());
log_internode_put_file_stage_failure!(stage, query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!(stage, query, e.as_ref());
return response_with_status(status, message);
}
};
record_put_file_metrics(copied);
@@ -2239,8 +2264,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(file) => file,
Err(e) => {
let message = put_file_stage_error_message("append", &query, &e);
log_internode_put_file_stage_failure!("append", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("append", query, &e);
return response_with_status(status, message);
}
}
} else {
@@ -2248,8 +2273,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(file) => file,
Err(e) => {
let message = put_file_stage_error_message("create", &query, &e);
log_internode_put_file_stage_failure!("create", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("create", query, &e);
return response_with_status(status, message);
}
}
};
@@ -2260,8 +2285,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(copied) => copied,
Err(e) => {
let message = put_file_stage_error_message("write_body", &query, &e);
log_internode_put_file_stage_failure!("write_body", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("write_body", query, &e);
return response_with_status(status, message);
}
};
@@ -2273,14 +2298,14 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
format!("body size mismatch: expected {} bytes, received {copied}", query.size),
);
let message = put_file_stage_error_message("verify_size", &query, &err);
log_internode_put_file_stage_failure!("verify_size", query, err);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("verify_size", query, &err);
return response_with_status(status, message);
}
if let Err(e) = file.flush().await {
let message = put_file_stage_error_message("flush", &query, &e);
log_internode_put_file_stage_failure!("flush", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("flush", query, &e);
return response_with_status(status, message);
}
empty_ok()
@@ -2505,6 +2530,49 @@ fn put_body_size_mismatch(query: &PutFileQuery, copied: u64) -> bool {
!query.append && query.size > 0 && copied != u64::try_from(query.size).unwrap_or(u64::MAX)
}
fn classify_put_file_stage_status(stage: &str, err: &(dyn std::error::Error + 'static)) -> StatusCode {
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(cause) = current {
if let Some(disk_err) = cause.downcast_ref::<DiskError>()
&& matches!(
disk_err,
DiskError::Timeout
| DiskError::FaultyDisk
| DiskError::FaultyRemoteDisk
| DiskError::DiskNotFound
| DiskError::DiskFull
| DiskError::TooManyOpenFiles
| DiskError::DiskOngoingReq
)
{
return StatusCode::SERVICE_UNAVAILABLE;
}
if matches!(stage, "write_body" | "verify_size") {
if let Some(io_err) = cause.downcast_ref::<io::Error>()
&& matches!(
io_err.kind(),
io::ErrorKind::UnexpectedEof
| io::ErrorKind::ConnectionReset
| io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionAborted
)
{
return StatusCode::BAD_REQUEST;
}
if let Some(hyper_err) = cause.downcast_ref::<hyper::Error>()
&& (hyper_err.is_body_write_aborted()
|| hyper_err.is_incomplete_message()
|| hyper_err.is_closed()
|| hyper_err.is_canceled())
{
return StatusCode::BAD_REQUEST;
}
}
current = cause.source();
}
StatusCode::INTERNAL_SERVER_ERROR
}
fn put_file_stage_error_message(stage: &str, query: &PutFileQuery, err: &dyn std::fmt::Display) -> String {
format!(
"{stage} file err {err} [disk={}, volume={}, path={}, append={}, size={}]",