mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-02 14:18:01 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b71942cf26 | |||
| ad9b5e29e6 | |||
| d8e2353825 | |||
| c3fb1aa4a0 |
@@ -144,6 +144,14 @@ threads-required = "num-test-threads"
|
||||
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# This 12-disk three-pool hot-reload and Pool-0 decommission E2E fixture drives
|
||||
# concurrent S3 traffic and durable pool migration under a 90s drain budget.
|
||||
# Reserve capacity so sibling disk fixtures cannot starve its target capacity
|
||||
# mutation gate; its deadlines, assertions, and zero-retry policy stay intact.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(rustfs) & binary(pool_hot_reload_e2e_test) & test(=multi_pool_1_to_2_to_3_expand_and_3_to_2_pool0_removal_with_concurrent_s3_io_e2e)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(rustfs-heal) & (binary(mrf_partial_write_test) | (binary(mrf_pipeline_test) & test(/^journal_replay_survives_/)) | test(=admin_selector_survives_sigkill_with_original_scope_and_receipts))'
|
||||
threads-required = "num-test-threads"
|
||||
@@ -511,6 +519,13 @@ threads-required = "num-test-threads"
|
||||
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# Match the local capacity reservation for the 12-disk three-pool hot-reload
|
||||
# and Pool-0 decommission E2E fixture; deadlines, assertions, and zero retries
|
||||
# remain in force.
|
||||
[[profile.ci.overrides]]
|
||||
filter = 'package(rustfs) & binary(pool_hot_reload_e2e_test) & test(=multi_pool_1_to_2_to_3_expand_and_3_to_2_pool0_removal_with_concurrent_s3_io_e2e)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
[[profile.ci.overrides]]
|
||||
filter = 'package(rustfs-heal) & (binary(mrf_partial_write_test) | (binary(mrf_pipeline_test) & test(/^journal_replay_survives_/)) | test(=admin_selector_survives_sigkill_with_original_scope_and_receipts))'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
@@ -7,3 +7,4 @@ self-hosted-runner:
|
||||
- dind-sm-standard-2
|
||||
- smoke-testing
|
||||
- pf-testing
|
||||
- rdma
|
||||
|
||||
@@ -296,6 +296,29 @@
|
||||
"origin": "baseline",
|
||||
"alert_contract": "scheduled-validation"
|
||||
},
|
||||
{
|
||||
"workflow": ".github/workflows/rdma-build.yml",
|
||||
"name": "S3-over-RDMA compile",
|
||||
"roles": [
|
||||
"pr",
|
||||
"manual"
|
||||
],
|
||||
"events": [
|
||||
"pull_request",
|
||||
"push",
|
||||
"workflow_dispatch"
|
||||
],
|
||||
"cadence": "event",
|
||||
"timezone": "UTC",
|
||||
"schedule": [],
|
||||
"owner": "@overtrue",
|
||||
"policy": "active",
|
||||
"monitor": "none",
|
||||
"result_owner": "rdma-build.yml",
|
||||
"disposition": "retained independent entry",
|
||||
"monitor_reason": "Event-driven or operator-requested work has no periodic freshness obligation.",
|
||||
"origin": "added"
|
||||
},
|
||||
{
|
||||
"workflow": ".github/workflows/rdma-feature-check.yml",
|
||||
"name": "S3-over-RDMA feature check",
|
||||
|
||||
@@ -45,7 +45,7 @@ A hosted runner is also the only choice for a few things the pods cannot do: `mo
|
||||
|
||||
- Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not.
|
||||
- The `ci-dev` key ends in a digest of `warm-ci-dev`'s build commands. Changing what that job warms therefore needs a new key, or readers keep restoring the old artifacts: `scripts/ci_gate.py --check-workflow` prints the key the commands require and fails until the writer and every registered `sm-standard-4` reader (`ci.yml`, `dual-stack-nightly.yml`, `e2e-replication-nightly.yml`, `fuzz.yml`, `gateway-acceptance.yml`, `mint.yml` and `reference-parity.yml`) name it.
|
||||
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`).
|
||||
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`). `rdma-build.yml` owns `ci-nixl-rdma` on the `rdma` label and is the only job that saves it.
|
||||
- Moving a job between pools therefore means renaming its key. The new key is empty until a run from `main` (a scheduled run, or a manual dispatch of that workflow from `main`) saves it; until then that lane does a cold build. The `build.yml` aarch64 release legs append `-ubicloud-arm` for this reason. `cache-warm.yml` does not write those keys.
|
||||
- `CARGO_BUILD_JOBS` and every other `CARGO*`, `CC*`, `CFLAGS*`, `CXX*`, `CMAKE*` and `RUST*` variable is hashed into the key. `ci.yml` sets `CARGO_BUILD_JOBS` at step level for that reason; promoting it to job level rotates the key for every lane that shares it.
|
||||
|
||||
|
||||
@@ -382,19 +382,6 @@ jobs:
|
||||
} > artifacts/workspace/doctest-diagnostics.txt
|
||||
exit "${status}"
|
||||
|
||||
- name: Verify production ECStore crash and recovery
|
||||
if: needs.classify-changes.outputs.mode == 'full'
|
||||
env:
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
run: |
|
||||
dst=(--locked -p rustfs-ecstore --features dst --test dst_production_ecstore --profile ci)
|
||||
mkdir -p artifacts/workspace/dst
|
||||
cargo nextest list "${dst[@]}" --message-format json > artifacts/workspace/dst/selection.json
|
||||
rm -f target/nextest/ci/junit.xml
|
||||
trap 'if [[ -f target/nextest/ci/junit.xml ]]; then cp target/nextest/ci/junit.xml artifacts/workspace/dst/junit.xml; fi' EXIT
|
||||
cargo nextest run "${dst[@]}" --no-tests fail --retries 0
|
||||
python3 scripts/ci_test_artifact.py evidence --dst artifacts/workspace/dst/selection.json target/nextest/ci/junit.xml
|
||||
|
||||
- name: Upload test reports and diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
@@ -417,8 +404,10 @@ jobs:
|
||||
needs: [ workspace-lint-and-build, classify-changes ]
|
||||
# The archive retains compile-time fixture paths and the large test set
|
||||
# requires the same runner image until the hosted-runtime pilot passes.
|
||||
# Full mode runs archive extraction, the 75m workspace suite, the 80m
|
||||
# serial ILM suite, and Vector KMS verification under their own step budgets.
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
timeout-minutes: 180
|
||||
env:
|
||||
CI_PACKAGES: ${{ needs.classify-changes.outputs.packages }}
|
||||
steps:
|
||||
|
||||
@@ -190,7 +190,8 @@ jobs:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
CARGO_BUILD_TARGET: x86_64-unknown-linux-gnu
|
||||
# Fuzz targets build without the dial9 feature, so tokio_unstable is not needed.
|
||||
RUSTFLAGS: "-C target-feature=-crt-static"
|
||||
# Use lld with bounded linker threads so linking all instrumented harnesses stays within the pod memory budget.
|
||||
RUSTFLAGS: "-C target-feature=-crt-static -C link-arg=-fuse-ld=lld -C link-arg=-Wl,--threads=2"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -201,7 +202,7 @@ jobs:
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: nightly
|
||||
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
|
||||
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'schedule' }}
|
||||
|
||||
- name: Install cargo-fuzz
|
||||
@@ -209,10 +210,15 @@ jobs:
|
||||
with:
|
||||
tool: cargo-fuzz
|
||||
|
||||
- name: Install lld
|
||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends lld
|
||||
|
||||
- name: Build selected fuzz targets
|
||||
env:
|
||||
# Keep memory-intensive instrumented rustc processes from crowding out the runner.
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
# Split monolithic ASan+SanCov LLVM modules across 16 codegen units so huge crates stay within 28 GB RAM.
|
||||
FUZZ_CODEGEN_UNITS: "16"
|
||||
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
|
||||
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# Copyright 2024 RustFS Team
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
name: S3-over-RDMA compile
|
||||
|
||||
# Compile the optional `nixl` feature when NIXL/RDMA sources change.
|
||||
# Pull requests and pushes to main share one path list; workflow_dispatch
|
||||
# runs the same job with no path filter. Unrelated changes do not start a runner.
|
||||
#
|
||||
# The job runs on the self-hosted `rdma` label, the same bare-label form as
|
||||
# `smoke-testing` and `sm-standard-4`. nixl-sys links libnixl when that
|
||||
# runner has it installed (NIXL_PREFIX, default /opt/nvidia/nvda_nixl, or
|
||||
# pkg-config). When the libraries are absent it compiles wrapper.h plus the
|
||||
# dlopen stub. This job does not set NIXL_NO_STUBS_FALLBACK. bindgen needs
|
||||
# g++ and libclang; the setup action installs a C toolchain, and the step
|
||||
# below adds libclang only when the image lacks it.
|
||||
#
|
||||
# Host-memory unit tests and the cuObject SDK lane stay in
|
||||
# rdma-feature-check.yml (pull requests, weekly schedule, manual dispatch).
|
||||
# Not a required check and not part of the `Test and Lint` aggregate.
|
||||
#
|
||||
# When adding a nixl-gated module, extend both path lists below. GitHub
|
||||
# filters are whole files: shared files are listed because they contain
|
||||
# `feature = "nixl"` branches, and crates/config/src/constants/internode.rs
|
||||
# also holds unrelated internode constants.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "crates/nixl/**"
|
||||
- "crates/ecstore/src/cluster/rpc/nixl_internode.rs"
|
||||
- "crates/ecstore/src/cluster/rpc/nixl_internode/**"
|
||||
- "crates/config/src/constants/internode.rs"
|
||||
- "rustfs/src/app/multipart_usecase/upload_part.rs"
|
||||
- "rustfs/src/app/object/cuobject.rs"
|
||||
- "rustfs/src/app/object/get.rs"
|
||||
- "rustfs/src/app/object/mod.rs"
|
||||
- "rustfs/src/app/object/put.rs"
|
||||
- "rustfs/src/app/storage_api.rs"
|
||||
- "rustfs/src/startup_server.rs"
|
||||
- "rustfs/src/storage/rpc/http_service.rs"
|
||||
- "rustfs/src/storage/rpc/mod.rs"
|
||||
- "rustfs/src/storage/rpc/nixl*"
|
||||
- "rustfs/src/storage/storage_api.rs"
|
||||
- "Cargo.toml"
|
||||
- "rustfs/Cargo.toml"
|
||||
- ".github/workflows/rdma-build.yml"
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "crates/nixl/**"
|
||||
- "crates/ecstore/src/cluster/rpc/nixl_internode.rs"
|
||||
- "crates/ecstore/src/cluster/rpc/nixl_internode/**"
|
||||
- "crates/config/src/constants/internode.rs"
|
||||
- "rustfs/src/app/multipart_usecase/upload_part.rs"
|
||||
- "rustfs/src/app/object/cuobject.rs"
|
||||
- "rustfs/src/app/object/get.rs"
|
||||
- "rustfs/src/app/object/mod.rs"
|
||||
- "rustfs/src/app/object/put.rs"
|
||||
- "rustfs/src/app/storage_api.rs"
|
||||
- "rustfs/src/startup_server.rs"
|
||||
- "rustfs/src/storage/rpc/http_service.rs"
|
||||
- "rustfs/src/storage/rpc/mod.rs"
|
||||
- "rustfs/src/storage/rpc/nixl*"
|
||||
- "rustfs/src/storage/storage_api.rs"
|
||||
- "Cargo.toml"
|
||||
- "rustfs/Cargo.toml"
|
||||
- ".github/workflows/rdma-build.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Cancel a superseded pull-request attempt. Pushes and manual runs finish.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
|
||||
jobs:
|
||||
nixl-build:
|
||||
name: cargo check and test compile (nixl)
|
||||
# Hardware: the RDMA/NIXL runner. Hosted ubuntu-latest has no NIXL/UCX
|
||||
# libraries. The label matches smoke-testing and sm-standard-4 (bare
|
||||
# label, not a [self-hosted, ...] list).
|
||||
runs-on: rdma
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
# Own key: rust-cache does not include the runner label, and
|
||||
# ci-e2e-distributed-hosted is written on ubuntu-latest.
|
||||
cache-shared-key: ci-nixl-rdma
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Install only missing native build tools
|
||||
run: |
|
||||
packages=()
|
||||
command -v g++ >/dev/null || packages+=(g++)
|
||||
ldconfig -p | grep -q 'libclang' || packages+=(libclang-dev)
|
||||
if (( ${#packages[@]} )); then
|
||||
sudo apt-get update
|
||||
sudo apt-get install --no-install-recommends -y "${packages[@]}"
|
||||
fi
|
||||
|
||||
- name: Check the nixl feature build
|
||||
run: cargo check --locked -p rustfs --features nixl
|
||||
|
||||
# Compiles rustfs-nixl unit and integration tests, including client-http.
|
||||
# Does not execute them: the host-memory suite runs in rdma-feature-check.yml.
|
||||
# `cargo test --no-run -p rustfs` is not used; that harness is the workspace
|
||||
# test build and does not fit this runner.
|
||||
- name: Compile rustfs-nixl tests
|
||||
run: cargo test --locked --no-run -p rustfs-nixl --features client-http
|
||||
@@ -2,6 +2,8 @@ name: S3-over-RDMA feature check
|
||||
|
||||
# Compile the optional RDMA features independently. The cuObject tests link
|
||||
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
|
||||
# Pushes to main are compiled by rdma-build.yml; this workflow keeps the
|
||||
# rustfs-nixl unit tests, the cuObject SDK lane, and the weekly run.
|
||||
# Not a required check and not part of the `Test and Lint` aggregate.
|
||||
|
||||
on:
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
@@ -2944,6 +2944,14 @@ mod tests {
|
||||
.expect("ledger")
|
||||
}
|
||||
|
||||
async fn read_test_ledger_synchronized(job: &ReconcileJob) -> QuotaLedger {
|
||||
let object = ledger_object(&job.bucket);
|
||||
let _guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_read", get_lock_acquire_timeout())
|
||||
.await
|
||||
.expect("ledger lock");
|
||||
load_ledger_locked(Arc::clone(&job.store), &object).await.expect("ledger")
|
||||
}
|
||||
|
||||
async fn drain_reconciliation_scheduler(job: &ReconcileJob) {
|
||||
let key = (
|
||||
job.store.id,
|
||||
@@ -3419,7 +3427,7 @@ mod tests {
|
||||
pause.reached().await;
|
||||
let at_seed = overwrites.load(Ordering::SeqCst);
|
||||
assert!(
|
||||
read_test_ledger(&job).await.scan_seed.is_some(),
|
||||
read_test_ledger_synchronized(&job).await.scan_seed.is_some(),
|
||||
"the recount seeded over in-flight writes"
|
||||
);
|
||||
// Admitted after the seed and visible to the walk: counted twice.
|
||||
@@ -3429,7 +3437,7 @@ mod tests {
|
||||
pause.0.release.notify_one();
|
||||
drain_reconciliation_scheduler(&job).await;
|
||||
|
||||
let published = read_test_ledger(&job).await;
|
||||
let published = read_test_ledger_synchronized(&job).await;
|
||||
let live = 10 + 35 + 1 + 5;
|
||||
assert!(published.scan_seed.is_none(), "the overlapping recount published");
|
||||
assert_eq!(
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -70,12 +70,6 @@ use crate::disk::{
|
||||
endpoint::Endpoint,
|
||||
error::{DiskError, Error, Result},
|
||||
format::FormatV3,
|
||||
multipart_source::{
|
||||
MULTIPART_SOURCE_PROTOCOL_VERSION, MultipartProofKind, MultipartPublicationResult, MultipartSourceOperation,
|
||||
MultipartSourcePhase, MultipartSourceProof, MultipartSourceRequest, MultipartSourceResponse, MultipartSourceSnapshot,
|
||||
MultipartUndoCapability, ProofVerificationContext, PublicationIdentity, SourceConditionV1, capture_source_condition,
|
||||
publication_identity, require_source_condition, strip_transport_condition,
|
||||
},
|
||||
part_transaction_path, validate_delete_recovery_options, validate_format_control_path,
|
||||
};
|
||||
use crate::erasure::coding::{self, bitrot_verify};
|
||||
@@ -84,8 +78,6 @@ use crate::set_disk::SetDisks;
|
||||
use crate::store::init_format::save_format_file;
|
||||
|
||||
const DST_DELETE_TX_DIR: &str = ".rustfs.sys/dst-del-tx";
|
||||
const DST_MULTIPART_STATE: &str = ".dst-mpu-consumed";
|
||||
const DST_MULTIPART_ANCHOR: &str = ".dst-mpu-retirement-anchor";
|
||||
const DEFAULT_SIM_CAPACITY_BYTES: u64 = 10 * 1024 * 1024 * 1024;
|
||||
|
||||
fn sim_to_io_err(err: SimErr) -> IoError {
|
||||
@@ -218,22 +210,6 @@ struct SimDeleteTxRecord {
|
||||
backup_xl: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SimMultipartAnchor {
|
||||
disk_id: Uuid,
|
||||
physical_slot: usize,
|
||||
publication: PublicationIdentity,
|
||||
original_sha256: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct SimMultipartState {
|
||||
anchor: SimMultipartAnchor,
|
||||
capability_sha256: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
/// Deterministic simulated disk implementing production [`DiskAPI`] directly
|
||||
/// on top of [`SimDiskIo`].
|
||||
#[derive(Clone)]
|
||||
@@ -250,7 +226,6 @@ pub struct DstSimDisk {
|
||||
scanning: Arc<AtomicU32>,
|
||||
delete_tx_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
cas_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
multipart_publication_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
configured_capacity: Arc<RwLock<Option<u64>>>,
|
||||
multipart_proof_authority: Arc<RwLock<Option<crate::disk::multipart_source::ProofVerificationContext>>>,
|
||||
}
|
||||
@@ -306,7 +281,6 @@ impl DstSimDisk {
|
||||
scanning: Arc::new(AtomicU32::new(0)),
|
||||
delete_tx_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
cas_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
multipart_publication_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
configured_capacity: Arc::new(RwLock::new(None)),
|
||||
multipart_proof_authority: Arc::new(RwLock::new(None)),
|
||||
}
|
||||
@@ -325,12 +299,6 @@ impl DstSimDisk {
|
||||
&self.sim
|
||||
}
|
||||
|
||||
/// Returns the simulator-only retirement witness path for fault injection.
|
||||
pub fn multipart_retirement_anchor_path(volume: &str, object: &str, data_dir: Uuid) -> Result<String> {
|
||||
let target_dir = join_vol_path(volume, object)?;
|
||||
Ok(format!("{target_dir}/{data_dir}/{DST_MULTIPART_ANCHOR}"))
|
||||
}
|
||||
|
||||
pub fn crash_registry(&self) -> &CrashRegistry {
|
||||
&self.crash_registry
|
||||
}
|
||||
@@ -463,241 +431,6 @@ impl DstSimDisk {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn multipart_authority(&self) -> Result<ProofVerificationContext> {
|
||||
self.multipart_proof_authority
|
||||
.read()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.clone()
|
||||
.ok_or(DiskError::UnsupportedDisk)
|
||||
}
|
||||
|
||||
async fn sync_multipart_source_absence(&self, mut path: &str) -> Result<()> {
|
||||
while let Some((parent, _)) = path.rsplit_once('/') {
|
||||
match self.sim.stat(parent).await {
|
||||
Ok(contents) if contents.is_dir => return self.fsync_parent_chain(parent).await,
|
||||
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
|
||||
Err(SimErr::NotFound(_)) => path = parent,
|
||||
Err(error) => return Err(map_sim_err(error)),
|
||||
}
|
||||
}
|
||||
self.fsync_parent_chain("").await
|
||||
}
|
||||
|
||||
async fn prepare_multipart_anchor(
|
||||
&self,
|
||||
source_dir: &str,
|
||||
src_path: &str,
|
||||
target: (&str, &str),
|
||||
fi: &FileInfo,
|
||||
publication: PublicationIdentity,
|
||||
) -> Result<SimMultipartAnchor> {
|
||||
self.multipart_authority()?;
|
||||
let condition = require_source_condition(fi)?;
|
||||
if publication.lineage.path != src_path
|
||||
|| (publication.lineage.bucket.as_str(), publication.lineage.object.as_str()) != target
|
||||
|| condition.attach(&mut fi.clone())? != publication
|
||||
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
|
||||
{
|
||||
return Err(DiskError::ConditionalDeleteConflict);
|
||||
}
|
||||
match self.sim.stat(&format!("{source_dir}/{DST_MULTIPART_STATE}")).await {
|
||||
Err(SimErr::NotFound(_)) => {}
|
||||
Err(error) => return Err(map_sim_err(error)),
|
||||
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
|
||||
}
|
||||
let original = self
|
||||
.sim
|
||||
.read_file(&format!("{source_dir}/{STORAGE_FORMAT_FILE}"))
|
||||
.await
|
||||
.map_err(map_sim_err)?;
|
||||
let original_fi = get_file_info(
|
||||
&original,
|
||||
RUSTFS_META_MULTIPART_BUCKET,
|
||||
src_path,
|
||||
&publication.lineage.original_version_id.unwrap_or_default().to_string(),
|
||||
FileInfoOpts {
|
||||
data: false,
|
||||
include_free_versions: false,
|
||||
include_part_checksums: true,
|
||||
},
|
||||
)?;
|
||||
if capture_source_condition(target.0, target.1, src_path, &original_fi, publication.attempt)? != condition
|
||||
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&original_fi.erasure.index)
|
||||
{
|
||||
return Err(DiskError::ConditionalDeleteConflict);
|
||||
}
|
||||
Ok(SimMultipartAnchor {
|
||||
disk_id: self.get_disk_id().await?.ok_or(DiskError::InconsistentDisk)?,
|
||||
physical_slot: self.disk_idx,
|
||||
publication,
|
||||
original_sha256: Sha256::digest(original).into(),
|
||||
})
|
||||
}
|
||||
|
||||
fn multipart_snapshot(
|
||||
anchor: &SimMultipartAnchor,
|
||||
revision: u64,
|
||||
phase: MultipartSourcePhase,
|
||||
record: &[u8],
|
||||
target: &[u8],
|
||||
capability_sha256: Option<[u8; 32]>,
|
||||
) -> MultipartSourceSnapshot {
|
||||
let state_sha256: [u8; 32] = Sha256::digest(record).into();
|
||||
let mut inventory = Sha256::new();
|
||||
inventory.update(state_sha256);
|
||||
inventory.update(Sha256::digest(target));
|
||||
MultipartSourceSnapshot {
|
||||
disk_id: anchor.disk_id,
|
||||
physical_slot: anchor.physical_slot,
|
||||
lineage: anchor.publication.lineage.clone(),
|
||||
generation: anchor.publication.source_generation,
|
||||
revision,
|
||||
phase,
|
||||
state_sha256,
|
||||
head_sha256: None,
|
||||
inventory_sha256: inventory.finalize().into(),
|
||||
capability_sha256,
|
||||
publication: Some(anchor.publication.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn publish_multipart_witness(
|
||||
&self,
|
||||
source_dir: &str,
|
||||
target_dir: &str,
|
||||
anchor: SimMultipartAnchor,
|
||||
target: &[u8],
|
||||
) -> Result<MultipartPublicationResult> {
|
||||
let authority = self.multipart_authority()?;
|
||||
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", anchor.publication.final_data_dir);
|
||||
let anchor_bytes = rmp_serde::to_vec_named(&anchor).map_err(Error::other)?;
|
||||
self.write_durable_file(&anchor_path, Bytes::from(anchor_bytes)).await?;
|
||||
|
||||
let undo_capability = MultipartUndoCapability::new();
|
||||
let state = SimMultipartState {
|
||||
anchor,
|
||||
capability_sha256: Some(undo_capability.digest()),
|
||||
};
|
||||
let record = rmp_serde::to_vec_named(&state).map_err(Error::other)?;
|
||||
// The fsync of the source directory also persists removal of its old
|
||||
// xl.meta name, which was renamed to the destination during commit.
|
||||
self.write_durable_file(&format!("{source_dir}/{DST_MULTIPART_STATE}"), Bytes::copy_from_slice(&record))
|
||||
.await?;
|
||||
let snapshot = Self::multipart_snapshot(
|
||||
&state.anchor,
|
||||
1,
|
||||
MultipartSourcePhase::ConsumedUnsealed,
|
||||
&record,
|
||||
target,
|
||||
state.capability_sha256,
|
||||
);
|
||||
let publication = state.anchor.publication;
|
||||
let proof = MultipartSourceProof::issue(&authority, MultipartProofKind::Published, publication.attempt, None, snapshot)?;
|
||||
Ok(MultipartPublicationResult {
|
||||
publication,
|
||||
proof,
|
||||
undo_capability,
|
||||
})
|
||||
}
|
||||
|
||||
async fn confirm_multipart_witness(
|
||||
&self,
|
||||
path: &str,
|
||||
publication: &PublicationIdentity,
|
||||
challenge: Uuid,
|
||||
) -> Result<MultipartSourceProof> {
|
||||
self.ensure_online()?;
|
||||
publication.lineage.validate()?;
|
||||
if publication.lineage.path != path || challenge.is_nil() {
|
||||
return Err(DiskError::ConditionalDeleteConflict);
|
||||
}
|
||||
let _guard = self.multipart_publication_lock.lock().await;
|
||||
let authority = self.multipart_authority()?;
|
||||
let lineage = &publication.lineage;
|
||||
let source_dir = join_vol_path(RUSTFS_META_MULTIPART_BUCKET, path)?;
|
||||
let target_dir = join_vol_path(&lineage.bucket, &lineage.object)?;
|
||||
let target_meta = format!("{target_dir}/{STORAGE_FORMAT_FILE}");
|
||||
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", publication.final_data_dir);
|
||||
let anchor_raw = self.sim.read_file(&anchor_path).await.map_err(map_sim_err)?;
|
||||
let anchor: SimMultipartAnchor = rmp_serde::from_slice(&anchor_raw).map_err(Error::other)?;
|
||||
if Some(anchor.disk_id) != self.get_disk_id().await?
|
||||
|| anchor.physical_slot != self.disk_idx
|
||||
|| anchor.publication != *publication
|
||||
{
|
||||
return Err(DiskError::ConditionalDeleteConflict);
|
||||
}
|
||||
|
||||
let target = self.sim.read_file(&target_meta).await.map_err(map_sim_err)?;
|
||||
let fi = get_file_info(
|
||||
&target,
|
||||
&lineage.bucket,
|
||||
&lineage.object,
|
||||
&publication.version_id.unwrap_or_default().to_string(),
|
||||
FileInfoOpts {
|
||||
data: false,
|
||||
include_free_versions: false,
|
||||
include_part_checksums: true,
|
||||
},
|
||||
)?;
|
||||
let condition = SourceConditionV1 {
|
||||
lineage: lineage.clone(),
|
||||
generation: publication.source_generation,
|
||||
attempt: publication.attempt,
|
||||
};
|
||||
let geometry = &lineage.geometry;
|
||||
if publication_identity(&fi)?.as_ref() != Some(publication)
|
||||
|| condition.attach(&mut fi.clone())? != *publication
|
||||
|| geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
|
||||
|| fi.erasure.distribution != geometry.distribution
|
||||
|| fi.erasure.data_blocks != geometry.data_blocks
|
||||
|| fi.erasure.parity_blocks != geometry.parity_blocks
|
||||
|| fi.erasure.block_size != geometry.block_size
|
||||
{
|
||||
return Err(DiskError::ConditionalDeleteConflict);
|
||||
}
|
||||
if !fi.inline_data() && fi.size > 0 {
|
||||
let verified = self.verify_file(&lineage.bucket, &lineage.object, &fi).await?;
|
||||
if verified.results.iter().any(|result| *result != CHECK_PART_SUCCESS) {
|
||||
return Err(DiskError::FileCorrupt);
|
||||
}
|
||||
}
|
||||
self.sim.fsync_file(&target_meta).await.map_err(map_sim_err)?;
|
||||
self.fsync_parent_chain(&target_dir).await?;
|
||||
|
||||
let (kind, snapshot) = match self.sim.stat(&source_dir).await {
|
||||
Err(SimErr::NotFound(_)) => {
|
||||
self.sync_multipart_source_absence(&source_dir).await?;
|
||||
(
|
||||
MultipartProofKind::RootMissingTerminal,
|
||||
Self::multipart_snapshot(&anchor, 0, MultipartSourcePhase::RootMissing, &anchor_raw, &target, None),
|
||||
)
|
||||
}
|
||||
Err(error) => return Err(map_sim_err(error)),
|
||||
Ok(_) => {
|
||||
match self.sim.stat(&format!("{source_dir}/{STORAGE_FORMAT_FILE}")).await {
|
||||
Err(SimErr::NotFound(_)) => {}
|
||||
Err(error) => return Err(map_sim_err(error)),
|
||||
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
|
||||
}
|
||||
let state_path = format!("{source_dir}/{DST_MULTIPART_STATE}");
|
||||
let mut raw = self.sim.read_file(&state_path).await.map_err(map_sim_err)?;
|
||||
let mut state: SimMultipartState = rmp_serde::from_slice(&raw).map_err(Error::other)?;
|
||||
if state.anchor != anchor {
|
||||
return Err(DiskError::ConditionalDeleteConflict);
|
||||
}
|
||||
if state.capability_sha256.take().is_some() {
|
||||
raw = Bytes::from(rmp_serde::to_vec_named(&state).map_err(Error::other)?);
|
||||
self.write_durable_file(&state_path, raw.clone()).await?;
|
||||
}
|
||||
(
|
||||
MultipartProofKind::TerminalTarget,
|
||||
Self::multipart_snapshot(&anchor, 2, MultipartSourcePhase::LocalTerminalSeal, &raw, &target, None),
|
||||
)
|
||||
}
|
||||
};
|
||||
MultipartSourceProof::issue(&authority, kind, challenge, None, snapshot)
|
||||
}
|
||||
|
||||
fn load_filemeta_preserving_inline(raw: &[u8]) -> Result<FileMeta> {
|
||||
let (mut fm, inline_buf) = FileMeta::load_with_borrowed_inline_data(raw)?;
|
||||
if !inline_buf.is_empty() {
|
||||
@@ -1695,7 +1428,7 @@ impl DiskAPI for DstSimDisk {
|
||||
&self,
|
||||
src_volume: &str,
|
||||
src_path: &str,
|
||||
mut file_info: FileInfo,
|
||||
file_info: FileInfo,
|
||||
dst_volume: &str,
|
||||
dst_path: &str,
|
||||
) -> Result<RenameDataResp> {
|
||||
@@ -1709,23 +1442,6 @@ impl DiskAPI for DstSimDisk {
|
||||
let bkp_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
|
||||
let src_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE}");
|
||||
|
||||
let multipart = src_volume == RUSTFS_META_MULTIPART_BUCKET;
|
||||
let _multipart_guard = if multipart {
|
||||
Some(self.multipart_publication_lock.lock().await)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let publication = if multipart { publication_identity(&file_info)? } else { None };
|
||||
let multipart_anchor = if let Some(publication) = publication {
|
||||
let anchor = self
|
||||
.prepare_multipart_anchor(&src_dir, src_path, (dst_volume, dst_path), &file_info, publication)
|
||||
.await?;
|
||||
strip_transport_condition(&mut file_info.metadata);
|
||||
Some(anchor)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let existing_raw = match self.sim.read_file(&dst_meta).await {
|
||||
Ok(b) => Some(b),
|
||||
Err(SimErr::NotFound(_)) => None,
|
||||
@@ -1768,15 +1484,20 @@ impl DiskAPI for DstSimDisk {
|
||||
self.sim.create_dir_all(&src_dir).await.map_err(map_sim_err)?;
|
||||
self.sim.create_dir_all(&dst_dir).await.map_err(map_sim_err)?;
|
||||
|
||||
let multipart_pub_identity = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
|
||||
crate::disk::multipart_source::publication_identity(&file_info)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let has_external_parts =
|
||||
!file_info.inline_data() && file_info.data.as_ref().is_none_or(|d| d.is_empty()) && file_info.size > 0;
|
||||
if has_external_parts
|
||||
&& let Some(data_dir) = file_info.data_dir
|
||||
&& !data_dir.is_nil()
|
||||
{
|
||||
let src_data_dir = multipart_anchor
|
||||
let src_data_dir = multipart_pub_identity
|
||||
.as_ref()
|
||||
.map(|anchor| anchor.publication.lineage.original_data_dir)
|
||||
.map(|p| p.lineage.original_data_dir)
|
||||
.unwrap_or(data_dir);
|
||||
let src_data = format!("{src_dir}/{src_data_dir}");
|
||||
let dst_data = format!("{dst_dir}/{data_dir}");
|
||||
@@ -1812,10 +1533,7 @@ impl DiskAPI for DstSimDisk {
|
||||
|
||||
self.check_crash_point(CrashPoint::RenameAfterBackupBeforeMetaCommit, dst_volume, dst_path)?;
|
||||
|
||||
self.sim
|
||||
.write_file(&src_meta, new_meta_bytes.clone())
|
||||
.await
|
||||
.map_err(map_sim_err)?;
|
||||
self.sim.write_file(&src_meta, new_meta_bytes).await.map_err(map_sim_err)?;
|
||||
self.sim.fsync_file(&src_meta).await.map_err(map_sim_err)?;
|
||||
self.sim.rename(&src_meta, &dst_meta).await.map_err(map_sim_err)?;
|
||||
|
||||
@@ -1827,12 +1545,50 @@ impl DiskAPI for DstSimDisk {
|
||||
let _ = self.sim.remove_dir_all(&src_dir).await;
|
||||
}
|
||||
|
||||
let multipart_source = match multipart_anchor {
|
||||
Some(anchor) => Some(Box::new(
|
||||
self.publish_multipart_witness(&src_dir, &dst_dir, anchor, &new_meta_bytes)
|
||||
.await?,
|
||||
)),
|
||||
None => None,
|
||||
let multipart_source = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
|
||||
let publication = crate::disk::multipart_source::publication_identity(&file_info)?;
|
||||
let authority = self
|
||||
.multipart_proof_authority
|
||||
.read()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.clone();
|
||||
if let (Some(publication), Some(authority)) = (publication, authority) {
|
||||
let disk_id = self
|
||||
.disk_id
|
||||
.read()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.ok_or(DiskError::InconsistentDisk)?;
|
||||
let undo_capability = crate::disk::multipart_source::MultipartUndoCapability::new();
|
||||
let snapshot = crate::disk::multipart_source::MultipartSourceSnapshot {
|
||||
disk_id,
|
||||
physical_slot: self.disk_idx,
|
||||
lineage: publication.lineage.clone(),
|
||||
generation: publication.source_generation,
|
||||
revision: 1,
|
||||
phase: crate::disk::multipart_source::MultipartSourcePhase::ConsumedUnsealed,
|
||||
state_sha256: [0; 32],
|
||||
head_sha256: None,
|
||||
inventory_sha256: [0; 32],
|
||||
capability_sha256: Some(undo_capability.digest()),
|
||||
publication: Some(publication.clone()),
|
||||
};
|
||||
let proof = crate::disk::multipart_source::MultipartSourceProof::issue(
|
||||
&authority,
|
||||
crate::disk::multipart_source::MultipartProofKind::Published,
|
||||
Uuid::new_v4(),
|
||||
None,
|
||||
snapshot,
|
||||
)?;
|
||||
Some(Box::new(crate::disk::multipart_source::MultipartPublicationResult {
|
||||
publication,
|
||||
proof,
|
||||
undo_capability,
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(RenameDataResp {
|
||||
@@ -1845,22 +1601,6 @@ impl DiskAPI for DstSimDisk {
|
||||
})
|
||||
}
|
||||
|
||||
async fn recover_multipart_source(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
|
||||
if request.protocol_version != MULTIPART_SOURCE_PROTOCOL_VERSION {
|
||||
return Err(DiskError::UnsupportedDisk);
|
||||
}
|
||||
match request.operation {
|
||||
MultipartSourceOperation::ConfirmTerminal {
|
||||
expected: None,
|
||||
publication,
|
||||
challenge,
|
||||
} => Ok(MultipartSourceResponse::TerminalConfirmed(
|
||||
self.confirm_multipart_witness(&request.path, &publication, challenge).await?,
|
||||
)),
|
||||
_ => Err(DiskError::UnsupportedDisk),
|
||||
}
|
||||
}
|
||||
|
||||
async fn list_dir(&self, _origvolume: &str, volume: &str, dir_path: &str, count: i32) -> Result<Vec<String>> {
|
||||
self.ensure_online()?;
|
||||
self.ensure_volume_exists(volume).await?;
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -379,9 +379,9 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
|
||||
CrashPoint::RenameAfterDataRename,
|
||||
CrashPoint::RenameAfterBackupBeforeMetaCommit,
|
||||
CrashPoint::RenameAfterMetaCommit,
|
||||
CrashPoint::MetaWriteAfterTmpBeforeRename,
|
||||
];
|
||||
|
||||
let mut acknowledged_overwrites = 0;
|
||||
for (seed_idx, &seed) in [0xC2A5_4001_u64, 0xC2A5_4002_u64, 0xC2A5_4003_u64, 0xC2A5_4004_u64]
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -457,13 +457,8 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
|
||||
}
|
||||
|
||||
// Attempt overwrite `v2` (may succeed at quorum if only 1 drive crashed, or fail if >=2 crashed)
|
||||
let overwrite = put_bytes(&fixture, bucket, &key, &v2).await;
|
||||
for slot in 0..affected_drives {
|
||||
assert!(
|
||||
!fixture.crash_registry.take_if_armed_on_drive(point, &key, "dst-node0", slot),
|
||||
"seed={seed:#x} key={key}: {point:?} did not fire on drive {slot}"
|
||||
);
|
||||
}
|
||||
let _overwrite_outcome = put_bytes(&fixture, bucket, &key, &v2).await;
|
||||
fixture.crash_registry.clear();
|
||||
|
||||
// Simulate simultaneous cluster-wide power outage & ALICE reboot!
|
||||
fixture.crash_and_reboot_all();
|
||||
@@ -480,19 +475,18 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
|
||||
}
|
||||
}
|
||||
|
||||
let observed = get_bytes(&fixture, bucket, &key).await.unwrap_or_else(|e| {
|
||||
panic!("committed object {key} unreadable after ALICE crash at {point:?} (seed={seed:#x}): {e:?}")
|
||||
});
|
||||
if overwrite.is_ok() {
|
||||
acknowledged_overwrites += 1;
|
||||
assert!(observed == v2, "seed={seed:#x} key={key}: acknowledged overwrite lost after {point:?}");
|
||||
} else {
|
||||
// A fault can interrupt the reply after local publication completed.
|
||||
assert!(
|
||||
observed == v1 || observed == v2,
|
||||
"seed={seed:#x} key={key}: torn overwrite after {point:?}: {overwrite:?}"
|
||||
);
|
||||
}
|
||||
// INVARIANT 2: Old-or-New-Never-Mixed! Reading `key` must return 100% bit-exact `v1`
|
||||
// OR 100% bit-exact `v2` — NEVER partial, zeroed, or mixed bytes!
|
||||
let observed = get_bytes(&fixture, bucket, &key)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("committed object {key} unreadable after ALICE crash at {point:?}: {e:?}"));
|
||||
assert!(
|
||||
observed == v1 || observed == v2,
|
||||
"atomicity violation after ALICE crash at {point:?} (seed={seed:#x}): payloadlen={} matches neither v1 ({}) nor v2 ({})",
|
||||
observed.len(),
|
||||
v1.len(),
|
||||
v2.len()
|
||||
);
|
||||
|
||||
// INVARIANT 3: Production `heal_object` converges all 4 drives back to unanimous health,
|
||||
// and previously untouched anchor objects remain 100% bit-exact!
|
||||
@@ -519,38 +513,6 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
|
||||
assert_eq!(get_bytes(&fixture, bucket, anchor_large_key).await.unwrap(), anchor_large_v1);
|
||||
}
|
||||
}
|
||||
assert!(acknowledged_overwrites > 0, "no degraded overwrite received an ACK");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_write_crash_preserves_published_metadata() {
|
||||
let fixture = make_dst_sim_set_disks(0xC2A5_4005, 4, 2, None).await.unwrap();
|
||||
let bucket = "dst-meta-crash";
|
||||
let key = "metadata.bin";
|
||||
fixture
|
||||
.set_disks
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
put_bytes(&fixture, bucket, key, b"committed").await.unwrap();
|
||||
let disk = &fixture.disks[0];
|
||||
let sim = &fixture.sim_disks[0];
|
||||
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
|
||||
let path = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}");
|
||||
let original = sim.sim().read_file(&path).await.unwrap();
|
||||
let mut next = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
|
||||
next.metadata.insert("x-amz-meta-probe".into(), "updated".into());
|
||||
let point = CrashPoint::MetaWriteAfterTmpBeforeRename;
|
||||
fixture.crash_registry.arm_on_drive(point, key, "dst-node0", 0);
|
||||
assert!(disk.write_metadata("", bucket, key, next.clone()).await.is_err());
|
||||
assert!(!fixture.crash_registry.take_if_armed_on_drive(point, key, "dst-node0", 0));
|
||||
fixture.crash_and_reboot_all();
|
||||
assert_eq!(sim.sim().read_file(&path).await.unwrap(), original);
|
||||
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), b"committed");
|
||||
disk.write_metadata("", bucket, key, next).await.unwrap();
|
||||
fixture.crash_and_reboot_all();
|
||||
let updated = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
|
||||
assert_eq!(updated.metadata.get("x-amz-meta-probe").map(String::as_str), Some("updated"));
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -940,10 +902,6 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
|
||||
// ------------------------------------------------------------------------
|
||||
let mut before_cleanup_hits = 0usize;
|
||||
for &seed in &[0x4D50_0101_u64, 0x4D50_0102_u64, 0x4D50_0103_u64, 0x4D50_0104_u64] {
|
||||
let opts = ObjectOptions {
|
||||
versioned: seed % 2 == 0,
|
||||
..dst_object_options()
|
||||
};
|
||||
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
|
||||
.await
|
||||
.expect("dst sim SetDisks for multipart pre-cleanup cutpoint");
|
||||
@@ -1001,7 +959,7 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
|
||||
let crashed = fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts.clone(), &opts)
|
||||
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
|
||||
.await;
|
||||
assert!(
|
||||
crashed.is_err(),
|
||||
@@ -1027,21 +985,6 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
|
||||
"seed={seed:#x}: committed multipart payload must be bit-exact after pre-cleanup crash"
|
||||
);
|
||||
|
||||
// A client that lost the completion response must recover the identity of
|
||||
// the existing commit, including the version ID on a versioned bucket.
|
||||
let published = fixture.set_disks.get_object_info(bucket, &key, &opts).await.unwrap();
|
||||
assert_eq!(published.version_id.is_some(), opts.versioned);
|
||||
let retried = fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
|
||||
.await
|
||||
.expect("complete retry after post-commit power loss");
|
||||
assert!(retried.multipart_completion_replayed, "seed={seed:#x}: upload committed again");
|
||||
assert_eq!(retried.version_id, published.version_id);
|
||||
assert_eq!(retried.etag, published.etag);
|
||||
assert_eq!(get_bytes(&fixture, bucket, &key).await.unwrap(), expected);
|
||||
|
||||
// Post-crash heal converges cleanly and every drive verifies both parts!
|
||||
let (_heal_item, heal_err) = fixture
|
||||
.set_disks
|
||||
@@ -1073,13 +1016,6 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
|
||||
vec![CHECK_PART_SUCCESS, CHECK_PART_SUCCESS],
|
||||
"drive {slot} must pass HighwayHash256S verification for both parts"
|
||||
);
|
||||
let raw = disk.read_all(bucket, &format!("{key}/{STORAGE_FORMAT_FILE}")).await.unwrap();
|
||||
let versions = FileMeta::load(&raw)
|
||||
.unwrap()
|
||||
.get_all_file_info_versions(bucket, &key, true)
|
||||
.unwrap();
|
||||
assert_eq!(versions.versions.len(), 1, "drive {slot}: duplicate multipart commit");
|
||||
assert_eq!(versions.versions[0].version_id, published.version_id);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
@@ -1087,77 +1023,3 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
|
||||
"fault.multipart_crashed_before_cleanup must hit across all 4 seeds"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multipart_replay_rejects_missing_or_other_disk_anchor() {
|
||||
let fixture = make_dst_sim_set_disks(0x671, 4, 2, None).await.unwrap();
|
||||
let bucket = "dst-mpu-anchor";
|
||||
let key = "published";
|
||||
let opts = dst_object_options();
|
||||
fixture
|
||||
.set_disks
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let upload = fixture.set_disks.new_multipart_upload(bucket, key, &opts).await.unwrap();
|
||||
let expected = deterministic_payload(0x671, key, 128 * 1024);
|
||||
let mut payload = PutObjReader::from_vec(expected.clone());
|
||||
let part = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, key, &upload.upload_id, 1, &mut payload, &opts)
|
||||
.await
|
||||
.unwrap();
|
||||
let parts = vec![CompletePart {
|
||||
part_num: 1,
|
||||
etag: part.etag,
|
||||
..Default::default()
|
||||
}];
|
||||
let complete = || {
|
||||
fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, key, &upload.upload_id, parts.clone(), &opts)
|
||||
};
|
||||
let published = complete().await.unwrap();
|
||||
fixture.crash_and_reboot_all();
|
||||
let replayed = complete().await.expect("all four witnesses are available");
|
||||
assert!(replayed.multipart_completion_replayed);
|
||||
assert_eq!(replayed.etag, published.etag);
|
||||
|
||||
let info = fixture.disks[0]
|
||||
.read_version("", bucket, key, "", &ReadOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let anchor =
|
||||
rustfs_ecstore::api::dst::DstSimDisk::multipart_retirement_anchor_path(bucket, key, info.data_dir.unwrap()).unwrap();
|
||||
let (parent, _) = anchor.rsplit_once('/').unwrap();
|
||||
let disks = &fixture.sim_disks;
|
||||
let own_0 = disks[0].sim().read_file(&anchor).await.unwrap();
|
||||
let own_1 = disks[1].sim().read_file(&anchor).await.unwrap();
|
||||
let foreign = disks[2].sim().read_file(&anchor).await.unwrap();
|
||||
for disk in &disks[..2] {
|
||||
disk.sim().remove_file(&anchor).await.unwrap();
|
||||
disk.sim().fsync_dir(parent).await.unwrap();
|
||||
}
|
||||
fixture.crash_and_reboot_all();
|
||||
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), expected);
|
||||
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
|
||||
|
||||
disks[0].sim().write_file(&anchor, foreign).await.unwrap();
|
||||
disks[0].sim().fsync_file(&anchor).await.unwrap();
|
||||
disks[0].sim().fsync_dir(parent).await.unwrap();
|
||||
fixture.crash_and_reboot_all();
|
||||
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
|
||||
|
||||
for (disk, own) in disks[..2].iter().zip([own_0, own_1]) {
|
||||
disk.sim().write_file(&anchor, own).await.unwrap();
|
||||
disk.sim().fsync_file(&anchor).await.unwrap();
|
||||
disk.sim().fsync_dir(parent).await.unwrap();
|
||||
}
|
||||
fixture.crash_and_reboot_all();
|
||||
let replayed = complete()
|
||||
.await
|
||||
.expect("each restored witness belongs to its own physical disk");
|
||||
assert!(replayed.multipart_completion_replayed);
|
||||
assert_eq!(replayed.etag, published.etag);
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1428,9 +1428,6 @@ impl VaultTransitKmsClient {
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
// Transit LIST also returns directory entries, including the BYOK
|
||||
// wrapping-key directory. Only actual key names belong in the cursor.
|
||||
all_keys.retain(|key| !key.ends_with('/'));
|
||||
// Vault's own LIST ordering is not part of its contract, so the sort is
|
||||
// what makes the marker a stable cursor across calls.
|
||||
all_keys.sort_unstable();
|
||||
@@ -2071,70 +2068,6 @@ mod tests {
|
||||
serde_json::to_value(&response).expect("serialize transit key read response")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_skips_byok_directories_before_pagination() {
|
||||
let listed = serde_json::json!({ "keys": ["zulu", "import/", "import", "alpha", "versions/"] });
|
||||
let metadata = metadata_read_data(&TransitKeyMetadata::from_create_request(&CreateKeyRequest::default()));
|
||||
let (vault, client) = scripted_client(vec![
|
||||
ScriptedResponse::ok(listed.clone()),
|
||||
ScriptedResponse::ok(transit_key_read_data("alpha")),
|
||||
ScriptedResponse::ok(metadata.clone()),
|
||||
ScriptedResponse::ok(transit_key_read_data("import")),
|
||||
ScriptedResponse::ok(metadata.clone()),
|
||||
ScriptedResponse::ok(listed),
|
||||
ScriptedResponse::ok(transit_key_read_data("zulu")),
|
||||
ScriptedResponse::ok(metadata),
|
||||
])
|
||||
.await;
|
||||
|
||||
let first = client
|
||||
.list_keys(
|
||||
&ListKeysRequest {
|
||||
limit: Some(2),
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("list the first page despite directory entries");
|
||||
assert_eq!(first.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["alpha", "import"]);
|
||||
assert_eq!(first.next_marker.as_deref(), Some("import"));
|
||||
assert!(first.truncated);
|
||||
assert!(first.unreadable_key_ids.is_empty());
|
||||
|
||||
let last = client
|
||||
.list_keys(
|
||||
&ListKeysRequest {
|
||||
limit: Some(2),
|
||||
marker: first.next_marker,
|
||||
..Default::default()
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("a sweep can continue past the wrapping-key directory");
|
||||
assert_eq!(last.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["zulu"]);
|
||||
assert!(last.next_marker.is_none());
|
||||
assert!(!last.truncated);
|
||||
assert!(last.unreadable_key_ids.is_empty());
|
||||
assert_eq!(vault.requests().len(), 8, "only actual keys should be described");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_with_only_the_byok_directory_is_empty() {
|
||||
let (vault, client) = scripted_client(vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/"] }))]).await;
|
||||
|
||||
let listed = client
|
||||
.list_keys(&ListKeysRequest::default(), None)
|
||||
.await
|
||||
.expect("the wrapping-key directory is not a KMS key");
|
||||
assert!(listed.keys.is_empty());
|
||||
assert!(listed.next_marker.is_none());
|
||||
assert!(!listed.truncated);
|
||||
assert!(listed.unreadable_key_ids.is_empty());
|
||||
assert_eq!(vault.requests().len(), 1, "a directory must not be described");
|
||||
}
|
||||
|
||||
/// A listing must not silently shrink when the backend is the problem.
|
||||
///
|
||||
/// Before the per-key classification this path used `?`, so any describe
|
||||
@@ -2143,7 +2076,7 @@ mod tests {
|
||||
/// about it. A transit mount that stops answering must still fail loudly.
|
||||
#[tokio::test]
|
||||
async fn list_fails_when_a_transit_key_read_is_unavailable() {
|
||||
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/", "key-a"] }))];
|
||||
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["key-a"] }))];
|
||||
for _ in 0..3 {
|
||||
responses.push(ScriptedResponse::error(503, "temporarily unavailable"));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,8 +22,6 @@ Specialized boundary, hardware and alternate-feature lanes run only on the sched
|
||||
|
||||
Workspace Clippy runs on every event with a selected workspace Rust job, pull requests included, in its own `Workspace Clippy` job. It runs beside `Workspace Lint and Build` instead of in front of it, because check-mode metadata and the linked test binaries share no compiler output; `scripts/ci_gate.py --check-workflow` rejects a workflow in which the archive producer or any archive consumer waits for the lint, or in which the lint leaves the aggregate. `Workspace Lint and Build` keeps its name as the archive producer: it creates the exact test archive and runs doctests; `Workspace tests` consumes the archive without rebuilding it. `cache-warm.yml` warms Clippy's check artifacts under `ci-dev` with the same invocation to reuse compatible dependency artifacts. `make pre-commit` does not run Clippy. Select local Clippy targets, features, and documentation exemptions from the root `AGENTS.md` verification tier; the workspace command below reproduces the CI lane and is not a universal pre-push requirement.
|
||||
|
||||
Full-scope runs also execute the production ECStore suite in `dst_production_ecstore` against simulated disks with `--features dst`. It checks the durability of acknowledged writes, metadata publication, and multipart retries with valid, missing, or misplaced per-drive evidence. The workspace producer retains the nextest listing and JUnit report and verifies that every required case passed.
|
||||
|
||||
Serial ILM tests run at the end of `workspace-tests` for the `full` scope, consuming the same verified archive as ordinary workspace tests. The existing ignored-test filter and `-j1` remain; `--profile default` keeps the no-retry execution and preserves the separate core CI JUnit report. Any ILM failure fails the consumer and required aggregate. Logs remain in the workspace test evidence artifact. There is no separate ILM compilation or cache restore.
|
||||
|
||||
`required-checks` runs even after failed or skipped dependencies. `scripts/ci_gate.py verify` rejects missing jobs, unexpected jobs, failure, cancellation, and unexpected skips; optional lanes are required only on their declared events. `Workspace Clippy` is the workspace lint, `Workspace Lint and Build` and `Workspace tests` are the ordinary Rust producer and consumer, while `Test and Lint` uniquely names the aggregate. New validation jobs must update both its direct dependencies and the script contract. A report-only lane is registered in `REPORT_ONLY_JOBS` instead: it stays out of the aggregate, must keep its distinguishing environment, and must keep the steps it reruns identical to the required job it mirrors. Test this wiring and its failure cases with `python3 scripts/ci_gate.py --self-test`.
|
||||
@@ -67,6 +65,7 @@ The four site-replication state-writer concurrency proofs reserve the available
|
||||
| PR touching `paths` in `audit.yml` | `Cargo Deny`, `Workflow Pin Report`, `Dependency Review` | `audit.yml` `cargo-deny`, `workflow-pin-report`, `dependency-review` | Report-only | `cargo deny check`; `scripts/security/check_workflow_pins.sh` |
|
||||
| PR touching `paths` in `nix.yml` | `Nix Build & Check` | `nix.yml` `nix-validation` | Report-only | `nix flake check` |
|
||||
| PR touching `paths` in `windows-filesystem.yml` | `Rename Safety`, `Startup Smoke` | `windows-filesystem.yml` `rename-safety`, `startup-smoke` | Report-only | the `cargo test -p rustfs-ecstore --lib <filter>` commands in the job, on Windows; `cargo build --locked -p rustfs --bin rustfs`, then `rustfs.exe --version` and a single-volume server polled on `/health/ready` |
|
||||
| PR or main push touching `paths` in `rdma-build.yml` | `cargo check and test compile (nixl)` | `rdma-build.yml` `nixl-build` | Report-only | `cargo check --locked -p rustfs --features nixl`; `cargo test --locked --no-run -p rustfs-nixl --features client-http` |
|
||||
| PR touching `paths` in `coverage.yml` | `Workspace line coverage` | `coverage.yml` `coverage` | Report-only | `make coverage`; `python3 scripts/check_security_coverage.py target/llvm-cov/coverage.json` |
|
||||
| PR touching `paths` in `oidc-keycloak.yml` | `OIDC Keycloak live gate` | `oidc-keycloak.yml` `oidc-keycloak-live` | Report-only | `cargo build --locked -p rustfs --bin rustfs`, then `bash scripts/test/oidc_keycloak_live.sh ./target/debug/rustfs` |
|
||||
| PR touching `paths` in `targets-integration.yml` | `PostgreSQL, MySQL, AMQP, and NATS` | `targets-integration.yml` `targets-live` | Report-only | start the containers as in the job, export the `RUSTFS_TEST_*` DSNs, then the job's `cargo test --locked -p rustfs-targets --test <name> -- --ignored --test-threads=1` commands |
|
||||
|
||||
@@ -50,6 +50,70 @@ debug = "line-tables-only"
|
||||
[profile.dev.package."*"]
|
||||
debug = false
|
||||
|
||||
# `cargo-fuzz build` compiles in release mode with `--config profile.release.debug="line-tables-only"`.
|
||||
# Keep third-party dependencies (DataFusion, Arrow, Parquet, AWS SDK) at opt-level 1 without DWARF
|
||||
# debuginfo so instrumented builds stay within the runner memory and artifact budgets, while
|
||||
# preserving full optimization and line tables for the fuzz crate and RustFS workspace crates.
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package."*"]
|
||||
opt-level = 1
|
||||
debug = false
|
||||
|
||||
[profile.release.package.rustfs-ecstore]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-filemeta]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-kms]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-lifecycle]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-notify]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-policy]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-rio]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-s3select-api]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-s3select-query]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-security-governance]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-signer]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-sse]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[profile.release.package.rustfs-utils]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
|
||||
[[bin]]
|
||||
name = "bucket_validation"
|
||||
path = "fuzz_targets/bucket_validation.rs"
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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}"),
|
||||
|
||||
@@ -2383,6 +2383,7 @@ mod tests {
|
||||
#[serial_test::serial]
|
||||
async fn http3_certificate_reload_updates_handshakes_and_retains_valid_config() {
|
||||
use crate::server::http3::tests::{client_endpoint, connect};
|
||||
ensure_rustls_crypto_provider();
|
||||
let dir = TempDir::new().expect("TLS directory");
|
||||
write_test_cert_pair(dir.path(), "localhost");
|
||||
let snapshot = load_tls_material(dir.path().to_str().expect("TLS path"))
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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={}]",
|
||||
|
||||
@@ -24,16 +24,6 @@ CORE_TESTS = {
|
||||
"head_object_consistency_test::head_object_consistency_after_write_and_multipart_and_presigned_head",
|
||||
"storage_class_capability_test::tests::historical_label_only_metadata_is_standard_without_hiding_a_real_transition_tier",
|
||||
}
|
||||
DST_SUITE = "rustfs-ecstore::dst_production_ecstore"
|
||||
DST_TESTS = {
|
||||
"dst_prod_test1_quorum_put_get_delete_offline_and_enospc",
|
||||
"dst_prod_test2_physical_bitrot_highwayhash_detect_reconstruct_and_heal",
|
||||
"dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixed",
|
||||
"metadata_write_crash_preserves_published_metadata",
|
||||
"dst_prod_test4_deterministic_multiseed_concurrent_chaos_and_replay_equivalence",
|
||||
"dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_before_cleanup",
|
||||
"multipart_replay_rejects_missing_or_other_disk_anchor",
|
||||
}
|
||||
|
||||
|
||||
def output(*args):
|
||||
@@ -161,16 +151,12 @@ def selected_tests(listing):
|
||||
return selected
|
||||
|
||||
|
||||
def verify_execution(listing, junit, core=False, dst=False):
|
||||
def verify_execution(listing, junit, core=False):
|
||||
inventory = json.loads(Path(listing).read_text())
|
||||
expected = selected_tests(inventory)
|
||||
known = {(binary, name) for binary, suite in inventory["rust-suites"].items() for name in suite["testcases"]}
|
||||
if core and (len(expected) != len(CORE_TESTS) or {name for _, name in expected} != CORE_TESTS):
|
||||
raise ValueError("core contract must select exactly the write/read, denial and restart proofs")
|
||||
if dst:
|
||||
missing = {(DST_SUITE, name) for name in DST_TESTS} - expected
|
||||
if missing:
|
||||
raise ValueError(f"missing production DST tests: {sorted(missing)}")
|
||||
report = ET.parse(junit).getroot()
|
||||
if report.tag != "testsuites" or report.get("failures") != "0" or report.get("errors") != "0":
|
||||
raise ValueError("test report must be a successful nextest run")
|
||||
@@ -215,9 +201,7 @@ def main():
|
||||
child = sub.add_parser("evidence")
|
||||
child.add_argument("listing", type=Path)
|
||||
child.add_argument("junit", type=Path)
|
||||
required = child.add_mutually_exclusive_group()
|
||||
required.add_argument("--core", action="store_true")
|
||||
required.add_argument("--dst", action="store_true")
|
||||
child.add_argument("--core", action="store_true")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command == "build":
|
||||
@@ -237,7 +221,7 @@ def main():
|
||||
"doc": [*selection, "--doc"], "warm": ["--no-run", *selection]}[args.operation]
|
||||
subprocess.run(command, cwd=ROOT, check=True)
|
||||
else:
|
||||
print(f"Verified {verify_execution(args.listing, args.junit, args.core, args.dst)} test executions")
|
||||
print(f"Verified {verify_execution(args.listing, args.junit, args.core)} test executions")
|
||||
except (OSError, ValueError, KeyError, TypeError, ET.ParseError, subprocess.CalledProcessError) as error:
|
||||
print(f"verification artifact: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
+21
-4
@@ -31,6 +31,7 @@
|
||||
# SKIP_BUILD — set to 1 to skip build phase (default: 0)
|
||||
# USE_PREBUILT_BINARY — set to 1 to run a prebuilt fuzz binary directly
|
||||
# PREBUILT_BINARY_DIR — directory containing prebuilt fuzz binaries
|
||||
# FUZZ_CODEGEN_UNITS — optional positive integer passed as --codegen-units to cargo-fuzz
|
||||
|
||||
set -eu
|
||||
|
||||
@@ -45,6 +46,7 @@ BUILD_ONLY=${BUILD_ONLY:-0}
|
||||
SKIP_BUILD=${SKIP_BUILD:-0}
|
||||
USE_PREBUILT_BINARY=${USE_PREBUILT_BINARY:-0}
|
||||
PREBUILT_BINARY_DIR=${PREBUILT_BINARY_DIR:-}
|
||||
FUZZ_CODEGEN_UNITS=${FUZZ_CODEGEN_UNITS:-}
|
||||
|
||||
case "$MAX_TOTAL_TIME" in
|
||||
''|0*|*[!0-9]*)
|
||||
@@ -62,6 +64,15 @@ if [ -n "$FUZZ_SEED" ]; then
|
||||
esac
|
||||
fi
|
||||
|
||||
if [ -n "$FUZZ_CODEGEN_UNITS" ]; then
|
||||
case "$FUZZ_CODEGEN_UNITS" in
|
||||
0*|*[!0-9]*)
|
||||
echo "FUZZ_CODEGEN_UNITS must be a positive decimal integer without leading zeroes: $FUZZ_CODEGEN_UNITS" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
cd "$FUZZ_DIR"
|
||||
mkdir -p "$ARTIFACT_ROOT"
|
||||
|
||||
@@ -126,7 +137,10 @@ PY
|
||||
if [ "$SKIP_BUILD" != "1" ]; then
|
||||
set --
|
||||
if [ -n "${CARGO_TARGET_DIR:-}" ]; then
|
||||
set -- --target-dir "$CARGO_TARGET_DIR"
|
||||
set -- "$@" --target-dir "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
if [ -n "$FUZZ_CODEGEN_UNITS" ]; then
|
||||
set -- "$@" --codegen-units "$FUZZ_CODEGEN_UNITS"
|
||||
fi
|
||||
if [ "$targets" = "$registered_targets" ]; then
|
||||
# A single Cargo invocation shares the instrumented dependency build across all harnesses.
|
||||
@@ -208,11 +222,14 @@ for target in $targets; do
|
||||
else
|
||||
echo "==> cargo +nightly fuzz run $target (-max_total_time=$MAX_TOTAL_TIME, -seed=$seed, -artifact_prefix=$artifact_dir/)"
|
||||
set +e
|
||||
set --
|
||||
if [ -n "${CARGO_TARGET_DIR:-}" ]; then
|
||||
cargo +nightly fuzz run --target-dir "$CARGO_TARGET_DIR" "$target" -- -max_total_time="$MAX_TOTAL_TIME" -seed="$seed" -artifact_prefix="$artifact_dir/"
|
||||
else
|
||||
cargo +nightly fuzz run "$target" -- -max_total_time="$MAX_TOTAL_TIME" -seed="$seed" -artifact_prefix="$artifact_dir/"
|
||||
set -- "$@" --target-dir "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
if [ -n "$FUZZ_CODEGEN_UNITS" ]; then
|
||||
set -- "$@" --codegen-units "$FUZZ_CODEGEN_UNITS"
|
||||
fi
|
||||
cargo +nightly fuzz run "$@" "$target" -- -max_total_time="$MAX_TOTAL_TIME" -seed="$seed" -artifact_prefix="$artifact_dir/"
|
||||
exit_code=$?
|
||||
set -e
|
||||
fi
|
||||
|
||||
@@ -244,10 +244,10 @@ class ExecutionEvidenceTests(unittest.TestCase):
|
||||
self.listing = listing([("crate-a", "one", False), ("crate-b", "two", False), ("crate-b", "ignored", True)])
|
||||
self.report = junit([("crate-a", "one", None), ("crate-b", "two", None)])
|
||||
|
||||
def verify(self, listing_value=None, report=None, *, core=False, dst=False):
|
||||
def verify(self, listing_value=None, report=None, *, core=False):
|
||||
self.listing_file.write_text(json.dumps(self.listing if listing_value is None else listing_value))
|
||||
ET.ElementTree(self.report if report is None else report).write(self.junit_file)
|
||||
return artifact.verify_execution(self.listing_file, self.junit_file, core=core, dst=dst)
|
||||
return artifact.verify_execution(self.listing_file, self.junit_file, core=core)
|
||||
|
||||
def test_exact_selected_set_and_known_ignored_cases(self):
|
||||
self.assertEqual(self.verify(), 2)
|
||||
@@ -321,17 +321,6 @@ class ExecutionEvidenceTests(unittest.TestCase):
|
||||
with self.subTest(attribute=attribute), self.assertRaises(ValueError):
|
||||
self.verify(report=report)
|
||||
|
||||
def test_dst_rejects_a_green_report_with_a_missing_required_test(self):
|
||||
cases = [(artifact.DST_SUITE, name) for name in sorted(artifact.DST_TESTS)]
|
||||
for selected in [cases, cases[:-1]]:
|
||||
inventory = listing([(suite, name, False) for suite, name in selected])
|
||||
report = junit([(suite, name, None) for suite, name in selected])
|
||||
if selected == cases:
|
||||
self.assertEqual(self.verify(inventory, report, dst=True), len(cases))
|
||||
else:
|
||||
with self.assertRaisesRegex(ValueError, "missing production DST tests"):
|
||||
self.verify(inventory, report, dst=True)
|
||||
|
||||
def test_core_requires_exactly_three_selected_proofs(self):
|
||||
names = sorted(artifact.CORE_TESTS)
|
||||
core_listing = listing([("e2e", name, False) for name in names])
|
||||
|
||||
@@ -140,4 +140,25 @@ for invalid_target in nonexistent "path_containment;id"; do
|
||||
fi
|
||||
done
|
||||
|
||||
PATH="$TMP_ROOT/bin:$PATH" \
|
||||
FAKE_CARGO_ARGS_FILE="$TMP_ROOT/build-cgu-args" \
|
||||
FUZZ_TARGET=path_containment \
|
||||
FUZZ_CODEGEN_UNITS=16 \
|
||||
BUILD_ONLY=1 \
|
||||
"$REPO_ROOT/scripts/fuzz/run.sh"
|
||||
|
||||
grep -Fx '+nightly' "$TMP_ROOT/build-cgu-args"
|
||||
grep -Fx 'fuzz' "$TMP_ROOT/build-cgu-args"
|
||||
grep -Fx 'build' "$TMP_ROOT/build-cgu-args"
|
||||
grep -Fx -- '--codegen-units' "$TMP_ROOT/build-cgu-args"
|
||||
grep -Fx '16' "$TMP_ROOT/build-cgu-args"
|
||||
grep -Fx 'path_containment' "$TMP_ROOT/build-cgu-args"
|
||||
|
||||
for invalid_cgu in 0 016 not-a-number "16;id"; do
|
||||
if FUZZ_TARGET=path_containment FUZZ_CODEGEN_UNITS="$invalid_cgu" BUILD_ONLY=1 "$REPO_ROOT/scripts/fuzz/run.sh" >/dev/null 2>&1; then
|
||||
echo "invalid FUZZ_CODEGEN_UNITS was accepted: $invalid_cgu" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "fuzz runner seed manifest tests passed"
|
||||
|
||||
Reference in New Issue
Block a user