Compare commits

...

10 Commits

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

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

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

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

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

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

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

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

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

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

---------

Signed-off-by: RustFS <hello@rustfs.com>
2026-12-02 20:53:48 +08:00
Chris An d8e2353825 fix(ci): prevent fuzz build OOM and stabilize workspace/http3 tests (#9856)
* fix(ci): prevent fuzz build OOM and stabilize workspace/http3 tests

* fix(fuzz): split fuzz build codegen units and bound dep opt-level/lld threads
2026-12-02 19:48:58 +08:00
hector c3fb1aa4a0 ci: compile the nixl feature only on RDMA path changes (#9851)
* ci: compile the nixl feature only on RDMA path changes

Add a path-filtered workflow so the optional nixl build runs on pull
requests and main pushes that touch NIXL/RDMA sources, and on manual
dispatch. It reads the hosted Rust cache and does not save it.

Co-authored-by: hector <majinghe@users.noreply.github.com>

* ci: run the nixl compile check on the rdma runner

Use the bare self-hosted label and a cache key that is not shared with
the ubuntu-latest lanes.

Co-authored-by: hector <majinghe@users.noreply.github.com>

* ci: register the path-filtered nixl compile workflow

Record the event-driven workflow in the validation registry and match
future nixl RPC modules with the same path glob as the feature check.

Co-authored-by: hector <majinghe@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: hector <majinghe@users.noreply.github.com>
2026-12-02 19:48:51 +08:00
Rasmus Haslund 615e55825e fix(s3): echo multipart checksums in ListParts (#9814)
Carry the upload's checksum algorithm and type and each part's recorded checksums through PartInfo and render them in the ListParts response.
2026-12-02 16:08:17 +08:00
Hauser Zhi 2537596a4f chore(deps): refresh Cargo dependencies (#9842)
* chore(deps): refresh Cargo dependencies

Update TAR and Windows bindings, preserve Windows file disposition flags, and retain the recorder version shared with Kafka and Gateway RDMA. Refresh the standalone fuzz dependency graph.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* chore(deps): upgrade metrics to 0.25

Route metrics 0.24 consumers through the 0.25 implementation in both workspaces. Verify that legacy metrics share the recorder and that dependency resolution cannot silently restore a second recorder.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* chore(deps): update RustFS Kafka to 1.5.0

Resolve both Kafka packages at 1.5.0 and drop the unused metrics facade patch from the fuzz workspace. Keep the main workspace facade for the remaining Metrique dependency.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(metrics): disambiguate the doctest extern names

Alias the 0.25 implementation so rustdoc can link it alongside the 0.24 compatibility facade. Preserve the shared recorder and dependency lockfile.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* chore(deps): update http to 1.6.0

Align the workspace and standalone fuzz manifests and lockfiles on http 1.6.0.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(deps): refresh Cargo dependencies and preserve HTTP values

Refresh registry constraints and lockfiles. Preserve legacy opaque ETags and response headers with byte validation while retaining POST and signed override validation.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:38 +08:00
Hauser Zhi 6b014ec215 feat(capacity): read usage directly on dedicated mounts (#9840)
* feat(capacity): read usage directly on dedicated mounts

Allow operators of dedicated filesystems to use block usage for background
capacity estimates. Reuse the existing blocking scan and cache update
paths so a successful probe establishes the per-disk baseline.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* refactor(capacity): verify whole mounts before reading usage

Share mount eligibility across a refresh and read allocated blocks
through the checked directory descriptor. Rebuild a complete per-disk
baseline when the local disk set changes.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(capacity): discard stale topology on bounded refresh

Reconcile a scheduled full refresh against the topology it scanned.
Represent baseline completeness with the per-disk map and compute
aggregate totals in one pass.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(capacity): restrict direct reads to isolated filesystem types

Use the filesystem type from the existing descriptor-based statfs
call to keep shared-pool accounting out of the direct mount path.
Cover directory fallback and symlinked mount roots.

Refs: rustfs/rustfs#9837

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:30 +08:00
Hauser Zhi a368c669a2 feat(bench): record write latency in preflight queue samples (#9850)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:24 +08:00
hector e0b548fff0 fix(docker): switch docker-compose-simple.yml to single-disk mode and /health/ready (#9848)
* fix(docker): switch docker-compose-simple.yml to single-disk mode and /health/ready

- Use single-node single-disk layout (RUSTFS_VOLUMES=/data with a single rustfs_data volume) so docker compose up works out of the box without triggering same-device strict disk topology errors
- Switch healthcheck to /health/ready on port 9000 with --connect-timeout 3 --max-time 5 (decoupled from console toggle)
- Pin volume-permission-helper to alpine:3.24 with network_mode: none and skip redundant recursive chown -R when ownership is already 10001:10001
- Allow overriding S3/Console host ports and credentials via env vars, and configure ulimits.nofile=65535

Signed-off-by: xiaomage <jhma@rustfs.com>

* fix(docker): align RUSTFS_OBS_LOG_DIRECTORY to /logs in docker-compose-simple.yml

Signed-off-by: xiaomage <jhma@rustfs.com>

---------

Signed-off-by: xiaomage <jhma@rustfs.com>
2026-12-02 11:21:56 +08:00
71 changed files with 3258 additions and 826 deletions
+15
View File
@@ -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"
+1
View File
@@ -7,3 +7,4 @@ self-hosted-runner:
- dind-sm-standard-2
- smoke-testing
- pf-testing
- rdma
+23
View File
@@ -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",
+1 -1
View File
@@ -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.
+3 -1
View File
@@ -404,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:
+8 -2
View File
@@ -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
+139
View File
@@ -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
View File
@@ -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:
Generated
+415 -222
View File
File diff suppressed because it is too large Load Diff
+17 -15
View File
@@ -40,6 +40,7 @@ members = [
"crates/lock", # Distributed locking implementation
"crates/log-analyzer", # Offline log fault-analysis core (rustfs diagnose)
"crates/madmin", # Management dashboard and admin API interface
"crates/metrics-compat", # Shared recorder for dependencies requiring metrics 0.24
"crates/notify", # Notification system for events
"crates/obs", # Observability utilities
"crates/object-capacity", # Capacity scan and refresh core
@@ -192,13 +193,13 @@ hyper = { version = "=1.12.0" } # Keep the HTTP/2 Expect backport below active.
h2 = { version = "0.4.21" }
hyper-rustls = { default-features = false, version = "0.27.10" }
hyper-util = { version = "0.1.21" }
http = "1.5.0"
http = "1.6.0"
http-body = "1.1.0"
http-body-util = "0.1.5"
memchr = "2.8.3"
minlz = "1.2.3"
reqwest = "0.13.5"
rustfs-kafka-async = { version = "1.4.1" }
rustfs-kafka-async = { version = "1.5.0" }
slab = { version = "0.4.12" }
socket2 = { version = "0.6.5" }
tokio = { version = "1.54.1" }
@@ -224,7 +225,7 @@ apache-avro = { version = "0.23.0", features = ["snappy", "zstandard"] }
bytes = { version = "1.12.2" }
csv-core = "0.1.13"
bytesize = "2.7.0"
byteorder = "1.5.0"
byteorder = "1.5.1"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.3"
prost = "0.14.6"
@@ -269,7 +270,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.0.3" }
jiff = { version = "1.1.0" }
time = { version = "0.3.55" }
# Database
@@ -282,15 +283,15 @@ anyhow = "1.0.105"
arc-swap = "1.9.5"
rustfs-tokio-tar = { version = "0.7.1" }
# Candidate Snowball parser versions exercised by rustfs-zip compatibility fixtures.
tar-codec = "0.0.17"
tar-framing = "0.0.17"
tar-codec = "0.0.18"
tar-framing = "0.0.18"
atoi = "3.1.1"
atomic_enum = "0.3.0"
aws-config = { version = "1.13.4" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.134.0" }
aws-sdk-s3 = { default-features = false, version = "1.163.0" }
aws-sdk-sts = { default-features = false, version = "1.129.0" }
aws-sdk-sts = { default-features = false, version = "1.130.0" }
aws-sdk-s3vectors = { default-features = false, version = "=1.52.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
@@ -357,7 +358,7 @@ percent-encoding = "2.3.2"
# Server-side QR rendering for TOTP enrollment, so neither the console nor the
# CLI needs its own QR encoder. No default features: the image/render backends
# pull in an image stack this only needs SVG and text output from.
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
qrcode-rs = { version = "2.2.1", default-features = false, features = ["std", "svg"] }
pin-project-lite = "0.2.18"
pretty_assertions = "1.4.1"
rand = { version = "0.10.4" }
@@ -378,7 +379,7 @@ siphasher = "1.0.4"
smallvec = { version = "1.16.6" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.1" }
starshard = { version = "2.4.2" }
strum = { version = "0.28.0" }
sync_wrapper = "1.0.2"
sysinfo = "0.40.5"
@@ -400,15 +401,15 @@ vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.1"
winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
windows = { version = "0.101.0" }
windows-sys = "0.101.0"
xxhash-rust = { version = "0.8.21" }
zip = "9.9.0"
zstd = "0.14.5"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
metrics = "0.25.1"
metrics-util = "0.21"
dial9 = { version = "0.5.9", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
@@ -416,7 +417,7 @@ opentelemetry-otlp = { version = "0.33.1" }
opentelemetry-proto = { version = "0.33.1", default-features = false, features = ["metrics", "gen-tonic-messages"] }
opentelemetry_sdk = { version = "0.33.1" }
opentelemetry-semantic-conventions = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.2" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
@@ -431,7 +432,7 @@ russh-sftp = "4.0.0"
dav-server = "0.12.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.5" }
rustfs-mimalloc = { version = "0.7.6" }
# Hotpath 0.33 infers type-qualified names for methods without explicit labels or impl_type.
hotpath = { version = "=0.33.1", default-features = false }
# Snapshot testing for output format regression detection
@@ -483,6 +484,7 @@ strip = "none"
# Pin upstream fixes until compatible crates.io releases are available.
[patch.crates-io]
metrics = { path = "crates/metrics-compat" }
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
hyper = { path = "vendor/hyper" }
lance-bitpacking = { git = "https://github.com/GatewayJ/lance", rev = "35a95d99a1f413d9cad0427837ee6939974a1570" }
+6
View File
@@ -45,6 +45,9 @@ pub const ENV_CAPACITY_METRICS_INTERVAL: &str = "RUSTFS_CAPACITY_METRICS_INTERVA
/// Environment variable for following symbolic links during capacity calculation
pub const ENV_CAPACITY_FOLLOW_SYMLINKS: &str = "RUSTFS_CAPACITY_FOLLOW_SYMLINKS";
/// Use filesystem-reported used space on dedicated drive mounts.
pub const ENV_CAPACITY_USE_MOUNT_USAGE: &str = "RUSTFS_CAPACITY_USE_MOUNT_USAGE";
/// Environment variable for enabling dynamic timeout calculation
pub const ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: &str = "RUSTFS_CAPACITY_ENABLE_DYNAMIC_TIMEOUT";
@@ -94,6 +97,9 @@ pub const DEFAULT_CAPACITY_METRICS_INTERVAL_SECS: u64 = 600;
/// Default: false (disabled for safety)
pub const DEFAULT_CAPACITY_FOLLOW_SYMLINKS: bool = false;
/// Use directory scans by default to preserve logical file-size accounting.
pub const DEFAULT_CAPACITY_USE_MOUNT_USAGE: bool = false;
/// Enable dynamic timeout calculation based on directory characteristics
/// Default: true (enabled)
pub const DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: bool = true;
+18 -18
View File
@@ -71,15 +71,15 @@ const _: () = assert!(DEFAULT_INTERNODE_RPC_TCP_NODELAY);
/// unary responses such as `ReadMultiple` and `BatchReadVersion`. Set to 0 to use the
/// `tonic`/`hyper` default. Defaults to 1MiB.
pub const ENV_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024;
/// HTTP/2 initial connection window size (bytes) for internode gRPC client channels.
///
/// Should be >= the stream window so multiple concurrent streams are not starved by the
/// connection-level flow-control window. Set to 0 to fall back to the library default.
/// Defaults to 2MiB.
/// Defaults to 16MiB.
pub const ENV_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE";
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 2 * 1024 * 1024;
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
// Compile-time invariant: the connection-level window must be >= the per-stream window, or
// concurrent streams would be starved by the connection-level flow-control budget.
@@ -284,23 +284,23 @@ pub const DEFAULT_INTERNODE_IDEMPOTENT_READ_RETRIES: usize = 1;
/// Enable control/bulk internode gRPC channel isolation.
///
/// Defaults to `false`: this touches lock-RPC transport routing (consistency-sensitive), so it
/// is opt-in and validated against a baseline before rollout. When `false`, bulk RPCs reuse the
/// control channel exactly as before, so the switch is a single-env rollback.
/// Defaults to `true` so bulk `ReadAll`/`WriteAll`/`ReadMultiple`/`BatchReadVersion` transfers
/// use dedicated bulk HTTP/2 channels instead of head-of-line blocking latency-sensitive
/// `Lock`/`UnLock`/`Refresh`/`DiskInfo` control RPCs under high concurrency. Set
/// `RUSTFS_INTERNODE_CHANNEL_ISOLATION=false` for single-env rollback to legacy shared-channel behavior.
pub const ENV_INTERNODE_CHANNEL_ISOLATION: &str = "RUSTFS_INTERNODE_CHANNEL_ISOLATION";
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = false;
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = true;
// Compile-time invariant: isolation is opt-in so the default build behaves exactly as before P1.
const _: () = assert!(!DEFAULT_INTERNODE_CHANNEL_ISOLATION);
// Compile-time invariant: channel isolation defaults on so bulk data RPCs cannot starve lock/quorum RPCs.
const _: () = assert!(DEFAULT_INTERNODE_CHANNEL_ISOLATION);
/// Number of bulk channels maintained per peer when channel isolation is enabled.
///
/// A tonic `Channel` is a single TCP/HTTP2 connection; multiple bulk channels are round-robined
/// to relieve the single-connection throughput ceiling for large transfers. Kept small (default
/// 2) to avoid a connection storm; clamped to at least 1. Set to 1 to isolate bulk onto a single
/// dedicated connection (still separate from control).
/// to relieve the single-connection throughput ceiling for large transfers. Defaults to 4 (matching
/// typical 4-drive-per-node stripes); clamped to at least 1.
pub const ENV_INTERNODE_BULK_CHANNELS: &str = "RUSTFS_INTERNODE_BULK_CHANNELS";
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 2;
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 4;
/// Optional receive-window overrides for isolated bulk channels. When unset, inherit the
/// corresponding `RUSTFS_INTERNODE_RPC_HTTP2_*` setting. Zero selects the library default.
@@ -310,7 +310,7 @@ pub const ENV_INTERNODE_BULK_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_BU
/// Transport admission and pending-buffer limits for isolated bulk channels. These limits
/// apply to the tonic service; complete unary bodies are observed separately by RPC metrics.
pub const ENV_INTERNODE_BULK_CONCURRENCY_LIMIT: &str = "RUSTFS_INTERNODE_BULK_CONCURRENCY_LIMIT";
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 64;
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 128;
pub const ENV_INTERNODE_BULK_BUFFER_SIZE: &str = "RUSTFS_INTERNODE_BULK_BUFFER_SIZE";
pub const DEFAULT_INTERNODE_BULK_BUFFER_SIZE: usize = 1024;
@@ -501,8 +501,8 @@ mod tests {
#[test]
fn internode_rpc_channel_tuning_defaults() {
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 2 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 4 * 1024 * 1024);
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 16 * 1024 * 1024);
// The nodelay-on and connection-window >= stream-window invariants are enforced at
// compile time next to the constant definitions.
}
@@ -525,8 +525,8 @@ mod tests {
#[test]
fn internode_channel_isolation_defaults_and_env_names() {
// The isolation-off default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 2);
// The isolation-on default is asserted at compile time next to the constant definition.
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 4);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, 0);
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_WAIT_TIMEOUT_MS, 1_000);
assert_eq!(ENV_INTERNODE_CHANNEL_ISOLATION, "RUSTFS_INTERNODE_CHANNEL_ISOLATION");
+1 -1
View File
@@ -482,7 +482,7 @@ pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MIN_SIZE_BYTES: usize = 0;
/// A short wait smooths transient bursts while still returning S3
/// `SlowDown`/503 before body ingest when the node is already saturated.
pub const ENV_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = "RUSTFS_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS";
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250;
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 2_000;
/// Time in milliseconds a multipart UploadPart waits for a foreground write permit.
///
+10 -2
View File
@@ -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!(
+181 -27
View File
@@ -1484,6 +1484,33 @@ static HOST_TIMEOUT_DEGRADATION: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, HostTimeoutDegradationState>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
static HOST_RPC_PROGRESS: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, Arc<std::sync::atomic::AtomicU64>>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
fn host_progress_counter(addr: &str) -> Arc<std::sync::atomic::AtomicU64> {
let mut map = HOST_RPC_PROGRESS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(counter) = map.get(addr) {
return Arc::clone(counter);
}
let counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
map.insert(addr.to_owned(), Arc::clone(&counter));
counter
}
pub(crate) fn host_completed_ops(addr: &str) -> u64 {
let Ok(map) = HOST_RPC_PROGRESS.lock() else {
return 0;
};
map.get(addr)
.map_or(0, |counter| counter.load(std::sync::atomic::Ordering::Acquire))
}
fn record_host_rpc_success(addr: &str) {
host_progress_counter(addr).fetch_add(1, std::sync::atomic::Ordering::AcqRel);
clear_host_timeout_degradation(addr);
}
fn record_host_disk_timeout(addr: &str, endpoint: &str) {
let now = tokio::time::Instant::now();
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
@@ -2506,10 +2533,17 @@ impl RemoteDisk {
/// same host to time out within the correlation window, so a single slow HDD
/// never engages host-level fast-fail while a `SIGSTOP`'d peer holding 4
/// drives fast-fails immediately on subsequent requests.
pub(crate) fn record_straggler_timeout(&self) {
pub(crate) fn record_straggler_timeout_if_stalled(&self, host_completed_before: u64) {
if host_completed_ops(&self.addr) > host_completed_before {
return;
}
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
}
pub(crate) fn host_completed_ops(&self) -> u64 {
host_completed_ops(&self.addr)
}
/// On-demand bounded recovery probe used only when a read is about to fail read quorum due to
/// `FaultyDisk` remote drives (e.g., drives waiting in `Returning` right after a rolling restart).
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
@@ -2520,7 +2554,7 @@ impl RemoteDisk {
else {
return false;
};
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
rustfs_io_metrics::internode_metrics::record_peer_reachable(&self.addr);
self.health
.mark_peer_restarted_online(&self.endpoint, "on_demand_quorum_recovery_probe_success")
@@ -2623,6 +2657,7 @@ impl RemoteDisk {
.unwrap_or_else(|| time::sleep(timeout_duration).deadline())
});
let max_retries = internode_idempotent_read_retries();
let drive_completed_before = self.health.completed_ops();
let mut attempt = 0usize;
loop {
let attempt_timeout = deadline
@@ -2647,7 +2682,9 @@ impl RemoteDisk {
return Err(err);
}
if matches!(err, DiskError::Timeout) && deadline.is_some_and(|deadline| time::Instant::now() >= deadline) {
self.mark_faulty("read_operation_deadline");
if self.health.completed_ops() == drive_completed_before {
self.mark_faulty("read_operation_deadline");
}
return Err(err);
}
attempt += 1;
@@ -2739,37 +2776,61 @@ impl RemoteDisk {
let _waiting_guard = self.health.waiting_guard();
if timeout_duration == Duration::ZERO {
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let operation_result = operation().await;
if operation_result.is_ok() {
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
return operation_result;
}
// Execute operation with timeout
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
let result = time::timeout(timeout_duration, operation()).await;
match result {
Ok(operation_result) => {
// Log success; the waiting guard balances every exit path.
if operation_result.is_ok() {
clear_host_timeout_degradation(&self.addr);
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
failure_health_action,
drive_stalled,
host_stalled,
)
.await;
operation_result
}
Err(_) => {
self.record_timeout(op, timeout_duration);
if failure_health_action == FailureHealthAction::MarkFailure {
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
self.mark_faulty_and_evict("operation_timeout").await;
self.mark_faulty_with_eviction("operation_timeout", host_stalled).await;
}
Err(DiskError::Timeout)
}
@@ -2790,17 +2851,32 @@ impl RemoteDisk {
self.record_timeout(op, timeout_duration);
return Err(DiskError::Timeout);
}
let drive_completed_before = self.health.completed_ops();
let host_completed_before = host_completed_ops(&self.addr);
match time::timeout(timeout_duration, operation()).await {
Ok(operation_result) => {
if operation_result.is_ok() {
record_host_rpc_success(&self.addr);
self.health.record_operation_success(&self.endpoint, "operation_success");
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
}
let evict = operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(op, timeout_duration, &operation_result, FailureHealthAction::IgnoreFailure)
.await;
let drive_stalled = self.health.completed_ops() == drive_completed_before;
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
let evict = drive_stalled
&& host_stalled
&& operation_result
.as_ref()
.err()
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
self.handle_network_like_error(
op,
timeout_duration,
&operation_result,
FailureHealthAction::IgnoreFailure,
drive_stalled,
host_stalled,
)
.await;
if evict {
evict_failed_connection_with_reason(
&self.addr,
@@ -2813,12 +2889,16 @@ impl RemoteDisk {
}
Err(_) => {
self.record_timeout(op, timeout_duration);
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
if self.health.completed_ops() == drive_completed_before
&& host_completed_ops(&self.addr) == host_completed_before
{
evict_failed_connection_with_reason(
&self.addr,
ChannelRebuildReason::OperationTimeout,
ConnectionEvictionLogLevel::Debug,
)
.await;
}
Err(DiskError::Timeout)
}
}
@@ -2853,6 +2933,8 @@ impl RemoteDisk {
timeout_duration: Duration,
operation_result: &Result<T>,
failure_health_action: FailureHealthAction,
drive_stalled: bool,
host_stalled: bool,
) {
if let Err(err) = operation_result
&& !err.is_metacache_output_stream_closed()
@@ -2878,8 +2960,8 @@ impl RemoteDisk {
"Remote disk operation returned network-like error"
);
}
if failure_health_action == FailureHealthAction::MarkFailure {
self.mark_faulty_and_evict("operation_network_error").await;
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
self.mark_faulty_with_eviction("operation_network_error", host_stalled).await;
}
}
}
@@ -2925,8 +3007,8 @@ impl RemoteDisk {
state != previous_state
}
async fn mark_faulty_and_evict(&self, reason: &'static str) {
if self.mark_faulty(reason) {
async fn mark_faulty_with_eviction(&self, reason: &'static str, evict_connection: bool) {
if self.mark_faulty(reason) && evict_connection {
counter!(
"rustfs_drive_connection_evict_total",
"endpoint" => self.endpoint.to_string(),
@@ -15034,4 +15116,76 @@ mod tests {
"host degradation must clear immediately after a successful RPC"
);
}
#[tokio::test]
async fn sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault() {
async fn make_drive(port: u16, disk_idx: i32) -> RemoteDisk {
let url = url::Url::parse(&format!("http://127.0.0.1:{port}/data{disk_idx}")).expect("endpoint url");
let endpoint = Endpoint {
url,
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx,
};
RemoteDisk::new(
&endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
Arc::new(TcpHttpInternodeDataTransport),
)
.await
.expect("remote disk handle")
}
let stalled_drive = make_drive(59985, 0).await;
let sibling_drive = make_drive(59985, 1).await;
let addr = stalled_drive.addr.clone();
clear_host_timeout_degradation(&addr);
let dummy_channel = tonic::transport::Endpoint::from_static("http://127.0.0.1:59985").connect_lazy();
rustfs_common::cache_connection(addr.clone(), dummy_channel).await;
assert!(rustfs_common::has_cached_connection(&addr).await);
// Start a slow operation on `stalled_drive` while `sibling_drive` on the same host
// completes an RPC before `stalled_drive` times out.
let sibling_ref = &sibling_drive;
let err = stalled_drive
.execute_with_timeout_for_op_and_health_action(
"write_all",
|| async move {
sibling_ref
.execute_with_timeout_for_op_and_health_action(
"read_all",
|| async { Ok::<(), Error>(()) },
Duration::from_secs(1),
FailureHealthAction::MarkFailure,
)
.await
.expect("sibling drive RPC succeeds");
tokio::time::sleep(Duration::from_millis(80)).await;
Ok::<(), Error>(())
},
Duration::from_millis(20),
FailureHealthAction::MarkFailure,
)
.await
.expect_err("stalled drive must time out");
assert!(matches!(err, DiskError::Timeout));
assert_ne!(
stalled_drive.runtime_state(),
RuntimeDriveHealthState::Online,
"sibling drive progress must not suppress mark_faulty on the drive that actually timed out"
);
assert!(
rustfs_common::has_cached_connection(&addr).await,
"host-level progress from sibling drive must suppress shared-channel eviction"
);
rustfs_protos::evict_failed_connection(&addr).await;
clear_host_timeout_degradation(&addr);
}
}
@@ -686,21 +686,34 @@ impl RemoteClient {
}
}
fn record_request_timeout(&self, op: &'static str, deadline: Duration) {
fn record_request_timeout(&self, op: &'static str, deadline: Duration, admission: Option<LockRequestAdmission>) {
if !is_request_breaker_operation(op) {
return;
}
let now = Instant::now();
with_lock_peer_health(&self.addr, |health| {
// Once request backoff is active (`request_backoff_until.is_some()`), only a timeout
// from the currently admitted half-open probe generation may escalate or re-arm the
// backoff window. Straggler timeouts from RPCs admitted before backoff opened
// (`probe_generation: None`) or from a superseded probe generation must not compound
// backoff even if they arrive after `until` has elapsed.
if health.request_backoff_until.is_some() {
let is_active_probe = admission
.and_then(|token| token.probe_generation)
.is_some_and(|generation| health.request_probe_generation == Some(generation));
if !is_active_probe {
return;
}
}
health.request_consecutive_timeouts = health.request_consecutive_timeouts.saturating_add(1);
if health.request_consecutive_timeouts < LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
return;
}
let initial = deadline / 2;
let initial = (deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500));
let next = if health.request_backoff.is_zero() {
initial.max(Duration::from_millis(1))
initial
} else {
health.request_backoff.saturating_mul(2)
};
@@ -1274,7 +1287,7 @@ impl RemoteClient {
let reason = err.to_string();
if err.code() == tonic::Code::DeadlineExceeded {
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1324,7 +1337,7 @@ impl RemoteClient {
// the offline threshold for no benefit. See issue #4567.
let transport_failure = Self::is_transport_failure(&err);
if transport_failure {
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
}
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1412,7 +1425,7 @@ impl RemoteClient {
None => {
let reason = format!("RPC timed out after {deadline:?}");
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
self.record_request_timeout(op, deadline);
self.record_request_timeout(op, deadline, token);
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
if Self::is_scanner_leader_lock(resource_summary) {
debug!(
@@ -1541,7 +1554,7 @@ impl LockClient for RemoteClient {
let mut client = match self.get_client().await {
Ok(client) => client,
Err(err) => {
self.record_request_timeout("lock", rpc_timeout);
self.record_request_timeout("lock", rpc_timeout, admission.admission);
return Err(err);
}
};
@@ -2209,7 +2222,7 @@ mod tests {
reset_lock_peer_health_for_test(addr);
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100));
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
assert!(
@@ -2263,7 +2276,7 @@ mod tests {
});
let first = client.admit_lock_request("lock").expect("first probe should be admitted");
client.record_request_timeout("lock", Duration::from_millis(10));
client.record_request_timeout("lock", Duration::from_millis(10), Some(first));
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(1));
health.request_in_flight = 0;
@@ -2279,6 +2292,46 @@ mod tests {
reset_lock_peer_health_for_test(addr);
}
#[test]
fn late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe() {
let addr = "http://breaker-late-timeout-test";
let client = RemoteClient::new(addr.to_string());
reset_lock_peer_health_for_test(addr);
let pre_backoff = client
.admit_lock_request("lock")
.expect("normal pre-backoff RPC should be admitted");
assert!(!pre_backoff.is_probe());
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
client.record_request_timeout("lock", Duration::from_millis(100), None);
}
let initial_backoff = lock_peer_health_for_test(addr).request_backoff;
assert_eq!(initial_backoff, Duration::from_millis(25));
// Simulate backoff window expiry while the pre-backoff RPC is still finishing.
with_lock_peer_health(addr, |health| {
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(5));
});
// A late timeout from a non-probe RPC (`probe_generation: None`) arriving after `until`
// must NOT double the backoff or block the upcoming half-open probe.
client.record_request_timeout("lock", Duration::from_millis(100), Some(pre_backoff));
client.release_lock_request("lock", Some(pre_backoff));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff);
let probe = client
.admit_lock_request("lock")
.expect("expired backoff must still admit a half-open probe");
assert!(probe.is_probe());
// Only when the active probe itself times out does the backoff escalate.
client.record_request_timeout("lock", Duration::from_millis(100), Some(probe));
client.release_lock_request("lock", Some(probe));
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff * 2);
reset_lock_peer_health_for_test(addr);
}
#[test]
fn bounded_acquire_request_matches_transport_deadline() {
let request = test_lock_request(Duration::from_secs(30));
+62 -2
View File
@@ -797,6 +797,8 @@ fn get_drive_timeout_health_policy() -> TimeoutHealthPolicy {
pub struct DiskHealthTracker {
/// Atomic timestamp of last successful operation
pub last_success: AtomicI64,
/// Monotonic count of operations that completed successfully on this handle
pub completed_ops: AtomicU64,
/// Atomic timestamp of last operation start
pub last_started: AtomicI64,
/// Atomic disk status (OK or Faulty)
@@ -1239,6 +1241,7 @@ impl DiskHealthTracker {
Self {
last_success: AtomicI64::new(now_nanos),
completed_ops: AtomicU64::new(0),
last_started: AtomicI64::new(now_nanos),
status: AtomicU32::new(DISK_HEALTH_OK),
waiting: AtomicU32::new(0),
@@ -1261,6 +1264,11 @@ impl DiskHealthTracker {
/// Log a successful operation
pub fn log_success(&self) {
self.last_success.store(current_unix_nanos(), Ordering::Relaxed);
self.completed_ops.fetch_add(1, Ordering::AcqRel);
}
pub fn completed_ops(&self) -> u64 {
self.completed_ops.load(Ordering::Acquire)
}
pub fn record_capacity_probe(&self, total: u64, used: u64, free: u64) {
@@ -1398,6 +1406,22 @@ impl DiskHealthTracker {
became_offline
}
/// Record a foreground timeout failure only when no sibling operation on this drive
/// succeeded while the timed-out operation was in flight. Under heavy queue contention,
/// tail-latency timeouts occur while the drive is actively completing other operations;
/// marking such a drive `Suspect`/`Offline` cascades into synthetic write-quorum 503s.
pub fn mark_failure_unless_progressed(
&self,
endpoint: &Endpoint,
reason: &'static str,
completed_before: u64,
) -> Option<bool> {
if self.completed_ops() > completed_before {
return None;
}
Some(self.mark_failure(endpoint, reason))
}
#[allow(dead_code, reason = "asserted by this file's tests (backlog#1823)")]
pub fn mark_offline(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
@@ -1430,6 +1454,7 @@ impl DiskHealthTracker {
self.consecutive_successes.store(0, Ordering::Release);
self.offline_since_unix_secs.store(0, Ordering::Release);
self.waiting.store(0, Ordering::Release);
self.completed_ops.store(0, Ordering::Release);
self.last_success.store(now_nanos, Ordering::Relaxed);
self.last_started.store(now_nanos, Ordering::Relaxed);
self.last_transition_unix_secs.store(now_secs, Ordering::Release);
@@ -2780,6 +2805,7 @@ impl LocalDiskWrapper {
.expect("test timeout lock")
.map_or(timeout_duration, |injected| timeout_duration.min(injected));
// Execute the operation with timeout
let completed_before = self.health.completed_ops();
let result = tokio::time::timeout(timeout_duration, operation).await;
match result {
@@ -2797,9 +2823,13 @@ impl LocalDiskWrapper {
Err(_) => {
self.metrics.record_operation_latency(op, started.elapsed());
self.metrics.record_timeout_error();
// Timeout occurred, mark disk as potentially faulty.
// Timeout occurred; mark disk as potentially faulty only if no sibling I/O
// completed while this operation was waiting.
if timeout_health_action == TimeoutHealthAction::MarkFailure
&& self.health.mark_failure(&self.endpoint(), "operation_timeout")
&& self
.health
.mark_failure_unless_progressed(&self.endpoint(), "operation_timeout", completed_before)
== Some(true)
{
self.spawn_recovery_monitor_if_needed();
}
@@ -6890,6 +6920,36 @@ mod tests {
assert_eq!(wrapper.runtime_state(), RuntimeDriveHealthState::Suspect);
}
#[test]
fn concurrent_progress_prevents_false_faulty_on_queue_timeout() {
let endpoint = Endpoint::try_from("/tmp/concurrent-progress-disk").expect("endpoint should parse");
let health = DiskHealthTracker::new();
let before = health.completed_ops();
// Sibling operation completes while a queued operation is waiting.
health.record_operation_success(&endpoint, "operation_success");
assert!(health.completed_ops() > before);
// Timed-out straggler from the earlier batch must not degrade or fault the active drive.
assert_eq!(health.mark_failure_unless_progressed(&endpoint, "operation_timeout", before), None);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Online);
assert!(!health.is_faulty());
// When no sibling operation completes after `stalled_before`, timeouts degrade normally.
let stalled_before = health.completed_ops();
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(false)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Suspect);
assert_eq!(
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
Some(true)
);
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Offline);
assert!(health.is_faulty());
}
#[test]
#[serial_test::serial]
fn drive_timeout_health_policy_defaults_to_mark_failure() {
+1 -1
View File
@@ -1731,7 +1731,7 @@ async fn remove_windows_empty_directory(directory: LockedEmptyDirectory) -> std:
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle};
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
let disposition_size = u32::try_from(std::mem::size_of_val(&disposition))
.map_err(|_| std::io::Error::other("FILE_DISPOSITION_INFO size exceeds the Win32 API limit"))?;
let handle = directory.handle.as_raw_handle();
+4 -2
View File
@@ -6252,7 +6252,7 @@ fn rename_into_existing_parent(
// its header, the complete UTF-16 name, and trailing zeroed storage.
// `dst_parent` and `source` remain live until the synchronous call returns.
unsafe {
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: true };
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: 1 };
(*rename_info).RootDirectory = dst_parent.as_raw_handle();
(*rename_info).FileNameLength = file_name_length;
std::ptr::copy_nonoverlapping(
@@ -7753,7 +7753,9 @@ fn set_windows_file_delete_on_close(file: &winapi_util::Handle, delete_file: boo
Win32::{Foundation::RtlNtStatusToDosError, System::IO::IO_STATUS_BLOCK},
};
let mut disposition = FILE_DISPOSITION_INFORMATION { DeleteFile: delete_file };
let mut disposition = FILE_DISPOSITION_INFORMATION {
DeleteFile: u8::from(delete_file),
};
let length = u32::try_from(size_of::<FILE_DISPOSITION_INFORMATION>())
.map_err(|_| io::Error::other("Windows file disposition size exceeds u32"))?;
let mut io_status = IO_STATUS_BLOCK::default();
+36 -5
View File
@@ -207,13 +207,16 @@ impl ListReadBudget {
}
}
fn weight(&self, fanout: usize) -> usize {
// Admit a full walk even when its fanout exceeds the configured budget.
fanout.max(1).min(self.capacity)
}
async fn acquire(&self, fanout: usize) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
if self.capacity == 0 {
return Ok(None);
}
// A single walk must remain admissible even when the topology exceeds
// the configured budget. Tokio accepts at most u32::MAX in one grant.
let weight = u32::try_from(fanout.max(1).min(self.capacity)).unwrap_or(u32::MAX);
let weight = u32::try_from(self.weight(fanout)).unwrap_or(u32::MAX);
self.permits
.clone()
.acquire_many_owned(weight)
@@ -491,6 +494,12 @@ impl InstanceContext {
.await
}
pub(crate) fn list_read_budget_has_capacity(&self, fanout: usize) -> Option<bool> {
self.list_read_budget
.get()
.map(|budget| budget.permits.available_permits() >= budget.weight(fanout))
}
/// Build a context bound to a specific lock manager.
///
/// [`bootstrap_ctx`] uses this to alias the process-global lock manager so
@@ -1575,8 +1584,16 @@ mod tests {
#[tokio::test]
async fn list_read_budget_zero_preserves_unbounded_configuration() {
let budget = ListReadBudget::new(0);
assert!(budget.acquire(usize::MAX).await.expect("disabled budget").is_none());
let ctx = InstanceContext::new();
assert_eq!(ctx.list_read_budget_has_capacity(1), None);
ctx.list_read_budget.set(ListReadBudget::new(0)).expect("fresh context");
assert!(
ctx.acquire_list_read_budget(usize::MAX)
.await
.expect("disabled budget")
.is_none()
);
assert_eq!(ctx.list_read_budget_has_capacity(usize::MAX), Some(true));
}
#[tokio::test]
@@ -1611,6 +1628,8 @@ mod tests {
let other = InstanceContext::new();
other.list_read_budget.set(ListReadBudget::new(4)).expect("fresh context");
let held = first.acquire_list_read_budget(4).await.expect("first context");
assert_eq!(same.list_read_budget_has_capacity(4), Some(false));
assert_eq!(other.list_read_budget_has_capacity(4), Some(true));
let mut waiter = std::pin::pin!(same.acquire_list_read_budget(1));
assert!(futures::poll!(&mut waiter).is_pending());
assert!(
@@ -1622,6 +1641,18 @@ mod tests {
);
drop(held);
assert!(waiter.await.expect("shared context resumed").is_some());
assert_eq!(same.list_read_budget_has_capacity(4), Some(true));
}
#[tokio::test]
async fn list_read_budget_reports_capacity_for_the_requested_fanout() {
let ctx = InstanceContext::new();
ctx.list_read_budget.set(ListReadBudget::new(64)).expect("fresh context");
let held = ctx.acquire_list_read_budget(48).await.expect("first walk");
assert_eq!(ctx.list_read_budget_has_capacity(16), Some(true));
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(false));
drop(held);
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(true));
}
#[test]
@@ -1025,6 +1025,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let futures = disks.iter().enumerate().map(|(disk_index, disk)| {
let disk = disk.clone();
let task_opts = opts;
@@ -1157,7 +1164,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout();
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
if let Some(observations) = &mut observations {
observations.push(MetadataFanoutObservation::from_error(
@@ -1270,6 +1277,13 @@ impl SetDisks {
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
);
let fanout_host_progress: Vec<u64> = disks
.iter()
.map(|disk| match disk.as_deref() {
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
_ => 0,
})
.collect();
let spawn_read_version = |join_set: &mut JoinSet<(usize, disk::error::Result<FileInfo>, Duration)>,
task_ids: &mut [Option<tokio::task::Id>],
index: usize,
@@ -1436,7 +1450,7 @@ impl SetDisks {
if let Some(Some(disk)) = disks.get(slot.disk_index)
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
{
remote.record_straggler_timeout();
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
}
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
slot.result = Some(Err(DiskError::Timeout));
@@ -3922,6 +3922,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: Some(OffsetDateTime::now_utc()),
size: w_size,
actual_size,
checksums: part_info.checksums,
};
// error!("put_object_part ret {:?}", &ret);
@@ -4020,6 +4021,19 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
bucket: owner.bucket,
object: owner.object,
});
// The upload records its checksum algorithm and type at CreateMultipartUpload.
// ListParts echoes them like CreateMultipartUpload and CompleteMultipartUpload do,
// so a client that resumes an upload can state the same checksum contract.
let checksum_algorithm = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM)
.cloned()
.unwrap_or_default();
let checksum_type = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE)
.cloned()
.unwrap_or_default();
let mut ret = ListPartsInfo {
recorded_owner,
bucket: bucket.to_owned(),
@@ -4028,6 +4042,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
storage_class,
max_parts,
part_number_marker,
checksum_algorithm,
checksum_type,
user_defined: {
let mut metadata = fi.metadata.clone();
strip_internal_multipart_metadata(&mut metadata);
@@ -4120,6 +4136,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: part.mod_time,
size: part.size,
actual_size: part.actual_size,
checksums: part.checksums.clone(),
});
count -= 1;
@@ -7607,6 +7624,35 @@ mod tests {
}
}
#[tokio::test]
async fn list_object_parts_echoes_upload_and_part_checksums() {
let (_temp_dirs, disks, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-checksum-listing";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let payloads: [&[u8]; 2] = [b"first checksummed part", b"second checksummed part"];
let (upload_id, _, checksums) =
stage_checksummed_multipart_upload(&set_disks, bucket, object, Some(rustfs_rio::ChecksumType::SHA256), &payloads)
.await;
let page = set_disks
.list_object_parts(bucket, object, &upload_id, None, 10, &ObjectOptions::default())
.await
.expect("checksummed parts should be listable");
assert_eq!(page.checksum_algorithm, "SHA256");
assert_eq!(page.checksum_type, "COMPOSITE");
assert_eq!(page.parts.len(), payloads.len());
for (part, checksum) in page.parts.iter().zip(&checksums) {
assert_eq!(
part.checksums.as_ref().and_then(|checksums| checksums.get("SHA256")),
Some(&checksum.encoded),
"part {} must echo its recorded checksum",
part.part_num
);
}
}
#[tokio::test]
async fn list_parts_baseline_legacy_owner_metadata() {
let (_roots, disks, set) = hermetic_set_disks(4).await;
+17 -4
View File
@@ -1572,6 +1572,18 @@ impl ECStore {
})
}
fn list_read_fanout(&self) -> usize {
self.pools.iter().fold(0usize, |total, pool| {
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
})
}
/// Whether the local budget can fit one full listing walk at the time of sampling.
/// Returns `None` until a listing walk initializes the budget.
pub fn list_read_budget_has_capacity(&self) -> Option<bool> {
self.ctx.list_read_budget_has_capacity(self.list_read_fanout())
}
pub async fn list_path(self: Arc<Self>, o: &ListPathOptions) -> Result<ListPage> {
// tracing::warn!("list_path opt {:?}", &o);
@@ -1625,10 +1637,11 @@ impl ECStore {
if o.transient {
o.create = false;
}
let fanout = self.pools.iter().fold(0usize, |total, pool| {
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
});
o.read_budget = self.ctx.acquire_list_read_budget(fanout).await.map_err(Error::other)?;
o.read_budget = self
.ctx
.acquire_list_read_budget(self.list_read_fanout())
.await
.map_err(Error::other)?;
let log_context = ListPathLogContext::from_options(&o);
+15
View File
@@ -37,6 +37,7 @@ pub type S3HttpCompletionObserverEnabled = fn() -> bool;
const METRIC: &str = "rustfs_s3_http_requests_total";
const LOCK_FAILURE_METRIC: &str = "rustfs_s3_lock_failures_total";
const S3_503_RESPONSES_METRIC: &str = "rustfs_s3_503_responses_total";
const ENTRY_TO_DISPATCH_METRIC: &str = "rustfs_s3_http_entry_to_dispatch_duration_seconds";
const METHODS: [&str; 10] = [
"GET", "PUT", "POST", "DELETE", "HEAD", "OPTIONS", "PATCH", "CONNECT", "TRACE", "OTHER",
@@ -240,6 +241,20 @@ pub fn record_s3_http_lock_failure(resource_class: &'static str, mode: &'static
});
}
/// Record an HTTP 503 S3 refusal classified by S3 error code and bounded subcause.
pub fn record_s3_http_503_response(s3_code: &'static str, subcause: &'static str) {
let op_label = CURRENT_OPERATION
.try_with(|current| operation_label(current.get().operation))
.unwrap_or("unknown");
metrics::counter!(
S3_503_RESPONSES_METRIC,
"op" => op_label,
"code" => s3_code,
"subcause" => subcause
)
.increment(1);
}
/// An external request is counted exactly once: at response headers, at a
/// service error, or when its future is dropped before producing a response.
/// Body-stream failures after headers use the existing streaming metrics.
+208 -7
View File
@@ -1887,7 +1887,14 @@ impl DistributedLock {
// A peer may grant promptly but deliver its response after its local
// contention budget. Keep this round's owners until a response proves
// quorum impossible or the caller's remaining budget expires.
let result = self.acquire_lock_quorum_once(&attempt_request, remaining).await?;
// On Exclusive contention retries (`attempt > 1`), serialize on the
// canonical anchor voter (`clients[0]`) before fanning out to remaining
// voters so N-node local-first split-votes do not livelock across rounds
// while preserving 1-RTT initial fanout and 2s reader-outlast queue time.
let serialize_on_anchor = request.lock_type == LockType::Exclusive && attempt > 1;
let result = self
.acquire_lock_quorum_once_inner(&attempt_request, remaining, serialize_on_anchor)
.await?;
if !result.response.success {
tracing::trace!(
target: "rustfs_lock::namespace_owner",
@@ -1973,10 +1980,21 @@ impl DistributedLock {
/// Quorum-based lock acquisition: success if at least the required quorum succeeds.
/// Collects all individual lock_ids from successful clients and creates an aggregate lock_id.
/// Returns the LockResponse with aggregate lock_id and individual lock mappings.
#[cfg_attr(not(test), allow(dead_code))]
async fn acquire_lock_quorum_once(&self, request: &LockRequest, quorum_timeout: Duration) -> Result<LockAcquireQuorumResult> {
self.acquire_lock_quorum_once_inner(request, quorum_timeout, false).await
}
async fn acquire_lock_quorum_once_inner(
&self,
request: &LockRequest,
quorum_timeout: Duration,
serialize_on_anchor: bool,
) -> Result<LockAcquireQuorumResult> {
let voter_count =
u32::try_from(self.clients.len().max(1)).map_err(|_| LockError::internal("lock voter count exceeds u32"))?;
let required_quorum = self.required_quorum(request.lock_type);
let anchor_serialized = serialize_on_anchor && self.clients.len() > 1;
let attempt_started = Instant::now();
let quorum_deadline = attempt_started.checked_add(quorum_timeout).unwrap_or(attempt_started);
let grant_valid_until = attempt_started.checked_add(request.ttl).unwrap_or(attempt_started);
@@ -1987,18 +2005,19 @@ impl DistributedLock {
fallback_lock_id: request.lock_id.clone(),
};
let mut next_client_index = 0usize;
self.spawn_lock_requests_until(
&mut round.pending,
request,
&mut next_client_index,
let initial_target = if anchor_serialized {
1
} else {
required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len()),
);
.min(self.clients.len())
};
self.spawn_lock_requests_until(&mut round.pending, request, &mut next_client_index, initial_target);
let mut last_failure = None;
let mut last_failure_kind = None;
let mut last_hard_failure_kind = None;
let mut hard_failures = 0usize;
let mut anchor_definitive_contention = false;
let mut retry_at = vec![None; self.clients.len()];
let mut contention_retries = vec![0usize; self.clients.len()];
let start = attempt_started;
@@ -2107,6 +2126,9 @@ impl DistributedLock {
// Only an authoritative no-grant response is safe to retry under
// the same ID. A successful or still-pending voter is never retried.
if is_definitive_lock_contention(&error) {
if idx == 0 {
anchor_definitive_contention = true;
}
contention_retries[idx] = contention_retries[idx].saturating_add(1);
let backoff = LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF
.saturating_mul(contention_retries[idx].try_into().unwrap_or(u32::MAX));
@@ -2263,6 +2285,34 @@ impl DistributedLock {
});
}
// When serializing a contended Exclusive retry on the healthy anchor voter
// (`clients[0]`), yield immediately only if `clients[0]` rejected due to definitive
// lock contention rather than fanning out and split-voting on `clients[1..]`. If
// `clients[0]` granted (`!round.grants.is_empty()`), returned a timeout/backoff/breaker
// failure (`!anchor_definitive_contention`), failed with an RPC error (`hard_failures > 0`),
// or timed out its silent-prefix hedge (`next_client_index > 1`), fall through and fan out
// normally so offline, degraded, or hung anchor nodes never block quorum.
if anchor_serialized
&& anchor_definitive_contention
&& round.grants.is_empty()
&& hard_failures == 0
&& next_client_index == 1
&& round.pending.is_empty()
{
let mut error = format!("Anchor voter contended: 0/{required_quorum} required");
if let Some(last_failure) = last_failure {
error.push_str("; last failure: ");
error.push_str(&last_failure);
}
return Ok(LockAcquireQuorumResult {
response: LockResponse::failure(error, Duration::ZERO),
individual_locks: Vec::new(),
failure_kind: Some(LockAcquireFailureKind::RetryableContention),
quorum_impossible: false,
attempt_timed_out: false,
});
}
let needed = required_quorum.saturating_sub(round.grants.len());
self.spawn_lock_requests_until(
&mut round.pending,
@@ -5053,4 +5103,155 @@ mod tests {
);
drop(results);
}
#[tokio::test]
async fn exclusive_retry_fans_out_to_remaining_voters_when_anchor_times_out_or_breaker_opens() {
#[derive(Debug)]
struct FixedResponseClient {
calls: Arc<std::sync::atomic::AtomicUsize>,
response: LockResponse,
}
#[async_trait::async_trait]
impl LockClient for FixedResponseClient {
async fn acquire_lock(&self, request: &LockRequest) -> crate::Result<LockResponse> {
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if self.response.success {
Ok(LockResponse::success(
LockInfo {
id: request.lock_id.clone(),
resource: request.resource.clone(),
lock_type: request.lock_type,
status: crate::LockStatus::Acquired,
owner: request.owner.clone(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + request.ttl,
last_refreshed: std::time::SystemTime::now(),
metadata: request.metadata.clone(),
priority: request.priority,
wait_start_time: None,
},
Duration::ZERO,
))
} else {
Ok(self.response.clone())
}
}
async fn release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn refresh(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn force_release(&self, _lock_id: &LockId) -> crate::Result<bool> {
Ok(true)
}
async fn check_status(&self, _lock_id: &LockId) -> crate::Result<Option<LockInfo>> {
Ok(None)
}
async fn get_stats(&self) -> crate::Result<LockStats> {
Ok(LockStats::default())
}
async fn close(&self) -> crate::Result<()> {
Ok(())
}
async fn is_online(&self) -> bool {
true
}
async fn is_local(&self) -> bool {
false
}
}
for anchor_error in [
"RPC request backoff active for lock on http://127.0.0.1:9000",
"remote lock RPC lock on http://127.0.0.1:9000 timed out after 1s",
] {
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c2_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure(anchor_error, Duration::ZERO),
});
let grant_template = LockResponse::success(
LockInfo {
id: LockId::new(ObjectKey::new("bucket", "key")),
resource: ObjectKey::new("bucket", "key"),
lock_type: LockType::Exclusive,
status: crate::LockStatus::Acquired,
owner: "owner".to_string(),
acquired_at: std::time::SystemTime::now(),
expires_at: std::time::SystemTime::now() + Duration::from_secs(30),
last_refreshed: std::time::SystemTime::now(),
metadata: Default::default(),
priority: Default::default(),
wait_start_time: None,
},
Duration::ZERO,
);
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: grant_template.clone(),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c2_calls),
response: grant_template,
});
let lock = DistributedLock::new("anchor-breaker-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("quorum attempt must complete");
assert!(
outcome.response.is_success(),
"anchor error `{anchor_error}` must fall through to remaining voters and reach 2/3 quorum"
);
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c2_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
}
// Conversely, definitive contention on the anchor must still short-circuit without
// contacting the remaining voters.
let c0_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c1_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let c0: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c0_calls),
response: LockResponse::failure("Lock conflict: resource held by other", Duration::ZERO),
});
let c1: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::clone(&c1_calls),
response: LockResponse::failure("unused", Duration::ZERO),
});
let c2: Arc<dyn LockClient> = Arc::new(FixedResponseClient {
calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
response: LockResponse::failure("unused", Duration::ZERO),
});
let lock = DistributedLock::new("anchor-contention-test".to_string(), vec![c0, c1, c2], 2);
let request = LockRequest::new(ObjectKey::new("bucket", "key"), LockType::Exclusive, "owner")
.with_acquire_timeout(Duration::from_millis(500))
.with_ttl(Duration::from_secs(30));
let outcome = lock
.acquire_lock_quorum_once_inner(&request, Duration::from_millis(500), true)
.await
.expect("contention attempt must complete");
assert!(!outcome.response.is_success());
assert!(matches!(outcome.failure_kind, Some(LockAcquireFailureKind::RetryableContention)));
assert_eq!(c0_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
assert_eq!(c1_calls.load(std::sync::atomic::Ordering::SeqCst), 0);
}
}
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "metrics"
version = "0.24.6"
publish = false
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
description = "RustFS compatibility facade for dependencies requiring metrics 0.24"
[dependencies]
# Use a distinct extern name when rustdoc also links the facade as metrics.
metrics_025 = { package = "metrics", version = "0.25.1" }
[dev-dependencies]
metrics-util = { workspace = true, features = ["debugging"] }
toml = "1.2.3"
[lints]
workspace = true
+82
View File
@@ -0,0 +1,82 @@
// Copyright 2026 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.
//! Share the metrics recorder with dependencies requiring metrics 0.24.
// RUSTFS_COMPAT_TODO(metrics-024-recorder): Share the recorder with 0.24 consumers. Remove after all consumers accept metrics 0.25 directly.
pub use metrics_025::*;
#[cfg(test)]
mod tests {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
#[test]
fn legacy_macros_reach_the_metrics_025_recorder() {
let recorder = DebuggingRecorder::new();
metrics_025::with_local_recorder(&recorder, || {
crate::counter!("messages", "topic" => "events").increment(2);
metrics_025::counter!("messages", "topic" => "events").increment(3);
crate::gauge!("connections").set(4.0);
crate::histogram!("latency").record(5.0);
});
let entries = recorder.snapshotter().snapshot().into_vec();
let expected = [
(
metrics_025::Key::from_parts("messages", vec![metrics_025::Label::new("topic", "events")]),
DebugValue::Counter(5),
),
(metrics_025::Key::from_name("connections"), DebugValue::Gauge(4.0.into())),
(metrics_025::Key::from_name("latency"), DebugValue::Histogram(vec![5.0.into()])),
];
assert_eq!(entries.len(), expected.len());
for (key, value) in expected {
assert!(
entries
.iter()
.any(|(entry, _, _, recorded)| entry.key() == &key && recorded == &value)
);
}
}
#[test]
fn workspace_and_fuzz_use_only_one_recorder_implementation() {
for (lockfile, needs_facade) in [
(include_str!("../../../Cargo.lock"), true),
(include_str!("../../../fuzz/Cargo.lock"), false),
] {
let lock: toml::Value = toml::from_str(lockfile).expect("Cargo lockfile should parse");
let packages = lock["package"].as_array().expect("Cargo lockfile should list packages");
let metrics: Vec<_> = packages
.iter()
.filter(|package| package["name"].as_str() == Some("metrics"))
.collect();
assert_eq!(metrics.len(), 1 + usize::from(needs_facade), "metrics must have one implementation");
assert_eq!(
metrics
.iter()
.any(|package| { package["version"].as_str() == Some("0.24.6") && package.get("source").is_none() }),
needs_facade,
);
assert!(metrics.iter().any(|package| {
package["version"]
.as_str()
.is_some_and(|version| version.starts_with("0.25."))
&& package["source"]
.as_str()
.is_some_and(|source| source.starts_with("registry+"))
}));
}
}
}
+9 -16
View File
@@ -169,34 +169,24 @@ Refreshing only dirty disks is safe only when:
- `disk_cache_complete == true`
- which means the system has already completed at least one full refresh without partial errors
- and the per-disk cache is fully populated
- and the per-disk cache covers the current local disk set
If no aggregate cache exists yet, the system performs a full refresh to establish an initial value. Once an aggregate cache exists, a scheduled refresh with no dirty disks stays idle instead of repeatedly walking unchanged disks. If disks are dirty while the per-disk cache is incomplete, the system performs a full refresh because a subset cannot be merged safely.
The first refresh builds an aggregate baseline. Scheduled refreshes stay idle when there are no dirty disks and the baseline still applies. A change in local disk membership triggers a full refresh, including replacements that keep the same disk count. Dirty disks with an incomplete per-disk baseline also trigger a full refresh.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. That bounded estimate acknowledges dirty marks that predate the scan, while marks recorded during the scan remain pending. This prevents one old dirty mark from causing an endless timeout loop without treating the estimate as exact.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. A bounded or degraded full refresh after a topology change discards the old per-disk baseline and publishes the available current aggregate. A timeout estimate acknowledges dirty marks that predate the scan. Marks recorded during the scan remain pending.
### Merge Rules After a Subset Refresh
- On a successful full refresh, `per_disk` replaces the entire `disk_cache`.
- On a successful dirty-subset refresh, only the affected per-disk entries are updated.
- The total capacity is recomputed from the updated `disk_cache` instead of trusting the subset sum directly.
- If a dirty-subset refresh reports partial errors, that cycle fails and the caller falls back to a full refresh to recover consistency.
- If a dirty-subset refresh reports partial errors, that cycle fails and preserves the last published cache and pending dirty marks.
## Relationship to the RustFS Main Flow
This crate provides capacity primitives only. The actual RustFS integration lives in `rustfs/src/capacity/service.rs`.
`rustfs/src/capacity/service.rs` starts the background capacity manager with a provider that discovers local disks on each scheduled refresh. The manager publishes the cached estimate as `rustfs_capacity_current_bytes`. The admin storage usage view comes from the storage information API.
The high-level flow is:
1. Startup calls `init_capacity_management_for_local_disks()`.
2. It collects all local disks and calls `capacity_manager::start_background_task(...)`.
3. Admin used-capacity queries first try the `HybridCapacityManager` cache.
4. If the cache is fresh enough, the cached value is returned directly.
5. If the cache is stale but still acceptable, the stale value is served and a background refresh is triggered.
6. If the cache is very stale and the write rate is high, the request blocks on a foreground refresh.
7. If the initial real-time scan fails, the service falls back to externally supplied disk-used capacity and stores it as `Fallback`.
`crates/ecstore/src/set_disk.rs` is responsible for recording capacity scopes during object writes, heal operations, data movement, and related flows, so this crate can learn which disks were affected.
`crates/ecstore/src/set_disk/mod.rs` records capacity scopes so object writes, heal operations, and data movement can mark affected disks dirty.
## Public API
@@ -288,6 +278,7 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | Cache age required before fast refresh is considered |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | Exact-count file threshold |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Base scan timeout |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | On Linux, use filesystem-reported used space on eligible dedicated drive mounts |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | Overflow-file sampling interval |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | Runtime summary emission interval |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | Whether to follow symlinks |
@@ -296,6 +287,8 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Dynamic-timeout upper bound |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | Stall-detection threshold |
On Linux, `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true` enables direct readings on whole XFS, ext-family, and tmpfs mounts used exclusively by RustFS. The fast path requires kernel mount IDs and the process mount table. A symlink used as the drive root resolves to its target. Subdirectory bind mounts, multiple views of a device, mounts with child mounts, and pooled filesystems such as Btrfs or ZFS use directory scanning. The reading estimates used capacity from allocated filesystem blocks, which can include metadata and differ from summed file lengths. Direct readings do not count files. When a directory scan in this mode times out, it estimates usage from available file samples. Other platforms and configurations that follow symlinks within the drive use the default scan behavior. Restart RustFS after changing this setting.
Explicit `RUSTFS_CAPACITY_STAT_TIMEOUT` and `RUSTFS_CAPACITY_MAX_TIMEOUT` values
take precedence over the drive-timeout profile.
+9 -16
View File
@@ -169,34 +169,24 @@ crate 不是“超时就直接失败”的设计:
- `disk_cache_complete == true`
- 也就是系统已经完成过一次“无部分错误”的全盘刷新
- 并且成功拿到了每盘缓存
- 并且每盘缓存覆盖当前本地盘集合
若当前还没有任何聚合缓存,系统会先执行一次全盘刷新来建立初始值。已有聚合缓存后,定时刷新在没有脏盘时会保持 idle,不再重复遍历未变化的磁盘。若 per-disk cache 尚不完整但存在脏盘,系统仍执行全盘刷新,因为此时不能安全合并子集结果。
首次刷新会建立聚合基线。没有脏盘且原基线仍适用时,定时刷新保持空闲。本地盘成员变化时触发全量刷新,包括盘数相同的替换。存在脏盘但每盘基线不完整时,也执行全量刷新。
全盘刷新达到时间预算后,可以发布估算聚合值,但不会借此建立完整 per-disk 基线。该有界估算会确认扫描开始前的脏标记;扫描过程中记录的新标记仍会保留。这样既不会把估算值当成精确值,也不会让一个旧脏标记永久触发超时循环。
全盘刷新达到时间预算后,可以发布估算聚合值。拓扑变化后的全量刷新若超时或降级,会丢弃旧的每盘基线,并发布当前可用的聚合值。超时估算会确认扫描开始前的脏标记,扫描过程中记录的新标记仍会保留。
### 子集刷新后的合并规则
- 全盘刷新成功时,`per_disk` 会完整替换 `disk_cache`。
- dirty subset 刷新成功时,只更新对应脏盘的缓存条目。
- 总容量会基于更新后的 `disk_cache` 重新求和,而不是盲信子集扫描返回的局部和。
- 若 dirty subset 刷新出现 partial errors,则当前轮次失败,并回退到全盘刷新恢复一致性。
- 若脏盘子集刷新出现部分错误,则本轮失败,保留上次发布的缓存和待处理脏标记。
## 与 RustFS 主流程的关系
这个 crate 本身只提供容量能力,真正把它接到 RustFS 主流程的是 `rustfs/src/capacity/service.rs`。
`rustfs/src/capacity/service.rs` 启动后台容量管理器,并在每轮定时刷新时发现当前本地盘。管理器通过 `rustfs_capacity_current_bytes` 发布缓存的容量估算值。管理接口的存储用量取自存储信息 API。
上层使用方式大致如下:
1. 启动时调用 `init_capacity_management_for_local_disks()`。
2. 它收集所有本地盘,调用 `capacity_manager::start_background_task(...)`。
3. 管理接口查询 used capacity 时,优先读 `HybridCapacityManager` 缓存。
4. 缓存足够新时直接返回。
5. 缓存过旧但还可容忍时,先返回 stale cache,再后台刷新。
6. 缓存极旧且写入频率高时,前台阻塞刷新。
7. 若首次实时扫描失败,则退回外部已有的磁盘 used capacity,并写入 `Fallback` 缓存。
`crates/ecstore/src/set_disk.rs` 中则负责在对象写入、heal、data movement 等流程里记录 capacity scope,把“这次写影响了哪些盘”传播给本 crate。
`crates/ecstore/src/set_disk/mod.rs` 记录容量作用域,以便对象写入、修复和数据迁移标记受影响的磁盘。
## 公开 API
@@ -288,6 +278,7 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | 缓存超过该年龄后才考虑快速刷新 |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | 精确统计文件数阈值 |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` | 基础扫描超时 |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | 在 Linux 上直接读取符合条件的独占挂载用量 |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | overflow 文件采样间隔 |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | runtime summary 打点间隔 |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | 是否跟随符号链接 |
@@ -296,6 +287,8 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` | 动态超时上界 |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | 无进展 stall 判定阈值 |
在 Linux 上设置 `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true`,可直接读取 RustFS 独占的 XFS、ext 系列和 tmpfs 整卷挂载。快速路径依赖内核挂载 ID 和进程挂载表,磁盘根路径是符号链接时会解析到目标。子目录 bind mount、同一设备的多个挂载视图、带子挂载的卷,以及 Btrfs、ZFS 等共享池文件系统走目录扫描。直接读取按已分配块估算容量,可能包含元数据,也可能与文件长度之和不同,无文件计数。此模式下目录扫描超时时,使用已有的文件样本估算。其他平台或启用盘内符号链接跟随时走默认扫描。更改设置后需重启 RustFS。
### 配置缓存注意事项
在非测试构建中,配置通过 `OnceLock` 缓存:
+161 -52
View File
@@ -29,6 +29,8 @@ use rustfs_config::{
ENV_CAPACITY_STAT_TIMEOUT, ENV_CAPACITY_WRITE_FREQUENCY_THRESHOLD, ENV_CAPACITY_WRITE_TRIGGER_DELAY,
ENV_DRIVE_TIMEOUT_PROFILE,
};
#[cfg(target_os = "linux")]
use rustfs_config::{DEFAULT_CAPACITY_USE_MOUNT_USAGE, ENV_CAPACITY_USE_MOUNT_USAGE};
use rustfs_io_metrics::capacity_metrics::{
record_capacity_current_bytes, record_capacity_degraded_reading, record_capacity_dirty_disk_count,
record_capacity_refresh_inflight, record_capacity_refresh_joiner, record_capacity_refresh_result,
@@ -86,6 +88,8 @@ struct CachedCapacityConfig {
metrics_interval: Duration,
/// Follow symlinks flag
follow_symlinks: bool,
#[cfg(target_os = "linux")]
use_mount_usage: bool,
/// Enable dynamic timeout flag
enable_dynamic_timeout: bool,
/// Min timeout
@@ -153,6 +157,8 @@ impl CachedCapacityConfig {
DEFAULT_CAPACITY_METRICS_INTERVAL_SECS,
)),
follow_symlinks: get_env_bool(ENV_CAPACITY_FOLLOW_SYMLINKS, DEFAULT_CAPACITY_FOLLOW_SYMLINKS),
#[cfg(target_os = "linux")]
use_mount_usage: get_env_bool(ENV_CAPACITY_USE_MOUNT_USAGE, DEFAULT_CAPACITY_USE_MOUNT_USAGE),
enable_dynamic_timeout: get_env_bool(ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT, DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT),
min_timeout: Duration::from_secs(env_u64_at_least(ENV_CAPACITY_MIN_TIMEOUT, DEFAULT_CAPACITY_MIN_TIMEOUT_SECS, 1)),
max_timeout: Duration::from_secs(env_u64_at_least(
@@ -285,6 +291,11 @@ pub fn get_follow_symlinks() -> bool {
get_cached_config().follow_symlinks
}
#[cfg(target_os = "linux")]
pub(crate) fn get_use_mount_usage() -> bool {
get_cached_config().use_mount_usage
}
/// Get enable dynamic timeout flag from environment or default
#[cfg(not(test))]
pub fn get_enable_dynamic_timeout() -> bool {
@@ -353,8 +364,7 @@ pub struct CapacityUpdate {
/// Whether the value is estimated instead of exact.
pub is_estimated: bool,
/// Whether the refresh behind this update had partial disk failures.
/// `is_estimated` only reflects sampling; this flag is the only carrier of
/// the "some disks failed to scan" fact (backlog#1014).
/// Independent of `is_estimated`, which describes how bytes were measured.
pub degraded: bool,
/// Whether the scan reached its time budget and returned a fallback estimate.
pub timed_out: bool,
@@ -754,7 +764,6 @@ pub struct HybridCapacityManager {
/// Per-disk cache populated after a successful full refresh and updated by dirty subset refreshes.
disk_cache: Arc<RwLock<HashMap<CapacityScopeDisk, CachedDiskCapacity>>>,
/// Whether the per-disk cache currently covers all known disks.
disk_cache_complete: Arc<RwLock<bool>>,
/// Configuration
config: HybridStrategyConfig,
/// Shared singleflight refresh state
@@ -787,7 +796,6 @@ impl HybridCapacityManager {
write_record: Arc::new(WriteRecord::new()),
dirty_disks: Arc::new(RwLock::new(HashMap::new())),
disk_cache: Arc::new(RwLock::new(HashMap::new())),
disk_cache_complete: Arc::new(RwLock::new(false)),
config,
refresh_state: Arc::new(Mutex::new(RefreshState::default())),
}
@@ -811,57 +819,62 @@ impl HybridCapacityManager {
/// only the scanned subset's totals; callers that publish or return this value (e.g. the
/// `refresh_or_join` leader and joiners, admin used-capacity) must use the reconciled copy
/// so they never report the subset bytes as the whole-cluster total.
pub async fn update_capacity(&self, mut update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
pub async fn update_capacity(&self, update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
self.commit_capacity(update, source, None).await
}
async fn commit_capacity(
&self,
mut update: CapacityUpdate,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
) -> CapacityUpdate {
let start = Instant::now();
if !update.per_disk.is_empty() || update.degraded {
let mut disk_cache = self.disk_cache.write().await;
let mut disk_cache_complete = self.disk_cache_complete.write().await;
let recompute = if !update.per_disk.is_empty()
let replaces_cache = !update.per_disk.is_empty()
&& update.replaces_disk_cache
&& update.expected_disk_count == Some(update.per_disk.len())
{
&& update.expected_disk_count == Some(update.per_disk.len());
if replaces_cache {
disk_cache.clear();
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
} else if !disk_cache.is_empty()
&& let Some(disks) = full_scan_disks
{
// A bounded full scan may publish bytes without establishing a
// baseline. Do not merge a previous topology into that result.
let local: HashSet<_> = disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
if disk_cache.len() != local.len()
|| !disk_cache
.keys()
.all(|disk| local.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
{
disk_cache.clear();
}
*disk_cache_complete = true;
true
} else if *disk_cache_complete {
// Merging over a complete cache also covers a degraded
// (partial-failure) full refresh: successfully scanned disks
// are refreshed while failed disks keep their last-known
// values, so the published total does not dip to the
// surviving-subset sum and bounce back on the next refresh.
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
true
} else {
false
};
}
if recompute {
// Reconcile cluster-wide aggregates from the full per-disk cache so a
// dirty-subset refresh reports the merged cluster totals, not the subset sum.
update.total_used = disk_cache.values().map(|entry| entry.used_bytes).sum();
update.file_count = disk_cache.values().map(|entry| entry.file_count).sum();
update.is_estimated = disk_cache.values().any(|entry| entry.is_estimated);
// A nonempty disk cache always covers one complete topology. A
// degraded refresh on that topology keeps last-known disk entries.
if replaces_cache || !disk_cache.is_empty() {
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
let (bytes, files, estimated) = disk_cache.values().fold((0, 0, false), |(bytes, files, estimated), entry| {
(bytes + entry.used_bytes, files + entry.file_count, estimated || entry.is_estimated)
});
update.total_used = bytes;
update.file_count = files;
update.is_estimated = estimated;
}
}
@@ -1051,15 +1064,33 @@ impl HybridCapacityManager {
/// Returns true if the manager has a complete per-disk cache and can safely refresh only dirty disks.
pub async fn can_refresh_dirty_subset(&self) -> bool {
*self.disk_cache_complete.read().await
!self.disk_cache.read().await.is_empty()
}
pub(crate) async fn disk_cache_matches(&self, local: &HashSet<CapacityScopeDisk>) -> Option<bool> {
let cache = self.disk_cache.read().await;
(!cache.is_empty()).then(|| cache.len() == local.len() && cache.keys().all(|disk| local.contains(disk)))
}
/// Run a singleflight refresh. Callers either join an existing in-flight refresh or become the leader.
///
/// Joiners subscribe to the watch channel *before* releasing the mutex, which guarantees
/// they cannot miss the completion notification even if the leader finishes very quickly.
#[hotpath::measure]
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
{
self.refresh_or_join_for_disks(source, None, refresh_fn).await
}
#[hotpath::measure]
async fn refresh_or_join_for_disks<F, Fut>(
&self,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
refresh_fn: F,
) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
@@ -1141,7 +1172,7 @@ impl HybridCapacityManager {
// returned to this caller and the one published to joiners carry the cluster totals
// rather than a dirty-subset's partial bytes.
let result = match result {
Ok(update) => Ok(self.update_capacity(update, source).await),
Ok(update) => Ok(self.commit_capacity(update, source, full_scan_disks).await),
Err(err) => Err(err),
};
let refresh_duration = refresh_start.elapsed();
@@ -1427,8 +1458,8 @@ async fn run_scheduled_capacity_refresh(manager: Arc<HybridCapacityManager>, dis
"capacity refresh scheduled"
);
let result = manager
.refresh_or_join(DataSource::Scheduled, move || async move {
refresh_capacity_with_scope(disks, dirty_subset).await
.refresh_or_join_for_disks(DataSource::Scheduled, (!dirty_subset).then_some(disks.as_slice()), || {
refresh_capacity_with_scope(&disks, dirty_subset)
})
.await;
scheduled_refresh_was_clean(&result)
@@ -2476,6 +2507,84 @@ mod tests {
assert!(!cached.degraded);
}
#[tokio::test]
async fn test_degraded_refresh_after_replacement_drops_retired_capacity() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
let temp = tempfile::TempDir::new().expect("create capacity fixture");
let active = temp.path().join("active");
let replacement = temp.path().join("replacement");
std::fs::create_dir(&active).expect("create active disk");
std::fs::write(active.join("object"), b"abc").expect("write active disk data");
let active = active.to_str().expect("UTF-8 active path");
let replacement_path = replacement.to_str().expect("UTF-8 replacement path");
let mut old = full_two_disk_update();
old.per_disk[0] = disk_entry("active", active, 100, 1);
manager.update_capacity(old, DataSource::Scheduled).await;
let current = vec![
CapacityDiskRef {
endpoint: "active".into(),
drive_path: active.into(),
},
CapacityDiskRef {
endpoint: "replacement".into(),
drive_path: replacement_path.into(),
},
];
assert!(!run_scheduled_capacity_refresh(manager.clone(), current.clone()).await);
let published = manager.get_capacity().await.expect("publish degraded refresh");
assert!(published.degraded);
assert_eq!(published.total_used, 3);
assert!(!manager.can_refresh_dirty_subset().await);
assert_eq!(
select_scheduled_capacity_refresh(&manager, &current).await,
ScheduledCapacityRefresh::Idle
);
std::fs::create_dir(&replacement).expect("make replacement readable");
std::fs::write(replacement.join("object"), b"12345").expect("write replacement disk data");
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![scope_disk("replacement", replacement_path)],
})
.await;
assert!(run_scheduled_capacity_refresh(manager.clone(), current).await);
let published = manager.get_capacity().await.expect("publish recovered refresh");
assert_eq!(published.total_used, 8);
assert!(!published.degraded);
assert!(manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_timed_out_full_refresh_after_replacement_uses_current_estimate() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
manager.update_capacity(full_two_disk_update(), DataSource::Scheduled).await;
let current = [
CapacityDiskRef {
endpoint: "node-a".into(),
drive_path: "/tmp/disk-a".into(),
},
CapacityDiskRef {
endpoint: "node-c".into(),
drive_path: "/tmp/disk-c".into(),
},
];
let mut timed_out = CapacityUpdate::estimated(160, 2);
timed_out.timed_out = true;
timed_out.per_disk = vec![
disk_entry("node-a", "/tmp/disk-a", 60, 1),
disk_entry("node-c", "/tmp/disk-c", 100, 1),
];
let published = manager
.refresh_or_join_for_disks(DataSource::Scheduled, Some(&current), || async { Ok(timed_out) })
.await
.expect("publish bounded full refresh");
assert_eq!(published.total_used, 160);
assert!(published.timed_out);
assert!(published.is_estimated);
assert!(!manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_update_capacity_degraded_with_empty_per_disk_serves_merged_cache() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
+168 -52
View File
@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(target_os = "linux")]
use super::capacity_manager::get_use_mount_usage;
use super::capacity_manager::{
CapacityUpdate, DiskCapacityUpdate, HybridCapacityManager, get_enable_dynamic_timeout, get_follow_symlinks,
get_max_files_threshold, get_max_timeout, get_min_timeout, get_sample_rate, get_stat_timeout,
@@ -23,6 +25,8 @@ use rustfs_io_metrics::capacity_metrics::{
record_capacity_dynamic_timeout, record_capacity_scan_disk, record_capacity_scan_mode, record_capacity_scan_sampling,
record_capacity_timeout_fallback,
};
#[cfg(target_os = "linux")]
use rustfs_utils::os::MountUsageSnapshot;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::{Component, Path};
@@ -198,10 +202,10 @@ fn is_tmp_trash_metadata_not_found(scan_root: &Path, entry_path: &Path, error_ki
&& components.all(|component| matches!(component, Component::Normal(_)))
}
async fn scan_disk_used_capacity(disk: CapacityDiskRef) -> DiskScanOutcome {
async fn scan_disk_used_capacity(disk: CapacityDiskRef, limits: ScanLimits) -> DiskScanOutcome {
let disk_label = disk_metric_label(&disk);
let start = Instant::now();
let result = get_dir_size_async(Path::new(&disk.drive_path)).await;
let result = get_dir_size_async(Path::new(&disk.drive_path), limits).await;
let disk = CapacityScopeDisk {
endpoint: disk.endpoint,
drive_path: disk.drive_path,
@@ -232,7 +236,14 @@ async fn calculate_data_dir_used_capacity_report(
let mut per_disk = Vec::with_capacity(disks.len());
let concurrency_limit = disks.len().clamp(1, MAX_CAPACITY_SCAN_CONCURRENCY);
let mut scans = stream::iter(disks.iter().cloned().map(scan_disk_used_capacity)).buffer_unordered(concurrency_limit);
let limits = ScanLimits::from_env();
let mut scans = stream::iter(
disks
.iter()
.cloned()
.map(|disk| scan_disk_used_capacity(disk, limits.clone())),
)
.buffer_unordered(concurrency_limit);
while let Some(outcome) = scans.next().await {
match outcome.result {
@@ -351,38 +362,43 @@ pub(crate) async fn select_scheduled_capacity_refresh(
// entries so the dirty gauge reflects local pending work (backlog#1020).
let local_set: HashSet<CapacityScopeDisk> = disks.iter().map(disk_scope_key).collect();
capacity_manager.retain_dirty_disks_within(&local_set).await;
if disks.is_empty() {
return ScheduledCapacityRefresh::Idle;
}
let full_scan = || ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
let cached_topology_matches = capacity_manager.disk_cache_matches(&local_set).await;
if cached_topology_matches == Some(false) {
return full_scan();
}
let dirty_disks = capacity_manager.get_dirty_disks().await;
if dirty_disks.is_empty() {
return if disks.is_empty() || capacity_manager.get_capacity().await.is_some() {
return if capacity_manager.get_capacity().await.is_some() {
ScheduledCapacityRefresh::Idle
} else {
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
full_scan()
};
}
if !capacity_manager.can_refresh_dirty_subset().await {
return ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
if cached_topology_matches.is_none() {
return full_scan();
}
let dirty_set: HashSet<CapacityScopeDisk> = dirty_disks.into_iter().collect();
let dirty_set: HashSet<_> = dirty_disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
let selected: Vec<_> = disks
.iter()
.filter(|disk| dirty_set.contains(&disk_scope_key(disk)))
.filter(|disk| dirty_set.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
.cloned()
.collect();
if selected.is_empty() || selected.len() >= disks.len() {
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
full_scan()
} else {
ScheduledCapacityRefresh::Scan {
disks: selected,
@@ -404,9 +420,13 @@ pub async fn select_capacity_refresh_disks(
}
#[hotpath::measure]
pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subset: bool) -> Result<CapacityUpdate, String> {
pub async fn refresh_capacity_with_scope(
disks: impl AsRef<[CapacityDiskRef]>,
dirty_subset: bool,
) -> Result<CapacityUpdate, String> {
let disks = disks.as_ref();
let scan_started_at = Instant::now();
let report = calculate_data_dir_used_capacity_report(&disks)
let report = calculate_data_dir_used_capacity_report(disks)
.await
.map_err(|e| e.to_string())?;
@@ -421,8 +441,8 @@ pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subs
/// Scan the provided local disk roots and return a summarized used-capacity result.
///
/// This is primarily intended for benchmarks and operational tooling that need to exercise
/// the same scan path as admin capacity queries without going through the full admin stack.
/// This is intended for benchmarks and operational tooling that need the same scan path
/// as background capacity refreshes. Direct filesystem readings do not count files.
pub async fn scan_used_capacity_disks(
disks: &[CapacityDiskRef],
) -> Result<CapacityScanSummary, Box<dyn std::error::Error + Send + Sync>> {
@@ -551,6 +571,8 @@ struct ScanLimits {
sample_rate: usize,
enable_dynamic_timeout: bool,
follow_symlinks: bool,
#[cfg(target_os = "linux")]
mount_usage: Option<Arc<MountUsageSnapshot>>,
}
impl ScanLimits {
@@ -572,6 +594,7 @@ impl ScanLimits {
sample_rate
};
let follow_symlinks = get_follow_symlinks();
Self {
max_files_threshold: get_max_files_threshold(),
base_timeout: get_stat_timeout(),
@@ -579,15 +602,15 @@ impl ScanLimits {
max_timeout: get_max_timeout(),
sample_rate: effective_sample_rate,
enable_dynamic_timeout: get_enable_dynamic_timeout(),
follow_symlinks: get_follow_symlinks(),
follow_symlinks,
#[cfg(target_os = "linux")]
mount_usage: (get_use_mount_usage() && !follow_symlinks).then(|| Arc::new(MountUsageSnapshot::default())),
}
}
}
/// Filesystem-level used bytes for `path`, only when `path` is a dedicated
/// mount point. On a shared filesystem (several logical disks per filesystem,
/// common in dev deployments) statvfs counts unrelated data and would badly
/// overcount, so `None` is returned and callers keep scan-based estimates.
/// Filesystem usage at a device boundary. This check cannot establish sole
/// ownership or distinguish a whole filesystem from a cross-device bind mount.
fn mount_point_used_bytes(path: &Path) -> Option<u64> {
let parent = path.parent()?;
let dedicated = !rustfs_utils::os::same_disk(path.to_str()?, parent.to_str()?).ok()?;
@@ -624,7 +647,7 @@ fn combine_timeout_estimates(seen_estimate: Option<u64>, disk_used: Option<u64>,
/// then propagates the original error, as before.
#[allow(clippy::too_many_arguments)]
fn timeout_fallback_estimate(
path: &Path,
fallback_mount_path: Option<&Path>,
reason: &'static str,
exact_prefix_bytes: u64,
overflow_sampled_bytes: u64,
@@ -639,7 +662,7 @@ fn timeout_fallback_estimate(
let estimated_overflow = estimate_overflow_bytes(overflow_sampled_bytes, overflow_count as u64, sampled_count as u64);
exact_prefix_bytes.saturating_add(estimated_overflow)
});
let disk_used = mount_point_used_bytes(path);
let disk_used = fallback_mount_path.and_then(mount_point_used_bytes);
let used_bytes = combine_timeout_estimates(seen_estimate, disk_used, exact_prefix_bytes)?;
info!(
@@ -699,9 +722,8 @@ impl Drop for ScanCancellationGuard {
}
}
async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::Error> {
async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityScanResult, std::io::Error> {
let path = path.to_path_buf();
let limits = ScanLimits::from_env();
let budget = outer_scan_budget(&limits);
// The blocking thread cannot be killed; on ceiling expiry the caller (and
@@ -734,6 +756,13 @@ async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::
}
fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -> Result<CapacityScanResult, std::io::Error> {
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled before starting",
));
}
let ScanLimits {
max_files_threshold,
base_timeout,
@@ -742,13 +771,28 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
sample_rate: effective_sample_rate,
enable_dynamic_timeout,
follow_symlinks,
..
} = *limits;
{
if !path.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Directory not found: {:?}", path),
));
#[cfg(target_os = "linux")]
if let Some(mount_usage) = &limits.mount_usage {
let start_time = Instant::now();
let used_bytes = mount_usage.used_bytes(path);
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled while reading mount usage",
));
}
if let Some(used_bytes) = used_bytes {
record_capacity_scan_mode("mount_usage");
return Ok(CapacityScanResult {
used_bytes,
is_estimated: true,
scan_duration: start_time.elapsed(),
..Default::default()
});
}
}
// Resolve the scan root before walking. A drive_path that is itself a
@@ -761,7 +805,13 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
.map_err(|err| std::io::Error::new(err.kind(), format!("failed to resolve scan root {path:?}: {err}")))?;
let path = resolved_root.as_path();
// Opt-in scans that rejected a mount must not count its whole filesystem on timeout.
#[cfg(target_os = "linux")]
let fallback_mount_path = limits.mount_usage.is_none().then_some(path);
#[cfg(not(target_os = "linux"))]
let fallback_mount_path = Some(path);
let start_time = Instant::now();
let mut exact_prefix_bytes = 0u64;
let mut overflow_sampled_bytes = 0u64;
let mut file_count = 0usize;
@@ -816,7 +866,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
Ok(half_elapsed) => half_elapsed,
Err(e) => {
if let Some(result) = timeout_fallback_estimate(
path,
fallback_mount_path,
"timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -989,7 +1039,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
if let Err(e) = progress_monitor.update_and_check_timeout(file_count, avg_size) {
if let Some(result) = timeout_fallback_estimate(
path,
fallback_mount_path,
"final_timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -1220,6 +1270,8 @@ mod tests {
sample_rate: 3,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
};
let result =
@@ -1236,7 +1288,7 @@ mod tests {
#[test]
fn test_timeout_fallback_is_marked_for_scheduler_backoff() {
let temp_dir = tempfile::TempDir::new().expect("capacity scan tempdir should be created");
let result = timeout_fallback_estimate(temp_dir.path(), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
let result = timeout_fallback_estimate(Some(temp_dir.path()), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
.expect("sampled timeout should produce a fallback estimate");
assert!(result.timed_out);
@@ -1248,7 +1300,7 @@ mod tests {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 0);
assert_eq!(size.file_count, 0);
}
@@ -1265,7 +1317,7 @@ mod tests {
file.write_all(b"Hello, World!").unwrap();
drop(file);
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 13);
assert_eq!(size.file_count, 1);
}
@@ -1284,7 +1336,7 @@ mod tests {
file.write_all(b"test").unwrap();
}
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 40);
assert_eq!(size.file_count, 10);
}
@@ -1309,14 +1361,14 @@ mod tests {
f2.write_all(b"content2").unwrap();
drop(f2);
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 16);
assert_eq!(size.file_count, 2);
}
#[tokio::test]
async fn test_get_dir_size_async_nonexistent_directory() {
let result = get_dir_size_async(Path::new("/nonexistent/path")).await;
let result = get_dir_size_async(Path::new("/nonexistent/path"), ScanLimits::from_env()).await;
assert!(result.is_err());
}
@@ -1424,12 +1476,45 @@ mod tests {
assert_eq!(combine_timeout_estimates(None, None, 40), None);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_point_used_bytes_rejects_shared_filesystem_path() {
// A tempdir lives on the same filesystem as its parent, so statvfs
// must not be trusted as a per-disk proxy there.
let temp_dir = tempfile::TempDir::new().unwrap();
assert_eq!(mount_point_used_bytes(temp_dir.path()), None);
fn test_mount_usage_keeps_directory_scan_on_shared_filesystem() {
let temp_dir = tempfile::TempDir::new().expect("create shared-filesystem scan root");
std::fs::write(temp_dir.path().join("object"), b"object bytes").expect("write object fixture");
let limits = ScanLimits {
mount_usage: Some(Arc::new(MountUsageSnapshot::default())),
..tight_limits(Duration::from_secs(60))
};
let scan = scan_dir_blocking(temp_dir.path(), &limits, &AtomicBool::new(false)).expect("scan shared directory");
assert_eq!(scan.used_bytes, 12);
assert_eq!(scan.file_count, 1);
assert!(!scan.is_estimated);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_usage_completes_without_walk_budget() {
// Docker and normal Linux hosts mount /dev/shm as a separate tmpfs.
let path = Path::new("/dev/shm");
let mount_usage = Arc::new(MountUsageSnapshot::default());
if mount_usage.used_bytes(path).is_none() {
return;
}
let limits = ScanLimits {
mount_usage: Some(mount_usage),
..tight_limits(Duration::ZERO)
};
let temp_dir = tempfile::TempDir::new().expect("create symlink fixture directory");
let drive_link = temp_dir.path().join("drive");
std::os::unix::fs::symlink(path, &drive_link).expect("link to mount root");
for root in [path, drive_link.as_path()] {
let scan = scan_dir_blocking(root, &limits, &AtomicBool::new(false)).expect("read usage at a mount root");
assert!(scan.is_estimated);
assert!(!scan.timed_out);
assert!(!scan.metadata_incomplete);
assert_eq!(scan.file_count, 0);
assert_eq!(scan.metadata_reads, 0);
}
}
#[test]
@@ -1452,6 +1537,8 @@ mod tests {
sample_rate: 1,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
}
}
@@ -1851,6 +1938,35 @@ mod tests {
assert_eq!(selected.len(), 1);
assert_eq!(selected[0].endpoint, "disk-2");
assert_eq!(selected[0].drive_path, "/tmp/disk-2");
let replacement = vec![
disks[0].clone(),
CapacityDiskRef {
endpoint: "disk-3".into(),
drive_path: "/tmp/disk-3".into(),
},
];
// Replacing a disk changes membership even when the disk count stays
// the same and the only dirty mark belonged to the removed disk.
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement.clone(),
dirty_subset: false,
}
);
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![disk_scope_key(&replacement[1])],
})
.await;
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement,
dirty_subset: false,
}
);
}
#[cfg(unix)]
@@ -1869,7 +1985,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("false"))], async {
get_dir_size_async(scan_dir.path()).await
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
})
.await
.unwrap();
@@ -1894,7 +2010,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("true"))], async {
get_dir_size_async(scan_dir.path()).await
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
})
.await
.unwrap();
+15 -10
View File
@@ -102,9 +102,14 @@ async fn accept_peer(listener: TcpListener) -> io::Result<TcpStream> {
Ok(socket)
}
async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, error_resets: Arc<AtomicUsize>) -> io::Result<()> {
async fn delayed_response_peer(
listener: TcpListener,
ready: mpsc::Sender<()>,
error_resets: Arc<AtomicUsize>,
concurrency_limit: usize,
) -> io::Result<()> {
let mut socket = accept_peer(listener).await?;
let mut cancelled = Vec::with_capacity(INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
let mut cancelled = Vec::with_capacity(concurrency_limit);
let mut resets = HashSet::new();
let mut probe = None;
loop {
@@ -118,9 +123,9 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
let credit = u32::try_from(frame.payload.len()).expect("bounded DATA frame").to_be_bytes();
write_frame(&mut socket, WINDOW_UPDATE, 0, 0, &credit).await?;
}
HEADERS if cancelled.len() < INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT => {
HEADERS if cancelled.len() < concurrency_limit => {
cancelled.push(frame.stream);
if cancelled.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
if cancelled.len() == concurrency_limit {
ready.send(()).await.map_err(|_| io::Error::other("test driver stopped"))?;
}
}
@@ -140,7 +145,7 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
_ => {}
}
if let Some(stream) = probe
&& resets.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT
&& resets.len() == concurrency_limit
{
// A raw peer controls bytes already in flight at cancellation. A normal
// server would consume RST_STREAM and suppress these delayed responses.
@@ -155,12 +160,12 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e
}
}
async fn assert_cancelled_responses_are_ignored(bulk: bool) {
async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: usize) {
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind isolated peer");
let address = format!("http://{}", listener.local_addr().expect("peer address"));
let (ready_tx, mut ready_rx) = mpsc::channel(1);
let error_resets = Arc::new(AtomicUsize::new(0));
let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone()));
let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone(), concurrency_limit));
let cache_key = if bulk {
super::bulk_cache_key(&address, 0)
} else {
@@ -173,7 +178,7 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool) {
let mut client = node_service::node_service_client::NodeServiceClient::new(channel);
for batch in 0..BATCHES {
let mut requests = JoinSet::new();
for _ in 0..INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
for _ in 0..concurrency_limit {
let mut pending_client = client.clone();
requests.spawn(async move { pending_client.read_version(node_service::ReadVersionRequest::default()).await });
}
@@ -203,14 +208,14 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool) {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn cancelled_metadata_responses_keep_the_shared_channel_usable() {
assert_cancelled_responses_are_ignored(false).await;
assert_cancelled_responses_are_ignored(false, INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn cancelled_metadata_responses_keep_the_bulk_channel_usable() {
temp_env::async_with_vars(
[(rustfs_config::ENV_INTERNODE_BULK_CONCURRENCY_LIMIT, Some("64"))],
assert_cancelled_responses_are_ignored(true),
assert_cancelled_responses_are_ignored(true, 64),
)
.await;
}
+14 -11
View File
@@ -3836,7 +3836,7 @@ fn complete_pending_rebuild_on_cache_hit(dial_addr: &str, cache_key: &str) -> bo
}
// Limits transport response futures; client RPC metrics separately cover unary body decoding.
pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 64;
pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 256;
// Quorum reads cancel surplus metadata RPCs in bursts. Keep bounded reset state
// for their in-flight replies through the HTTP/2 grace period without spending
@@ -5929,7 +5929,7 @@ mod tests {
);
assert_eq!(
checked_rpc_window(internode_rpc_http2_stream_window()).expect("control setting"),
Some(1024 * 1024)
Some(rustfs_config::DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE)
);
},
)
@@ -6024,17 +6024,20 @@ mod tests {
#[tokio::test]
async fn get_channel_for_class_bulk_reuses_control_cache_when_isolation_disabled() {
let _test_guard = TLS02_TEST_LOCK.lock().await;
// Isolation defaults off, so a Bulk request must reuse the control channel keyed by the
// bare address and must NOT create a separate bulk-keyed entry (zero behavior change).
let addr = "http://get-channel-isolation-off-test";
let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
cache_connection(addr.to_string(), channel).await;
temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CHANNEL_ISOLATION, Some("false"))], async {
// When isolation is explicitly disabled, a Bulk request must reuse the control channel
// keyed by the bare address and must NOT create a separate bulk-keyed entry.
let addr = "http://get-channel-isolation-off-test";
let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy();
cache_connection(addr.to_string(), channel).await;
let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await;
assert!(acquired.is_ok());
assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await);
let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await;
assert!(acquired.is_ok());
assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await);
evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await;
evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await;
})
.await;
}
}
+89 -5
View File
@@ -855,6 +855,10 @@ fn classify_transport_error(
return InternodeHttpErrorKind::BodyStreamAborted;
}
if let Some(kind) = find_request_phase_close_in_chain(err) {
return kind;
}
InternodeHttpErrorKind::Unknown
}
@@ -864,8 +868,13 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>() {
match io_err.kind() {
io::ErrorKind::ConnectionRefused => return Some(InternodeHttpErrorKind::ConnectionRefused),
io::ErrorKind::ConnectionReset | io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionAborted => {
io::ErrorKind::ConnectionRefused | io::ErrorKind::AddrNotAvailable => {
return Some(InternodeHttpErrorKind::ConnectionRefused);
}
io::ErrorKind::ConnectionReset
| io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::NotConnected => {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
io::ErrorKind::TimedOut => return Some(InternodeHttpErrorKind::ConnectTimeout),
@@ -875,9 +884,31 @@ fn find_transport_error_kind_in_chain(err: &(dyn std::error::Error + 'static)) -
_ => {}
}
}
if current
.downcast_ref::<hyper::Error>()
.is_some_and(hyper::Error::is_incomplete_message)
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>() {
if hyper_err.is_body_write_aborted() {
return Some(InternodeHttpErrorKind::BodyStreamAborted);
}
if hyper_err.is_incomplete_message() {
return Some(InternodeHttpErrorKind::ConnectionReset);
}
}
source = current.source();
}
None
}
/// Map pooled HTTP/1.1 request-dispatch closes (`is_closed` / `is_canceled` / `UnexpectedEof`)
/// after `is_body` has been checked so response-body truncations retain `BodyStreamAborted`.
fn find_request_phase_close_in_chain(err: &(dyn std::error::Error + 'static)) -> Option<InternodeHttpErrorKind> {
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(current) = source {
if let Some(io_err) = current.downcast_ref::<io::Error>()
&& io_err.kind() == io::ErrorKind::UnexpectedEof
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
if let Some(hyper_err) = current.downcast_ref::<hyper::Error>()
&& (hyper_err.is_closed() || hyper_err.is_canceled())
{
return Some(InternodeHttpErrorKind::ConnectionReset);
}
@@ -2187,6 +2218,8 @@ mod tests {
io::ErrorKind::ConnectionReset,
io::ErrorKind::BrokenPipe,
io::ErrorKind::ConnectionAborted,
io::ErrorKind::UnexpectedEof,
io::ErrorKind::NotConnected,
] {
let err = WrapperError::new("transport", Some(io_source(io_kind)));
assert_eq!(
@@ -2197,6 +2230,57 @@ mod tests {
}
}
#[test]
fn classify_io_addr_not_available_maps_to_refused() {
let err = WrapperError::new("ephemeral port exhausted", Some(io_source(io::ErrorKind::AddrNotAvailable)));
assert_eq!(
classify_transport_error(&err, false, false, false),
InternodeHttpErrorKind::ConnectionRefused
);
}
#[tokio::test]
async fn early_503_during_streaming_upload_remains_retryable() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("peer listener should bind");
let address = listener.local_addr().expect("peer address should be available");
let peer = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.expect("peer should accept");
let mut buf = [0_u8; 1024];
let _ = socket.read(&mut buf).await.expect("peer should read initial headers");
let _ = socket
.write_all(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.await;
let _ = socket.shutdown().await;
});
let mut writer =
HttpWriter::new(format!("http://{address}/rustfs/rpc/put_file_stream_v1"), Method::PUT, HeaderMap::new())
.await
.expect("internode writer should be created");
let payload = vec![b'x'; 4 * 1024 * 1024];
let mut final_err = None;
if let Err(err) = writer.write_all(&payload).await {
final_err = Some(err);
} else if let Err(err) = writer.shutdown().await {
final_err = Some(err);
}
let error = final_err.expect("early 503 close must fail streaming upload");
let source = error
.get_ref()
.and_then(|source| source.downcast_ref::<InternodeHttpError>())
.expect("streaming failure must preserve InternodeHttpError");
assert!(
source.kind().is_retryable(),
"expected retryable classification on early 503 body abort, got {:?}",
source.kind()
);
peer.await.expect("peer should finish");
}
#[test]
fn classify_io_unreachable_variants() {
for io_kind in [io::ErrorKind::HostUnreachable, io::ErrorKind::NetworkUnreachable] {
+2
View File
@@ -70,6 +70,8 @@ pub struct PartInfo {
pub size: usize,
pub etag: Option<String>,
pub actual_size: i64,
/// Checksums recorded when the part was uploaded, keyed by algorithm name.
pub checksums: Option<HashMap<String, String>>,
}
#[derive(Debug, Clone, Default)]
+109 -23
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::{DiskInfo, IOStats, fs_type::get_fs_type};
use rustix::fs::statfs;
use std::collections::BTreeSet;
use rustix::fs::{AtFlags, Mode, OFlags, StatFs, StatxAttributes, StatxFlags, fstatfs, open, statfs, statx};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, Error, ErrorKind, Read};
@@ -27,27 +27,10 @@ static BAVAIL_GT_BFREE_WARNING_PATHS: OnceLock<Mutex<BTreeSet<PathBuf>>> = OnceL
/// Returns total and free bytes available in a directory, e.g. `/`.
pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
// Use statfs on Linux to get access to f_type (filesystem magic number)
let stat = statfs(p.as_ref())?;
// Linux statfs:
// f_bsize: Optimal transfer block size
// f_blocks: Total data blocks in file system
// f_frsize: Fragment size (since Linux 2.6) - unit for blocks
//
// If f_frsize is > 0, it is the unit for f_blocks, f_bfree, f_bavail.
// Otherwise f_bsize is used.
let bsize = if stat.f_frsize > 0 {
stat.f_frsize as u64
} else {
stat.f_bsize as u64
};
let bfree = stat.f_bfree as u64;
let bavail = stat.f_bavail as u64;
let blocks = stat.f_blocks as u64;
let (total, free, used) = calculate_space_usage(blocks, bfree, bavail, bsize, p.as_ref())?;
let st = rustix::fs::stat(p.as_ref())?;
let path = p.as_ref();
let stat = statfs(path)?;
let (total, free, used) = statfs_space_usage(&stat, path)?;
let st = rustix::fs::stat(path)?;
Ok(DiskInfo {
total,
@@ -62,6 +45,84 @@ pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
})
}
fn statfs_space_usage(stat: &StatFs, path: &Path) -> io::Result<(u64, u64, u64)> {
// Block counts are in fragment-size units when the kernel provides them.
let block_size = if stat.f_frsize > 0 { stat.f_frsize } else { stat.f_bsize };
calculate_space_usage(stat.f_blocks, stat.f_bfree, stat.f_bavail, block_size as u64, path)
}
/// Snapshot of Linux whole-filesystem mount eligibility for one refresh.
///
/// The mount table is read lazily when the first candidate mount root is
/// probed. The caller is responsible for ensuring exclusive use of the filesystem.
#[derive(Debug, Default)]
pub struct MountUsageSnapshot(OnceLock<Option<HashMap<u64, (u32, u32)>>>);
impl MountUsageSnapshot {
/// Return filesystem-reported used bytes for a directory at an eligible mount root.
///
/// Direct accounting is supported for XFS, the ext family, and tmpfs.
/// Returns `None` when the mount or its filesystem type is ineligible
/// or the kernel cannot identify or read the mounted filesystem.
pub fn used_bytes(&self, path: &Path) -> Option<u64> {
let directory = open(path, OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).ok()?;
let stat = statx(&directory, "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID).ok()?;
if !StatxFlags::from_bits_retain(stat.stx_mask).contains(StatxFlags::MNT_ID)
|| !stat.stx_attributes.contains(StatxAttributes::MOUNT_ROOT)
{
return None;
}
let mounts = self
.0
.get_or_init(|| {
let mountinfo = fs::read("/proc/self/mountinfo").ok()?;
eligible_usage_mounts(&String::from_utf8_lossy(&mountinfo))
})
.as_ref()?;
if mounts.get(&stat.stx_mnt_id) != Some(&(stat.stx_dev_major, stat.stx_dev_minor)) {
return None;
}
// Read the same mount that was classified, even if the path was replaced.
let stat = fstatfs(directory).ok()?;
if !supports_direct_mount_usage(stat.f_type as u64) {
return None;
}
let (_, _, used) = statfs_space_usage(&stat, path).ok()?;
Some(used)
}
}
fn supports_direct_mount_usage(fs_type: u64) -> bool {
// Distinct mount and device IDs do not establish independent block
// accounting on filesystems that share a pool across subvolumes.
matches!(get_fs_type(fs_type), "XFS" | "EXT4" | "TMPFS")
}
fn eligible_usage_mounts(mountinfo: &str) -> Option<HashMap<u64, (u32, u32)>> {
let mut devices = HashMap::new();
let mut parents = HashSet::new();
for line in mountinfo.lines() {
let mut fields = line.split_ascii_whitespace();
let id: u64 = fields.next()?.parse().ok()?;
let parent: u64 = fields.next()?.parse().ok()?;
let (major, minor) = fields.next()?.split_once(':')?;
let device = (major.parse().ok()?, minor.parse().ok()?);
let root = fields.next()?;
parents.insert(parent);
// A second view of the same device may alias accounting for the whole filesystem.
devices
.entry(device)
.and_modify(|mount| *mount = None)
.or_insert((root == "/").then_some(id));
}
Some(
devices
.into_iter()
.filter_map(|(device, id)| id.filter(|id| !parents.contains(id)).map(|id| (id, device)))
.collect(),
)
}
fn calculate_space_usage(blocks: u64, bfree: u64, bavail: u64, bsize: u64, path: &Path) -> std::io::Result<(u64, u64, u64)> {
let available = if bfree < bavail {
if should_warn_bavail_greater_than_bfree(path) {
@@ -450,6 +511,31 @@ mod tests {
assert_eq!(mountinfo_path(line), Some("/data/replacement"));
}
#[test]
fn mount_usage_requires_a_unique_whole_filesystem_with_no_child_mounts() {
let mountinfo = "\
1 0 0:1 / / rw - overlay overlay rw\n\
2 1 0:2 / /data/whole rw - tmpfs tmpfs rw\n\
3 1 0:3 /subdir /data/bind rw - tmpfs tmpfs rw\n\
4 1 0:4 / /data/parent rw - tmpfs tmpfs rw\n\
5 4 0:5 / /data/parent/child rw - tmpfs tmpfs rw\n\
6 1 0:6 / /data/alias1 rw - tmpfs tmpfs rw\n\
7 1 0:6 / /data/alias2 rw - tmpfs tmpfs rw";
assert_eq!(eligible_usage_mounts(mountinfo), Some(HashMap::from([(2, (0, 2)), (5, (0, 5))])));
assert!(eligible_usage_mounts("1 0 no-device /").is_none());
}
#[test]
fn mount_usage_uses_only_filesystems_with_independent_block_accounting() {
assert!(supports_direct_mount_usage(0x58465342)); // XFS
assert!(supports_direct_mount_usage(0xEF53)); // ext family
assert!(supports_direct_mount_usage(0x01021994)); // tmpfs
assert!(!supports_direct_mount_usage(0x9123683E)); // Btrfs
assert!(!supports_direct_mount_usage(0x2FC12FC1)); // ZFS
assert!(!supports_direct_mount_usage(0x794C7630)); // OverlayFS
assert!(!supports_direct_mount_usage(0x6969)); // NFS
}
#[test]
fn reject_relative_path_for_cross_device_validation() {
let err = ensure_no_sub_mounts("relative/path", &[]).unwrap_err();
+3 -1
View File
@@ -24,7 +24,9 @@ mod unix;
mod windows;
#[cfg(target_os = "linux")]
pub use linux::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
pub use linux::{
MountUsageSnapshot, check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk,
};
#[cfg(all(unix, not(target_os = "linux")))]
pub use unix::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
+32 -36
View File
@@ -13,7 +13,7 @@
# limitations under the License.
services:
# RustFS main service
# RustFS single-node single-disk (SNSD) service
rustfs:
image: rustfs/rustfs:latest
container_name: rustfs-server
@@ -23,31 +23,29 @@ services:
security_opt:
- "no-new-privileges:true"
ports:
- "9000:9000" # S3 API port
- "9001:9001" # Console port
- "${RUSTFS_S3_PORT:-9000}:9000" # S3 API port
- "${RUSTFS_CONSOLE_PORT:-9001}:9001" # Console port
environment:
- RUSTFS_VOLUMES=/data/rustfs{0...3}
- RUSTFS_VOLUMES=/data
- RUSTFS_ADDRESS=0.0.0.0:9000
- RUSTFS_CONSOLE_ADDRESS=0.0.0.0:9001
- RUSTFS_CONSOLE_ENABLE=true
- RUSTFS_CONSOLE_CORS_ALLOWED_ORIGINS=*
- RUSTFS_ACCESS_KEY=rustfsadmin # CHANGEME
- RUSTFS_SECRET_KEY=rustfsadmin # CHANGEME
- RUSTFS_ACCESS_KEY=${RUSTFS_ACCESS_KEY:-rustfsadmin} # CHANGEME
- RUSTFS_SECRET_KEY=${RUSTFS_SECRET_KEY:-rustfsadmin} # CHANGEME
- RUSTFS_OBS_LOGGER_LEVEL=info
- RUSTFS_OBS_LOG_DIRECTORY=/app/logs
- RUSTFS_OBS_LOG_DIRECTORY=/logs
# Optional TLS:
# - mount your cert directory to /opt/tls
# - set RUSTFS_TLS_PATH=/opt/tls
# - when TLS is enabled, health checks automatically switch to HTTPS
# Keep strict disk topology checks enabled by default.
# For local testing only, set `RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true` explicitly.
- RUSTFS_UNSAFE_BYPASS_DISK_CHECK=${RUSTFS_UNSAFE_BYPASS_DISK_CHECK:-false}
volumes:
- rustfs_data_0:/data/rustfs0
- rustfs_data_1:/data/rustfs1
- rustfs_data_2:/data/rustfs2
- rustfs_data_3:/data/rustfs3
- logs:/app/logs
- rustfs_data:/data
- logs:/logs
ulimits:
nofile:
soft: 65535
hard: 65535
networks:
- rustfs-network
restart: unless-stopped
@@ -63,21 +61,21 @@ services:
test:
[
"CMD",
"sh", "-ec",
"host=\"$${RUSTFS_HEALTHCHECK_HOST:-127.0.0.1}\"; scheme=\"http\"; set -- -fsS; \
"sh",
"-ec",
"host=\"$${RUSTFS_HEALTHCHECK_HOST:-127.0.0.1}\"; scheme=\"http\"; set -- -fsS --connect-timeout 3 --max-time 5; \
if [ -n \"$${RUSTFS_TLS_PATH:-}\" ]; then \
scheme=\"https\"; \
ca_path=\"$${RUSTFS_HEALTHCHECK_CA:-}\"; \
if [ -z \"$${ca_path}\" ] && [ -f /opt/tls/ca.crt ]; then ca_path=/opt/tls/ca.crt; fi; \
case \"$${host}\" in 127.0.0.1|localhost) strict_host=false ;; *) strict_host=true ;; esac; \
if [ \"$${strict_host}\" = true ] && [ -n \"$${ca_path}\" ]; then \
set -- \"$${@}\" --cacert \"$${ca_path}\" --resolve \"$${host}:9000:127.0.0.1\" --resolve \"$${host}:9001:127.0.0.1\"; \
set -- \"$${@}\" --cacert \"$${ca_path}\" --resolve \"$${host}:9000:127.0.0.1\"; \
else \
set -- \"$${@}\" -k; \
fi; \
fi; \
curl \"$${@}\" \"$${scheme}://$${host}:9000/health\" && \
curl \"$${@}\" \"$${scheme}://$${host}:9001/rustfs/console/health\""
curl \"$${@}\" \"$${scheme}://$${host}:9000/health/ready\""
]
interval: 30s
timeout: 10s
@@ -86,30 +84,28 @@ services:
# RustFS volume permissions fixer service
volume-permission-helper:
image: alpine
image: alpine:3.24
network_mode: none
volumes:
- rustfs_data_0:/data/rustfs0
- rustfs_data_1:/data/rustfs1
- rustfs_data_2:/data/rustfs2
- rustfs_data_3:/data/rustfs3
- logs:/app/logs
- rustfs_data:/data
- logs:/logs
command: >
sh -c "
chown -R 10001:10001 /data/rustfs0 /data/rustfs1 /data/rustfs2 /data/rustfs3 /app/logs &&
echo 'Volume Permissions fixed' &&
exit 0
"
sh -ec '
for dir in /data /logs; do
if [ "$$(stat -c %u:%g "$$dir")" != "10001:10001" ]; then
chown -R 10001:10001 "$$dir"
fi
done
echo "Volume permissions ready"
'
# Permission baseline:
# - default RustFS runtime user is 10001:10001
# - alternatively, run rustfs service with host-matched `user: \"<uid>:<gid>\"`
# - alternatively, run rustfs service with host-matched `user: "<uid>:<gid>"`
restart: "no"
networks:
rustfs-network:
volumes:
rustfs_data_0:
rustfs_data_1:
rustfs_data_2:
rustfs_data_3:
rustfs_data:
logs:
@@ -11,6 +11,10 @@
## Open Items
- `http-opaque-response-headers` HTTP response encoding. Preserve UTF-8 lifecycle rule IDs in x-amz-expiration and UTF-8 Content-Type parameters while the gateway string encoder accepts only ASCII. Remove the RustFS projection after the gateway emits the original opaque bytes in these response headers.
- `metrics-024-recorder` dependency constraint bridge. The workspace still resolves metrics 0.24 for Metrique and its metrics utility. The local crate re-exports metrics 0.25 so all producers share the same recorder. Remove the crate and workspace Cargo patch after every resolved consumer accepts metrics 0.25 directly.
- `9526` NIXL shard reads recognize the exact file-missing response from peers that predate the disk error header. Remove the response-body check once all supported NIXL peers send the header.
- `openidconnect-hmac-signature-width` ID token verification guard: openidconnect 4.1.0 converts decoded HMAC signatures to fixed-size arrays, which panic on unexpected lengths. Check HS256, HS384, and HS512 signature widths before delegating all cryptographic, issuer, audience, expiry, and nonce checks to the upstream verifier. Remove the guard after a supported upstream release returns verification errors for arbitrary HMAC signature lengths.
@@ -98,6 +98,8 @@ For a dedicated Linux test cluster, add the following flags to the ABBA command
Repeat the SSH target and device mapping for every node. Specify the Linux kernel device names of the benchmark volumes. With the queue check enabled, each PUT attempt waits for two consecutive rounds of parallel five-second sampling. Each node must have mean queue depth at most 0.25 and no listed device above 0.75. Queue depth uses the change in weighted I/O milliseconds divided by elapsed monotonic milliseconds. Each attempt records the collected samples in its cell's `node_telemetry/queue_*.tsv`. An unavailable node, invalid counter or timeout fails the attempt before Warp starts. The ABBA drift and regression budgets still apply. [Linux block device counters](https://docs.kernel.org/admin-guide/iostats.html)
The queue TSV also records `completed_writes`, `write_ms_per_op`, and `peak_write_ms_per_op` for the same samples. Write latency divides the change in milliseconds spent writing by the change in completed writes. The node average is weighted by completed writes, and the peak is the highest per-device average among devices with write completions. A window with no completed writes reports zero completions and `NA` for both latency fields. Compare the last two samples of successful attempts across legs to check for different write completion behavior at similarly low queue depths. These fields are diagnostic and the existing queue and drift thresholds still apply.
Use the same persistent lock file for cooperating commands on the same controller. An occupied lock makes the runner exit before deployment. Keep the lock file in place so every command locks the same inode. The controller runs the restore hook once after any deployment attempt, including a failed deploy, interrupted workload or failed gate. The hook receives `HOTPATH_ABBA_DATASET_NAMESPACE` and `HOTPATH_ABBA_OUT_DIR`. It owns the site-specific cleanup and must reconcile partially completed remote deployment, restore services and verify readiness before returning. Use bounded, synchronous hooks on the controller. The runner stops the active controller process group before restoration, holds the lock through restoration and records `restore.log` and `restore.status`. Managed runs require `flock` and a `timeout` implementation supporting `--foreground` and `--kill-after`.
For diagnostic PUT runs using `--service-prometheus-query-url`, add `--require-rename-rank-metrics` after enabling PUT stage metrics and warming that deployment. The service snapshots must include `rustfs_s3_put_object_rename_disk_wait_completion_ms_count` for both `position="quorum_first"` and `position="quorum_tail"`. Each group must advance across the attempt without series resets or changes in membership. Use the existing query or service-name filter to scope snapshots to the benchmark service. These counters describe completion order. Per-request attribution also needs a join with the coordinator's ACK decision.
+1
View File
@@ -65,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 |
+238 -97
View File
@@ -796,9 +796,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.162.0"
version = "1.163.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -825,7 +825,7 @@ dependencies = [
"lru",
"percent-encoding",
"regex-lite",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
"url",
]
@@ -924,7 +924,7 @@ dependencies = [
"http",
"p256",
"percent-encoding",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"time",
"tracing",
@@ -959,7 +959,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
]
@@ -1364,9 +1364,9 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "byteorder"
version = "1.5.0"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
[[package]]
name = "bytes"
@@ -1512,7 +1512,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -3014,7 +3014,7 @@ checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"subtle",
]
@@ -3636,7 +3636,7 @@ checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
dependencies = [
"cfg-if",
"libc",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -3656,9 +3656,9 @@ checksum = "b4db3c637c6c3cf7120ab641f12f83aa19dfa015679ac1b29e16b15684c7a3e3"
[[package]]
name = "http"
version = "1.5.0"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05"
dependencies = [
"bytes",
"itoa",
@@ -3804,7 +3804,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
"windows-core 0.62.2",
]
[[package]]
@@ -3957,9 +3957,9 @@ dependencies = [
[[package]]
name = "io-uring"
version = "0.7.15"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@@ -3975,7 +3975,7 @@ dependencies = [
"socket2",
"widestring",
"windows-registry",
"windows-result",
"windows-result 0.4.1",
"windows-sys 0.61.2",
]
@@ -4041,23 +4041,23 @@ dependencies = [
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "jiff"
version = "1.0.3"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f"
checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92"
dependencies = [
"jiff-core 1.0.2",
"jiff-static 1.0.3",
"jiff-core 1.1.0",
"jiff-static 1.1.0",
"jiff-tzdb-platform 1.0.0",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4072,9 +4072,9 @@ dependencies = [
[[package]]
name = "jiff-core"
version = "1.0.2"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f"
checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79"
dependencies = [
"log",
]
@@ -4093,11 +4093,11 @@ dependencies = [
[[package]]
name = "jiff-static"
version = "1.0.3"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8"
checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3"
dependencies = [
"jiff-core 1.0.2",
"jiff-core 1.1.0",
"proc-macro2",
"quote",
"syn 3.0.9",
@@ -4147,7 +4147,7 @@ dependencies = [
"simd_cesu8",
"thiserror",
"walkdir",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4527,9 +4527,9 @@ dependencies = [
[[package]]
name = "metrics"
version = "0.24.6"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2"
checksum = "eb1b882a87a42420c952fbb7173ff4fa5d380b51eb26c95bf77435811201db7a"
dependencies = [
"portable-atomic",
"rapidhash",
@@ -5055,7 +5055,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -5094,7 +5094,7 @@ dependencies = [
"libc",
"redox_syscall 0.5.18",
"smallvec",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -5106,7 +5106,7 @@ dependencies = [
"libc",
"redox_syscall 0.9.5",
"smallvec",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -5422,7 +5422,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.2",
"sha2 0.11.3",
"stringprep",
]
@@ -6170,7 +6170,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -6253,7 +6253,7 @@ dependencies = [
"http",
"md-5",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"xxhash-rust",
]
@@ -6299,7 +6299,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
]
@@ -6317,7 +6317,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
]
@@ -6362,7 +6362,7 @@ dependencies = [
"hyper",
"hyper-rustls",
"hyper-util",
"jiff 1.0.3",
"jiff 1.1.0",
"lazy_static",
"libc",
"md-5",
@@ -6414,7 +6414,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"shadow-rs",
"slab",
"smallvec",
@@ -6432,7 +6432,7 @@ dependencies = [
"urlencoding",
"uuid",
"winapi-util",
"windows-sys 0.61.2",
"windows-sys 0.101.0",
"xxhash-rust",
]
@@ -6476,7 +6476,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"time",
"tokio",
@@ -6492,7 +6492,7 @@ dependencies = [
"arbitrary",
"bytes",
"http",
"jiff 1.0.3",
"jiff 1.1.0",
"libfuzzer-sys",
"quick-xml 0.42.0",
"rustfs-ecstore",
@@ -6510,7 +6510,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"tokio",
"uuid",
@@ -6542,7 +6542,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"twox-hash",
"unicode-normalization",
@@ -6592,9 +6592,9 @@ dependencies = [
[[package]]
name = "rustfs-kafka"
version = "1.4.1"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82dc39ba1a5a9f6b2e49decb0b54c23ebaebdfb08a899307c266694bfd269bf9"
checksum = "d66b41fff6ef985a310f7dac070fda947b7588e56decd837084c41edc24841a0"
dependencies = [
"base64 0.23.1",
"bytes",
@@ -6606,7 +6606,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"socket2",
"thiserror",
"tracing",
@@ -6617,20 +6617,21 @@ dependencies = [
[[package]]
name = "rustfs-kafka-async"
version = "1.4.1"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "684f5e78ea1421bbf915e4cd0515bdefd587cfa281da000e41ae4a434f90195a"
checksum = "7ceb19d7045aa067259792637be2f72c971aece9ccaf7f6c76ec7ac272904d37"
dependencies = [
"base64 0.23.1",
"bytes",
"hmac 0.13.0",
"indexmap",
"kafka-protocol",
"metrics",
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-rustls",
"tracing",
@@ -6654,7 +6655,7 @@ dependencies = [
"chacha20poly1305",
"hex-simd",
"hotpath",
"jiff 1.0.3",
"jiff 1.1.0",
"md-5",
"metrics",
"moka",
@@ -6665,7 +6666,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"thiserror",
"tokio",
@@ -6724,7 +6725,7 @@ dependencies = [
"http",
"humantime",
"hyper",
"jiff 1.0.3",
"jiff 1.1.0",
"reqwest",
"rustfs-signer",
"serde",
@@ -6742,7 +6743,7 @@ dependencies = [
"form_urlencoded",
"hashbrown 0.17.2",
"hotpath",
"jiff 1.0.3",
"jiff 1.1.0",
"metrics",
"percent-encoding",
"quick-xml 0.42.0",
@@ -6795,7 +6796,7 @@ dependencies = [
"base64-simd",
"futures",
"ipnetwork",
"jiff 1.0.3",
"jiff 1.1.0",
"jsonwebtoken",
"moka",
"regex",
@@ -6878,7 +6879,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"tokio",
"tokio-util",
@@ -6919,7 +6920,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"time",
"tokio",
@@ -6971,7 +6972,7 @@ dependencies = [
"futures-core",
"hotpath",
"http",
"jiff 1.0.3",
"jiff 1.1.0",
"lz4",
"lz4_flex",
"memchr",
@@ -7016,7 +7017,7 @@ dependencies = [
name = "rustfs-scanner-metrics"
version = "1.0.8"
dependencies = [
"jiff 1.0.3",
"jiff 1.1.0",
"metrics",
"rmp-serde",
"rustfs-heal-contracts",
@@ -7092,7 +7093,7 @@ dependencies = [
"hotpath",
"hyper",
"hyper-rustls",
"jiff 1.0.3",
"jiff 1.1.0",
"lapin",
"libc",
"metrics",
@@ -7114,7 +7115,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"snap",
"sysinfo",
"thiserror",
@@ -7139,7 +7140,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"serde",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"tokio",
"tracing",
@@ -7148,8 +7149,9 @@ dependencies = [
[[package]]
name = "rustfs-uring"
version = "0.3.0"
source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba"
dependencies = [
"io-uring",
"libc",
@@ -7183,14 +7185,14 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"siphasher",
"snap",
"tokio",
"tracing",
"transform-stream",
"url",
"windows",
"windows 0.101.0",
"zstd 0.14.5",
]
@@ -7551,9 +7553,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.2"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -7784,9 +7786,9 @@ dependencies = [
[[package]]
name = "starshard"
version = "2.4.1"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0883700b50fd0b62120ebc4c07230e02f0cf1ead474c3b3b44eaa13e0a999ea"
checksum = "adc82b6d069d07eb9b6433ccabdaf31ea1508cd240f6fe12284e0dd3d7609bd5"
dependencies = [
"async-trait",
"hashbrown 0.17.2",
@@ -7902,9 +7904,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.4"
version = "0.40.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
dependencies = [
"libc",
"memchr",
@@ -7913,7 +7915,7 @@ dependencies = [
"objc2-io-kit",
"objc2-open-directory",
"rayon",
"windows",
"windows 0.62.2",
]
[[package]]
@@ -8156,7 +8158,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-postgres",
"tokio-rustls",
@@ -8847,10 +8849,24 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
name = "windows"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa86febe1d5f623619e56067e9c6f84c368cf94f9f36df738875a0dc5affd752"
dependencies = [
"windows-collections 0.101.0",
"windows-core 0.101.0",
"windows-future 0.101.0",
"windows-numerics 0.101.0",
"windows-reference",
"windows-time",
]
[[package]]
@@ -8859,7 +8875,16 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
"windows-core 0.62.2",
]
[[package]]
name = "windows-collections"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c988c3f56b2a0cf740d2837950f25c43539ea6c004a5244085ce6749e1c61f29"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
@@ -8868,11 +8893,24 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-core"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27abecb0bac0f1602c4e0d0c885aca58e9a2a25d852135b96e4d0f9daf989aac"
dependencies = [
"windows-implement 0.101.0",
"windows-interface 0.101.0",
"windows-link 0.101.0",
"windows-result 0.101.0",
"windows-strings 0.101.0",
]
[[package]]
@@ -8881,9 +8919,20 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
]
[[package]]
name = "windows-future"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c1de418ec955682054a08c9a2925719c76af9408397fd89fc7c2418bd3b2551"
dependencies = [
"windows-core 0.101.0",
"windows-link 0.101.0",
"windows-threading 0.101.0",
]
[[package]]
@@ -8897,6 +8946,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33a7f9008fbe08b219a4d9b2db1ceff71b9ed7f0e02472a3bf2046a2b258f933"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -8908,20 +8968,56 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67d1b654cf5aa8120c8c796fe6c88f0e0407512c341e83ea7bb65b933b596474"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-link"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
name = "windows-numerics"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d54e417b9761be91da0ab663a5e393e9e54820e55fa9a1d902b978bda3a71ba"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
name = "windows-reference"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0a017bb8eab108f37103deaa4eaad24ce324c30c6f72628a59250be24c87466"
dependencies = [
"windows-core 0.101.0",
"windows-time",
]
[[package]]
@@ -8930,9 +9026,9 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
"windows-result",
"windows-strings",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
@@ -8941,7 +9037,16 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-result"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a02baed928b12dbc90e3a37d1504af179d275e13427510f6bcded0607c9251a7"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8950,7 +9055,16 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3301e29c2a308301e0e84fe4242684b1310864f3e15aba65b4ae41f1a44f7f95"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8968,7 +9082,16 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8993,7 +9116,25 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-threading"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e1e41d72a0564ebe2cbb9487ed918acfc71d541683b84816a424dc3c7939592"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
name = "windows-time"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186ef23b1710095987bf5281bd19e3669934d4353946f24cbdcfd0ed4f2deff6"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
+65 -1
View File
@@ -16,7 +16,7 @@ path = "src/lib.rs"
[dependencies]
arbitrary = { version = "1", features = ["derive"] }
bytes = "1.12.2"
http = "1.5.0"
http = "1.6.0"
jiff = { version = "1.0.2", features = ["serde"] }
libfuzzer-sys = "0.4"
quick-xml = { version = "0.42.0", features = ["serialize", "serde-types", "encoding"] }
@@ -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"
+1 -1
View File
@@ -422,7 +422,7 @@ rustfs-mimalloc = { workspace = true }
[target.'cfg(target_os = "linux")'.dependencies]
libsystemd.workspace = true
rustfs-mimalloc = { workspace = true, features = ["no_thp"] }
rustfs-mimalloc-sys = "0.7.5"
rustfs-mimalloc-sys = "0.7.6"
[target.'cfg(any(all(target_os = "macos", any(target_arch = "x86_64", target_arch = "aarch64")), all(target_os = "linux", target_env = "gnu", any(target_arch = "x86_64", target_arch = "aarch64"))))'.dependencies]
pyroscope = { workspace = true, optional = true, features = ["backend-pprof-rs"] }
+22 -43
View File
@@ -714,44 +714,21 @@ fn summarize_storage_readiness(snapshot: &ClusterReadOnlySnapshot) -> Capability
}
}
fn summarize_listing_readiness(snapshot: &ClusterReadOnlySnapshot) -> CapabilityStatus {
match snapshot
.workload_admission
.entries()
.iter()
.find(|entry| entry.class == WorkloadClass::ForegroundRead)
{
Some(entry) if entry.state == AdmissionState::Open => {
CapabilityStatus::supported().with_reason("foreground read admission is open")
}
Some(entry) => {
let mut reason = format!("foreground read admission is {}", admission_state_label(entry.state));
if let Some(detail) = entry.reason.as_deref() {
reason.push_str(": ");
reason.push_str(detail);
}
CapabilityStatus::unknown().with_reason(reason)
}
None => CapabilityStatus::unknown().with_reason("foreground read admission is not reported"),
}
}
fn summarize_listing_metacache(snapshot: &ClusterReadOnlySnapshot) -> ClusterListingMetacacheStatus {
const HINT: &str = "bucket and prefix attribution is emitted through metacache quorum logs; inspect operation-labelled walk_dir metrics for internode traffic";
let admission = summarize_listing_readiness(snapshot);
let stalls = snapshot.listing_diagnostics.internode_stall_timeouts_total;
let (condition, status) = if admission.state == CapabilityState::Supported {
("healthy", admission)
} else {
(condition_from_capability(&admission), admission)
let diagnostics = snapshot.listing_diagnostics;
let status = match diagnostics.local_budget_has_capacity {
Some(true) => CapabilityStatus::supported().with_reason("local listing budget has capacity"),
Some(false) => CapabilityStatus::unknown().with_reason("local listing budget cannot admit a full walk"),
None => CapabilityStatus::unknown().with_reason("local listing budget is not reported"),
};
ClusterListingMetacacheStatus {
source: "workload_admission+internode_metrics",
condition,
source: "local_listing_budget+internode_metrics",
condition: condition_from_capability(&status),
status,
internode_stall_timeouts_total: stalls,
internode_stall_timeouts_total: diagnostics.internode_stall_timeouts_total,
hint: HINT,
}
}
@@ -1213,6 +1190,7 @@ mod tests {
..Default::default()
},
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: None,
internode_stall_timeouts_total: 2,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot {
@@ -1233,7 +1211,7 @@ mod tests {
assert_eq!(value["components"]["storage"]["source"], "runtime_readiness");
assert_eq!(value["components"]["storage"]["condition"], "degraded");
assert_eq!(value["components"]["peer_health"]["source"], "cluster_peer_health");
assert_eq!(value["components"]["listing"]["source"], "workload_admission+internode_metrics");
assert_eq!(value["components"]["listing"]["source"], "local_listing_budget+internode_metrics");
assert_eq!(value["components"]["listing"]["condition"], "unknown");
assert_eq!(value["components"]["listing"]["internode_stall_timeouts_total"], 2);
assert_eq!(value["pool_meta_write_gate"]["writesReady"], false);
@@ -1309,8 +1287,8 @@ mod tests {
assert_eq!(summary.storage.state, CapabilityState::Supported);
assert_eq!(summary.storage.reason.as_deref(), Some("storage readiness reports ready"));
assert_eq!(summary.peer_health.state, CapabilityState::Unknown);
assert_eq!(summary.listing.state, CapabilityState::Supported);
assert_eq!(summary.listing.reason.as_deref(), Some("foreground read admission is open"));
assert_eq!(summary.listing.state, CapabilityState::Unknown);
assert_eq!(summary.listing.reason.as_deref(), Some("local listing budget is not reported"));
assert_eq!(summary.usage.state, CapabilityState::Unknown);
assert_eq!(summary.usage.reason.as_deref(), Some("no usage cache save result has been reported"));
assert_eq!(summary.rpc_boundary.state, CapabilityState::Supported);
@@ -1342,11 +1320,10 @@ mod tests {
},
rpc_boundary: sample_rpc_boundary_snapshot(),
observability: ObservabilitySnapshot::default(),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![
WorkloadAdmissionSnapshot::new(WorkloadClass::ForegroundRead, AdmissionState::Throttled)
.with_counts(Some(4), Some(8), Some(4))
.with_reason("metacache listing backpressure"),
]),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![WorkloadAdmissionSnapshot::new(
WorkloadClass::ForegroundRead,
AdmissionState::Open,
)]),
runtime_status: ClusterRuntimeStatusSnapshot {
readiness: DependencyReadiness {
storage_ready: false,
@@ -1365,6 +1342,7 @@ mod tests {
..Default::default()
},
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: Some(false),
internode_stall_timeouts_total: 0,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot::default(),
@@ -1383,7 +1361,7 @@ mod tests {
assert_eq!(view.components.listing.status.state, CapabilityState::Unknown);
assert_eq!(
view.components.listing.status.reason.as_deref(),
Some("foreground read admission is throttled: metacache listing backpressure")
Some("local listing budget cannot admit a full walk")
);
assert_eq!(view.components.listing.condition, "unknown");
assert_eq!(view.components.usage.status.state, CapabilityState::Unknown);
@@ -1433,7 +1411,7 @@ mod tests {
}
#[test]
fn cluster_snapshot_listing_component_keeps_historical_stalls_as_evidence() {
fn cluster_snapshot_listing_uses_its_own_budget_while_get_is_saturated() {
let snapshot = ClusterReadOnlySnapshot {
topology: TopologySnapshot::default(),
membership: ClusterMembershipSnapshot::default(),
@@ -1444,7 +1422,7 @@ mod tests {
observability: ObservabilitySnapshot::default(),
workload_admission: WorkloadAdmissionRegistrySnapshot::new(vec![WorkloadAdmissionSnapshot::new(
WorkloadClass::ForegroundRead,
AdmissionState::Open,
AdmissionState::Saturated,
)]),
runtime_status: ClusterRuntimeStatusSnapshot {
readiness: DependencyReadiness::default(),
@@ -1453,6 +1431,7 @@ mod tests {
},
usage_freshness: ClusterUsageFreshnessSnapshot::default(),
listing_diagnostics: ClusterListingDiagnosticsSnapshot {
local_budget_has_capacity: Some(true),
internode_stall_timeouts_total: 2,
},
pool_meta_write_gate: ClusterPoolMetaWriteGateSnapshot::default(),
@@ -1461,7 +1440,7 @@ mod tests {
let component = super::summarize_listing_metacache(&snapshot);
assert_eq!(component.status.state, CapabilityState::Supported);
assert_eq!(component.status.reason.as_deref(), Some("foreground read admission is open"));
assert_eq!(component.status.reason.as_deref(), Some("local listing budget has capacity"));
assert_eq!(component.condition, "healthy");
assert_eq!(component.internode_stall_timeouts_total, 2);
}
+2 -2
View File
@@ -777,8 +777,8 @@ impl DefaultAdminUsecase {
}
pub async fn execute_collect_cluster_read_only_snapshot(&self) -> Option<ClusterReadOnlySnapshot> {
let endpoint_pools = current_endpoints_handle()?;
collect_cluster_read_only_snapshot(&endpoint_pools).await
let context = current_app_context()?;
collect_cluster_read_only_snapshot(&context).await
}
pub fn cluster_snapshot_route(&self) -> &'static str {
+61 -38
View File
@@ -213,22 +213,17 @@ impl Drop for ColdFillDiskPermitMetric {
}
struct GetObjectDiskPermit {
permit: Option<OwnedSemaphorePermit>,
metric: Option<ColdFillDiskPermitMetric>,
_permit: OwnedSemaphorePermit,
_metric: Option<ColdFillDiskPermitMetric>,
}
impl GetObjectDiskPermit {
fn new(permit: OwnedSemaphorePermit) -> Self {
Self {
permit: Some(permit),
metric: current_cold_fill_disk_permit_owner().map(ColdFillDiskPermitMetric::new),
_permit: permit,
_metric: current_cold_fill_disk_permit_owner().map(ColdFillDiskPermitMetric::new),
}
}
fn release(&mut self) {
self.permit.take();
self.metric.take();
}
}
impl From<OwnedSemaphorePermit> for GetObjectDiskPermit {
@@ -237,12 +232,6 @@ impl From<OwnedSemaphorePermit> for GetObjectDiskPermit {
}
}
impl Drop for GetObjectDiskPermit {
fn drop(&mut self) {
self.release();
}
}
fn release_disk_read_permit_if_buffered(disk_permit: &mut Option<GetObjectDiskPermit>, buffered_body: Option<&Bytes>) {
if buffered_body.is_some() {
disk_permit.take();
@@ -708,8 +697,7 @@ const GET_DISK_READ_MIN_WINDOW_BYTES: usize = 64 * 1024;
struct DiskReadLease<R> {
reader: Option<Pin<Box<R>>>,
permit: Option<GetObjectDiskPermit>,
pending: bool,
pending_capacity: usize,
pending: Option<PendingDiskRead>,
closed: bool,
expired: bool,
abandoned: tokio_util::sync::CancellationToken,
@@ -718,7 +706,11 @@ struct DiskReadLease<R> {
window_bytes: usize,
idle_timeout: Duration,
progress_window: Duration,
waker: Option<std::task::Waker>,
}
struct PendingDiskRead {
capacity: usize,
waker: std::task::Waker,
}
impl<R> DiskReadLease<R> {
@@ -771,10 +763,9 @@ impl<R> DiskReadLeaseControl<R> {
let mut state = self.lease.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
state.closed = true;
state.abandoned.cancel();
state.pending = false;
state.reader.take();
state.permit.take();
state.waker.take()
state.pending.take().map(|read| read.waker)
};
if let Some(waker) = waker {
waker.wake();
@@ -805,8 +796,7 @@ impl<R: AsyncRead + Send + 'static> DiskReadPermitReader<R> {
let lease = Arc::new(Mutex::new(DiskReadLease {
reader: Some(Box::pin(inner)),
permit: Some(disk_permit),
pending: false,
pending_capacity: 0,
pending: None,
closed: false,
expired: false,
abandoned: tokio_util::sync::CancellationToken::new(),
@@ -815,7 +805,6 @@ impl<R: AsyncRead + Send + 'static> DiskReadPermitReader<R> {
window_bytes: 0,
idle_timeout,
progress_window: idle_timeout.saturating_mul(2),
waker: None,
}));
let changed = Arc::new(tokio::sync::Notify::new());
tokio::spawn(Self::watch(lease.clone(), changed.clone()));
@@ -823,7 +812,7 @@ impl<R: AsyncRead + Send + 'static> DiskReadPermitReader<R> {
}
async fn watch(lease: Arc<Mutex<DiskReadLease<R>>>, changed: Arc<tokio::sync::Notify>) {
let (reader, permit, pending_capacity, waker, abandoned) = loop {
let (reader, permit, pending, abandoned) = loop {
let next_check = {
let mut state = lease.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if !state.closed {
@@ -831,13 +820,7 @@ impl<R: AsyncRead + Send + 'static> DiskReadPermitReader<R> {
}
if state.closed || state.expired {
state.closed = true;
break (
state.reader.take(),
state.permit.take(),
state.pending.then_some(state.pending_capacity),
state.waker.take(),
state.abandoned.clone(),
);
break (state.reader.take(), state.permit.take(), state.pending.take(), state.abandoned.clone());
}
state.next_check_delay(tokio::time::Instant::now())
};
@@ -846,9 +829,10 @@ impl<R: AsyncRead + Send + 'static> DiskReadPermitReader<R> {
_ = changed.notified() => {},
}
};
if let Some(waker) = waker {
waker.wake();
}
let pending_capacity = pending.map(|read| {
read.waker.wake();
read.capacity
});
if let Some(mut reader) = reader {
if let Some(capacity) = pending_capacity {
// A cancelled response must not release disk admission while a
@@ -889,15 +873,14 @@ impl<R: AsyncRead> AsyncRead for DiskReadPermitReader<R> {
if state.closed {
return Poll::Ready(Ok(()));
}
state.waker = Some(cx.waker().clone());
let filled_before = buf.filled().len();
state.pending_capacity = buf.remaining();
let capacity = buf.remaining();
let poll = match state.reader.as_mut() {
Some(reader) => reader.as_mut().poll_read(cx, buf),
None => return Poll::Ready(Ok(())),
};
state.pending = poll.is_pending();
if let Poll::Ready(result) = &poll {
state.pending = None;
let progress = buf.filled().len() - filled_before;
if result.is_err() || progress == 0 {
state.closed = true;
@@ -909,6 +892,14 @@ impl<R: AsyncRead> AsyncRead for DiskReadPermitReader<R> {
state.last_progress = tokio::time::Instant::now();
state.window_bytes = state.window_bytes.saturating_add(progress);
}
} else if let Some(read) = state.pending.as_mut() {
read.capacity = capacity;
read.waker.clone_from(cx.waker());
} else {
state.pending = Some(PendingDiskRead {
capacity,
waker: cx.waker().clone(),
});
}
poll
}
@@ -918,7 +909,7 @@ impl<R> Drop for DiskReadPermitReader<R> {
fn drop(&mut self) {
let mut state = self.lease.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
state.closed = true;
if !state.pending {
if state.pending.is_none() {
state.reader.take();
state.permit.take();
}
@@ -12527,6 +12518,38 @@ mod tests {
);
}
#[tokio::test]
async fn disk_read_permit_reader_does_not_retain_ready_read_waker() {
struct ReadyReadWaker(AtomicUsize);
impl std::task::Wake for ReadyReadWaker {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, AtomicOrdering::Relaxed);
}
}
let waker_owner = Arc::new(ReadyReadWaker(AtomicUsize::new(0)));
let waker = std::task::Waker::from(Arc::clone(&waker_owner));
let mut context = Context::from_waker(&waker);
let semaphore = Arc::new(tokio::sync::Semaphore::new(1));
let permit = Arc::clone(&semaphore).try_acquire_owned().expect("disk permit");
let mut reader = DiskReadPermitReader::new(std::io::Cursor::new(b"data"), permit.into());
let mut byte = [0_u8; 1];
let mut read_buf = ReadBuf::new(&mut byte);
assert!(matches!(
Pin::new(&mut reader).poll_read(&mut context, &mut read_buf),
Poll::Ready(Ok(()))
));
assert_eq!(read_buf.filled(), b"d");
assert_eq!(Arc::strong_count(&waker_owner), 2, "a synchronous read has nobody to wake");
assert_eq!(semaphore.available_permits(), 0, "more data remains");
reader.lease_control().abandon();
assert_eq!(waker_owner.0.load(AtomicOrdering::Relaxed), 0, "no read was pending");
assert_eq!(semaphore.available_permits(), 1, "abandonment returns the permit");
}
#[tokio::test]
async fn disk_read_permit_reader_releases_permit_at_eof() {
use tokio::io::AsyncReadExt;
+1 -1
View File
@@ -53,7 +53,7 @@ pub(crate) struct ResponseEtag {
impl ResponseEtag {
pub(crate) fn to_http_header(&self) -> Result<http::HeaderValue, http::header::InvalidHeaderValue> {
let prefix = if self.weak { "W/" } else { "" };
http::HeaderValue::from_str(&format!("{prefix}\"{}\"", self.opaque))
http::HeaderValue::from_bytes(format!("{prefix}\"{}\"", self.opaque).as_bytes())
}
pub(super) fn from_stored(value: &str) -> Self {
+2 -1
View File
@@ -85,7 +85,8 @@ pub(crate) fn post_metadata_headers(
}
}
if let Some(value) = content_type {
let wire = HeaderValue::from_str(value).map_err(|_| s3_error!(InvalidArgument, "Invalid POST content field"))?;
let wire =
HeaderValue::from_bytes(value.as_bytes()).map_err(|_| s3_error!(InvalidArgument, "Invalid POST content field"))?;
let base = value.split(';').next().unwrap_or(value).trim();
if !base.is_ascii() {
return Err(s3_error!(InvalidArgument, "Invalid POST content field"));
+2 -2
View File
@@ -740,7 +740,7 @@ fn build_put_object_expiration_header(event: &lifecycle::Event) -> Option<String
// parser, which rejects `2026-10-02T00:00:00Z` and drops the metadata.
let expiry_date = format_http_date(&expire_time).ok()?;
let value = format!("expiry-date=\"{}\", rule-id=\"{}\"", expiry_date, event.rule_id);
http::HeaderValue::from_str(&value).is_ok().then_some(value)
http::HeaderValue::from_bytes(value.as_bytes()).is_ok().then_some(value)
}
pub(super) fn internal_object_info_lookup_opts(mut opts: ObjectOptions) -> ObjectOptions {
@@ -2278,7 +2278,7 @@ mod tests {
}
event.rule_id = "保留策略".to_owned();
let header = build_put_object_expiration_header(&event).expect("valid UTF-8 IDs remain supported");
assert!(http::HeaderValue::from_str(&header).is_ok());
assert!(http::HeaderValue::from_bytes(header.as_bytes()).is_ok());
assert!(header.contains("保留策略"));
}
+18 -17
View File
@@ -13,6 +13,7 @@
// limitations under the License.
use crate::runtime_capabilities::runtime_observability_snapshot;
use crate::runtime_sources::AppContext;
use crate::server::snapshot_dependency_readiness_report;
use crate::shared_types::{DependencyReadiness, DependencyReadinessReport, ReadinessDegradedReason};
use crate::storage_api::cluster::EndpointServerPools;
@@ -24,7 +25,7 @@ use crate::storage_api::cluster::control_plane::{
};
use crate::workload_admission::workload_admission_registry_snapshot;
use rustfs_concurrency::{AdmissionState, WorkloadAdmissionRegistrySnapshot};
use rustfs_io_metrics::internode_metrics::{InternodeMetricsSnapshot, global_internode_metrics};
use rustfs_io_metrics::internode_metrics::InternodeMetricsSnapshot;
use rustfs_scanner_metrics::metrics::{ScannerMetricsReport, global_metrics};
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -102,9 +103,19 @@ impl From<&ScannerMetricsReport> for ClusterUsageFreshnessSnapshot {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ClusterListingDiagnosticsSnapshot {
pub local_budget_has_capacity: Option<bool>,
pub internode_stall_timeouts_total: u64,
}
impl From<InternodeMetricsSnapshot> for ClusterListingDiagnosticsSnapshot {
fn from(snapshot: InternodeMetricsSnapshot) -> Self {
Self {
internode_stall_timeouts_total: snapshot.operation_stall_timeouts_total,
..Self::default()
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClusterPoolMetaWriteGateSnapshot {
pub writes_ready: bool,
@@ -136,14 +147,6 @@ impl Default for ClusterPoolMetaWriteGateSnapshot {
}
}
impl From<InternodeMetricsSnapshot> for ClusterListingDiagnosticsSnapshot {
fn from(snapshot: InternodeMetricsSnapshot) -> Self {
Self {
internode_stall_timeouts_total: snapshot.operation_stall_timeouts_total,
}
}
}
impl ClusterRuntimeReadinessState {
fn from_report(report: &DependencyReadinessReport) -> Self {
if report.readiness.storage_ready
@@ -200,11 +203,14 @@ pub fn cluster_read_only_snapshot_from_control_plane(
}
}
pub async fn collect_cluster_read_only_snapshot(endpoint_pools: &EndpointServerPools) -> Option<ClusterReadOnlySnapshot> {
pub(crate) async fn collect_cluster_read_only_snapshot(context: &AppContext) -> Option<ClusterReadOnlySnapshot> {
let endpoint_pools = context.endpoints().handle()?;
let store = context.object_store();
let runtime_status = ClusterRuntimeStatusSnapshot::from_readiness_report(snapshot_dependency_readiness_report().await);
let mut snapshot = cluster_read_only_snapshot_from_endpoint_pools(endpoint_pools, runtime_status);
let mut snapshot = cluster_read_only_snapshot_from_endpoint_pools(&endpoint_pools, runtime_status);
snapshot.usage_freshness = current_usage_freshness_snapshot().await;
snapshot.listing_diagnostics = current_listing_diagnostics_snapshot();
snapshot.listing_diagnostics = context.internode_metrics().handle().snapshot().into();
snapshot.listing_diagnostics.local_budget_has_capacity = store.list_read_budget_has_capacity();
snapshot.pool_meta_write_gate = current_pool_meta_write_gate_snapshot().await;
Some(snapshot)
}
@@ -217,11 +223,6 @@ async fn current_usage_freshness_snapshot() -> ClusterUsageFreshnessSnapshot {
ClusterUsageFreshnessSnapshot::from(&report)
}
fn current_listing_diagnostics_snapshot() -> ClusterListingDiagnosticsSnapshot {
let metrics = crate::runtime_sources::current_internode_metrics().unwrap_or_else(|| global_internode_metrics().clone());
ClusterListingDiagnosticsSnapshot::from(metrics.snapshot())
}
async fn current_pool_meta_write_gate_snapshot() -> ClusterPoolMetaWriteGateSnapshot {
match crate::runtime_sources::current_object_store_handle() {
Some(store) => {
+248
View File
@@ -591,6 +591,16 @@ fn is_hyper_body_eof(err: &(dyn std::error::Error + 'static)) -> bool {
.is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::UnexpectedEof)
}
fn is_unavailable_internode_http_error(err: &rustfs_rio::InternodeHttpError) -> bool {
err.kind().is_retryable()
|| matches!(
err.kind(),
rustfs_rio::InternodeHttpErrorKind::HttpStatus(status)
if status.is_server_error() || status.as_u16() == 409
)
|| (err.kind() == rustfs_rio::InternodeHttpErrorKind::Unknown && err.context().operation().is_some())
}
/// A nested lock timeout retains its retry advice even when an outer lock
/// failure supplies a less specific cause. Share one bounded source walk.
fn service_unavailable_cause(source: &(dyn std::error::Error + 'static)) -> Option<&'static str> {
@@ -610,6 +620,13 @@ fn service_unavailable_cause(source: &(dyn std::error::Error + 'static)) -> Opti
}
_ => None,
};
if cause.is_none()
&& let Some(internode_err) = error.downcast_ref::<rustfs_rio::InternodeHttpError>()
&& is_unavailable_internode_http_error(internode_err)
&& matches!(internode_err.context().operation(), Some("put_file_stream" | "put_file_capability"))
{
cause = Some("storage_write_quorum");
}
}
None
}
@@ -646,6 +663,130 @@ impl From<ApiError> for rustfs_s3_types::S3Error {
}
}
/// Fine-grained, bounded classification for every HTTP 503 response (`ServiceUnavailable`,
/// `SlowDown`, `SlowDownRead`, `Busy`), emitted via `x-rustfs-503-subcause` at the outer
/// gateway stack edge and counted under `rustfs_s3_503_responses_total` without expanding
/// `rustfs-gateway`'s closed inner `x-rustfs-error-cause` set.
pub(crate) fn classify_s3_503_subcause(
code: &S3ErrorCode,
message: Option<&str>,
headers: Option<&http::HeaderMap>,
source: Option<&(dyn std::error::Error + 'static)>,
) -> &'static str {
if let Some(hdrs) = headers
&& let Some(cause) = hdrs.get("x-rustfs-error-cause").and_then(|v| v.to_str().ok())
{
match cause {
"namespace_lock_timeout" => return "namespace_lock_timeout",
"namespace_lock_unavailable" => return "namespace_lock_unavailable",
"storage_write_quorum" => return "storage_write_quorum",
_ => {}
}
}
if matches!(code, S3ErrorCode::Custom(name) if &**name == SLOW_DOWN_READ_CODE) {
return "storage_read_quorum";
}
if code == &S3ErrorCode::Busy {
return "s3_select_busy";
}
if let Some(src) = source
&& let Some(sub) = classify_503_source_chain(src)
{
return sub;
}
let msg = message.unwrap_or_default();
if code == &S3ErrorCode::SlowDown {
if msg.contains("write concurrency limit reached") || msg.contains("foreground write concurrency") {
return "foreground_write_admission";
}
if msg.contains("disk read concurrency limit reached") {
return "disk_read_permit_exhausted";
}
if msg.contains("Table listing exceeded") {
return "table_list_scan_limit";
}
if msg.contains("cold-fill") || msg.contains("cache") {
return "object_cache_cold_fill_rejected";
}
if headers.and_then(|h| h.get(http::header::RETRY_AFTER)).is_some() {
return "bucket_operation_admission";
}
if msg.contains("Resource requested is unreadable") {
return "storage_slowdown";
}
return "slowdown_other";
}
if msg.contains("quota") || msg.contains("Quota") {
return "quota_usage_unavailable";
}
if msg.contains("server context is not ready") || msg.contains("iam unavailable") {
return "server_not_ready";
}
"service_unavailable_other"
}
fn classify_503_source_chain(source: &(dyn std::error::Error + 'static)) -> Option<&'static str> {
if let Some(lock_or_write_cause) = service_unavailable_cause(source) {
return Some(lock_or_write_cause);
}
error_chain_find(source, |error| {
if let Some(status) = error.downcast_ref::<tonic::Status>() {
if status.code() == tonic::Code::ResourceExhausted
&& status
.metadata()
.get(RPC_ADMISSION_METADATA_KEY)
.is_some_and(|v| v.as_encoded_bytes() == RPC_REPLAY_ADMISSION_METADATA_VALUE.as_bytes())
{
return Some("internode_replay_cache_overflow");
}
if status.code() == tonic::Code::Unavailable {
return Some("internode_rpc_unavailable");
}
}
if error.is::<KmsUnavailableError>() || error.is::<rustfs_kms::KmsError>() {
return Some("kms_unavailable");
}
if error.is::<QuotaError>() {
return Some("quota_usage_unavailable");
}
if error.is::<ServerSideSourceReadError>() {
return Some("server_side_source_read_unavailable");
}
if let Some(internode_err) = error.downcast_ref::<rustfs_rio::InternodeHttpError>()
&& is_unavailable_internode_http_error(internode_err)
{
return Some("internode_rpc_unavailable");
}
if let Some(storage_err) = error.downcast_ref::<StorageError>() {
if storage_err.pool_metadata_failure().is_some() {
return Some("pool_metadata_unavailable");
}
if unreadable_config_refusal(storage_err).is_some() {
return Some("unreadable_bucket_config");
}
return match storage_err {
StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(_, _) => Some("storage_read_quorum"),
StorageError::ErasureWriteQuorum | StorageError::InsufficientWriteQuorum(_, _) => Some("storage_write_quorum"),
StorageError::DiskFull | StorageError::StorageFull => Some("disk_full"),
StorageError::TooManyOpenFiles => Some("too_many_open_files"),
StorageError::Timeout => Some("storage_timeout"),
StorageError::FaultyDisk | StorageError::FaultyRemoteDisk | StorageError::DiskNotFound => {
Some("faulty_or_missing_disk")
}
StorageError::UnsupportedDisk => Some("unsupported_participant_disk"),
StorageError::DeleteRecoveryWorkLimit => Some("delete_recovery_work_limit"),
StorageError::SlowDown => Some("storage_slowdown"),
_ => None,
};
}
None
})
}
/// Carry an owned refusal into a fixture that invokes the pinned transport.
#[cfg(test)]
pub(crate) fn legacy_error_for_test(error: rustfs_s3_types::S3Error) -> s3s::S3Error {
@@ -818,6 +959,21 @@ impl From<StorageError> for ApiError {
source: Some(Box::new(err)),
};
}
if error_chain_find(inner, |cause| {
cause
.downcast_ref::<rustfs_rio::InternodeHttpError>()
.filter(|err| is_unavailable_internode_http_error(err))
.map(|_| ())
})
.is_some()
{
return ApiError {
code: S3ErrorCode::ServiceUnavailable,
message: ApiError::error_code_to_message(&S3ErrorCode::ServiceUnavailable),
source: Some(Box::new(err)),
};
}
}
let code = match &err {
@@ -2610,6 +2766,42 @@ mod tests {
}
}
#[test]
fn internode_http_quorum_failures_map_to_service_unavailable_not_500() {
use crate::storage_api::error::{DiskError, OBJECT_OP_IGNORED_ERRS, reduce_write_quorum_errs};
use rustfs_rio::InternodeHttpErrorKind::{BodyStreamAborted, ConnectionReset, HttpStatus, Unknown};
for kind in [
ConnectionReset,
BodyStreamAborted,
Unknown,
HttpStatus(http::StatusCode::SERVICE_UNAVAILABLE),
HttpStatus(http::StatusCode::INTERNAL_SERVER_ERROR),
] {
let errors = [
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
Some(DiskError::from(rustfs_rio::new_test_internode_http_io_error(kind))),
None,
];
let reduced = reduce_write_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, 3)
.expect("quorum of internode http errors must reduce to a concrete error");
let api_err = ApiError::from(StorageError::from(reduced));
assert_eq!(
api_err.code,
S3ErrorCode::ServiceUnavailable,
"{kind:?} quorum failure should map to 503 ServiceUnavailable"
);
let response = S3Error::from(api_err);
assert_eq!(response.status_code(), Some(http::StatusCode::SERVICE_UNAVAILABLE));
}
let bad_req = DiskError::from(rustfs_rio::new_test_internode_http_io_error(HttpStatus(http::StatusCode::BAD_REQUEST)));
let errors = [Some(bad_req.clone()), Some(bad_req.clone()), Some(bad_req), None];
let reduced = reduce_write_quorum_errs(&errors, OBJECT_OP_IGNORED_ERRS, 3).unwrap();
assert_eq!(ApiError::from(StorageError::from(reduced)).code, S3ErrorCode::InternalError);
}
#[test]
fn test_api_error_from_unexpected_eof_maps_to_incomplete_body() {
let io_error = IoError::new(ErrorKind::UnexpectedEof, rustfs_rio::IncompleteBody { remaining: 7 });
@@ -2840,4 +3032,60 @@ mod tests {
assert_eq!(source.to_string(), "source error");
assert!(std::error::Error::source(&ApiError::access_denied()).is_none());
}
#[test]
fn test_classify_s3_503_subcause_covers_slowdown_and_source_chains() {
let slow_write = rustfs_s3_types::S3Error::with_message(
S3ErrorCode::SlowDown,
"foreground write concurrency limit reached, please reduce your request rate",
);
let parts = slow_write.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"foreground_write_admission"
);
let slow_read = rustfs_s3_types::S3Error::from(slow_down_read_api_error(StorageError::ErasureReadQuorum));
let parts = slow_read.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"storage_read_quorum"
);
let replay_overflow = rustfs_s3_types::S3Error::from(ApiError::from(StorageError::Io(IoError::other(
rpc_replay_admission_exhausted_status(),
))));
let parts = replay_overflow.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"internode_replay_cache_overflow"
);
let timeout_err = rustfs_s3_types::S3Error::from(ApiError::from(StorageError::Timeout));
let parts = timeout_err.into_parts();
assert_eq!(
classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
),
"storage_timeout"
);
}
}
@@ -40,6 +40,36 @@ use rustfs_gateway::{
use rustfs_gateway_types::{ETag, ErrorCode, Timestamp, TimestampFormat};
use rustfs_s3_types::S3Error;
use std::borrow::Cow;
use std::cell::Cell;
use std::future::Future;
tokio::task_local! {
static CURRENT_503_SUBCAUSE: Cell<Option<&'static str>>;
}
/// Runs `future` with a task-local slot that captures the fine-grained subcause of any HTTP 503
/// rendered by [`handler_error`] so [`crate::server::gateway_stack::GatewayStack::call`] can
/// emit `x-rustfs-503-subcause` on the outer response without widening the gateway's closed
/// inner `x-rustfs-error-cause` set.
pub(in crate::server) async fn scope_503_subcause<F: Future>(future: F) -> (F::Output, Option<&'static str>) {
CURRENT_503_SUBCAUSE
.scope(Cell::new(None), async move {
let out = future.await;
let subcause = CURRENT_503_SUBCAUSE.try_with(Cell::get).ok().flatten();
(out, subcause)
})
.await
}
fn s3_code_metric_label(code: &rustfs_s3_types::S3ErrorCode) -> &'static str {
match code.as_str() {
"ServiceUnavailable" => "ServiceUnavailable",
"SlowDown" => "SlowDown",
"SlowDownRead" => "SlowDownRead",
"Busy" => "Busy",
_ => "Other503",
}
}
const LOG_COMPONENT_STORAGE: &str = "storage";
const LOG_SUBSYSTEM_OBJECT: &str = "object";
@@ -154,6 +184,16 @@ pub(crate) fn handler_error(error: S3Error) -> HandlerError {
.status
.or_else(|| parts.code.status_code())
.unwrap_or(http::StatusCode::INTERNAL_SERVER_ERROR);
if status == http::StatusCode::SERVICE_UNAVAILABLE {
let subcause = crate::error::classify_s3_503_subcause(
&parts.code,
parts.message.as_deref(),
parts.headers.as_ref(),
parts.source.as_deref().map(|err| err as &(dyn std::error::Error + 'static)),
);
rustfs_io_metrics::s3_http_metrics::record_s3_http_503_response(s3_code_metric_label(&parts.code), subcause);
let _ = CURRENT_503_SUBCAUSE.try_with(|slot| slot.set(Some(subcause)));
}
// A declared code compares equal to the custom code of the same spelling and status.
let code = ErrorCode::custom(parts.code.as_str().to_owned(), status);
let headers = parts.headers.unwrap_or_default();
@@ -152,6 +152,14 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
.user_defined
.keys()
.any(|key| rustfs_utils::http::is_object_encryption_marker(key));
// The upload's checksum contract, recorded at CreateMultipartUpload, is echoed here so a
// client resuming from ListParts sees the same algorithm and type.
let checksum_algorithm = (!page.checksum_algorithm.is_empty())
.then_some(page.checksum_algorithm)
.map(dto::ChecksumAlgorithm::custom);
let checksum_type = (!page.checksum_type.is_empty())
.then_some(page.checksum_type)
.map(dto::ChecksumType::custom);
let parts = page
.parts
.into_iter()
@@ -168,12 +176,23 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
i64::try_from(part.size)
.map_err(|_| s3_error!(InternalError, "a stored part size is outside the ListParts response range"))?
};
let checksums = part.checksums.unwrap_or_default();
let checksum = |algorithm: &str| checksums.get(algorithm).cloned();
Ok(dto::Part {
e_tag: dto_values::stored_etag(tag),
last_modified: part.last_mod.map(dto_values::timestamp),
part_number,
size,
..Default::default()
checksum_crc32: checksum("CRC32"),
checksum_crc32c: checksum("CRC32C"),
checksum_crc64nvme: checksum("CRC64NVME"),
checksum_sha1: checksum("SHA1"),
checksum_sha256: checksum("SHA256"),
checksum_sha512: checksum("SHA512"),
checksum_md5: checksum("MD5"),
checksum_xxhash3: checksum("XXHASH3"),
checksum_xxhash64: checksum("XXHASH64"),
checksum_xxhash128: checksum("XXHASH128"),
})
})
.collect::<S3Result<_>>()?;
@@ -192,6 +211,8 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
storage_class: Some(dto::StorageClass::custom(
effective_class(Some(page.storage_class.as_str()), None).to_owned(),
)),
checksum_algorithm,
checksum_type,
..Default::default()
})
}
@@ -84,6 +84,36 @@ fn test_list_parts_output_maps_parts_and_owner() {
assert_eq!(initiator.display_name, owner.display_name);
}
#[test]
fn test_list_parts_output_maps_recorded_checksums() {
let output = list_parts_output(ListPartsInfo {
checksum_algorithm: "SHA256".into(),
checksum_type: "COMPOSITE".into(),
parts: vec![PartInfo {
size: 5,
checksums: Some(std::collections::HashMap::from([
("CRC32".to_owned(), "part-crc32".to_owned()),
("SHA256".to_owned(), "part-sha256".to_owned()),
])),
..part(1)
}],
..page()
})
.unwrap();
assert_eq!(output.checksum_algorithm.as_ref().map(|value| value.as_str()), Some("SHA256"));
assert_eq!(output.checksum_type.as_ref().map(|value| value.as_str()), Some("COMPOSITE"));
assert_eq!(output.parts[0].checksum_crc32.as_deref(), Some("part-crc32"));
assert_eq!(output.parts[0].checksum_sha256.as_deref(), Some("part-sha256"));
assert!(output.parts[0].checksum_sha1.is_none());
let xml = encode_xml(output);
assert!(xml.contains("<ChecksumAlgorithm>SHA256</ChecksumAlgorithm>"), "{xml}");
assert!(xml.contains("<ChecksumType>COMPOSITE</ChecksumType>"), "{xml}");
assert!(xml.contains("<ChecksumCRC32>part-crc32</ChecksumCRC32>"), "{xml}");
assert!(xml.contains("<ChecksumSHA256>part-sha256</ChecksumSHA256>"), "{xml}");
}
#[test]
fn test_list_parts_output_xml_omits_terminal_marker() {
for (marker, parts) in [(0, vec![]), (3, vec![10]), (0, vec![1, 3])] {
+24
View File
@@ -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};
@@ -135,6 +136,18 @@ fn resp<O: Served>(answered: Answered<O::Output>) -> Resp<O> {
.with_extra_headers(headers)
}
// RUSTFS_COMPAT_TODO(http-opaque-response-headers): Preserve UTF-8 response values. Remove after the gateway codec emits opaque bytes.
fn preserve_opaque_header(headers: &mut http::HeaderMap, name: impl http::header::IntoHeaderName, field: Option<&str>) {
// Keep the typed field so the encoder does not write a default Content-Type.
// Its ASCII constructor skips the opaque value, leaving the extra header to supply it.
if let Some(value) = field
&& !value.is_ascii()
&& let Ok(value) = http::HeaderValue::from_bytes(value.as_bytes())
{
headers.insert(name, value);
}
}
impl<O: Served> Handler<O> for GatewayBackend {
async fn call(&self, request: Req<O>) -> HandlerResult<O> {
self.serve(request).await
@@ -270,6 +283,17 @@ mod tests {
assert_eq!(registered, rows(OPERATIONS).map(|row| row.name).collect());
}
#[test]
fn expiration_projection_preserves_utf8_without_accepting_controls() {
let mut headers = http::HeaderMap::new();
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, Some("rule-id=\"保留策略\""));
assert_eq!(headers[rustfs_utils::http::AMZ_EXPIRATION].as_bytes(), "rule-id=\"保留策略\"".as_bytes());
headers.clear();
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, Some("rule-id=\"保留\n策略\""));
assert!(headers.is_empty());
}
/// An invalid header value does not alter the response status or other headers.
#[test]
fn a_stored_tag_a_header_cannot_hold_is_left_out_and_the_answer_stands() {
@@ -14,7 +14,7 @@
//! The gateway operations of migration batch C (rustfs/backlog#2765): GetObject, HeadObject and GetObjectAttributes.
use super::{OpRow, Served, resp, row};
use super::{OpRow, Served, preserve_opaque_header, resp, row};
use crate::app::object_usecase::{
DefaultObjectUsecase, GetObjectAttributesFields, GetObjectAttributesOutputFacts, GetObjectBody, GetObjectOutputFacts,
HeadObjectOutputFacts, ResponseEtag,
@@ -28,7 +28,7 @@ use crate::storage_api::server::http::access::access_owned::object_read::{
use rustfs_gateway::{Req, Resp, dto};
use rustfs_s3_ops::S3Operation;
use rustfs_s3_types::{S3ErrorCode, S3Result, s3_error};
use rustfs_utils::http::{SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
use rustfs_utils::http::{AMZ_EXPIRATION, SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
use std::sync::Arc;
pub(super) const ROWS: &[OpRow] = &[
@@ -63,9 +63,18 @@ impl Served for dto::HeadObject {
authorize_head_object(&server_ctx, envelope, bucket, key, version_id).await
}
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
let preserve_content_type = request.input().response_content_type.is_none();
let result = DefaultObjectUsecase::with_context(context)
.execute_head_object(envelope, request.into_input())
.await;
.await
.map(|mut answered| {
preserve_opaque_header(
&mut answered.headers,
http::header::CONTENT_TYPE,
answered.output.dto.content_type.as_deref().filter(|_| preserve_content_type),
);
answered
});
head_result(result)
}
}
@@ -95,10 +104,19 @@ impl Served for dto::GetObject {
}
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
let log_error = super::error::object_error_logger("GetObject", request.context().transport_extensions().clone());
let preserve_content_type = request.input().response_content_type.is_none();
let result = get_result(
DefaultObjectUsecase::with_context(context)
.execute_gateway_get_object(envelope, request.into_input())
.await,
.await
.map(|mut answered| {
preserve_opaque_header(
&mut answered.headers,
http::header::CONTENT_TYPE,
answered.output.dto.content_type.as_deref().filter(|_| preserve_content_type),
);
answered
}),
);
result.inspect_err(log_error)
}
@@ -222,6 +240,7 @@ pub(super) fn get_response(answered: Answered<GetObjectOutputFacts>) -> S3Result
} = answered;
insert_etag(&mut headers, output.etag)
.map_err(|_| s3_error!(InternalError, "We encountered an internal error. Please try again."))?;
preserve_opaque_header(&mut headers, AMZ_EXPIRATION, output.dto.expiration.as_ref().map(AsRef::as_ref));
output.dto.body = output
.body
.map(|body| match body {
@@ -271,6 +290,7 @@ pub(super) fn head_response(answered: Answered<HeadObjectOutputFacts>) -> S3Resu
mut headers,
} = answered;
insert_etag(&mut headers, output.etag)?;
preserve_opaque_header(&mut headers, AMZ_EXPIRATION, output.dto.expiration.as_ref().map(AsRef::as_ref));
Ok(resp::<dto::HeadObject>(Answered {
output: output.dto,
status,
@@ -14,7 +14,7 @@
//! PutObject gateway registration and native request/response projection.
use super::{OpRow, Served, row};
use super::{OpRow, Served, preserve_opaque_header, row};
use crate::app::RequestEnvelope;
use crate::app::multipart_usecase::{DefaultMultipartUsecase, UploadPartTarget, UploadPartWriteInput, UploadPartWriteOutput};
use crate::app::object::FrameTrailers;
@@ -275,6 +275,7 @@ fn native_output(output: PutObjectWriteOutput) -> S3Result<Resp<dto::PutObject>>
output.checksum_crc64nvme,
],
)?;
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, output.expiration.as_deref());
let dto = dto::PutObjectOutput {
e_tag: crate::app::dto_values::stored_etag(
output
+10 -1
View File
@@ -405,7 +405,16 @@ impl GatewayStack {
// left unread in a detached task of its own, which takes the body away from
// `EarlyResponseBodyService`, the drain the HTTP/1-2 shutdown accounting owns. The
// adapter's connection verdict is kept.
let mut response = service.call(request).await;
let (mut response, subcause_503) =
crate::server::gateway_handlers::scope_503_subcause(async move { service.call(request).await }).await;
if response.status() == http::StatusCode::SERVICE_UNAVAILABLE
&& let Some(subcause) = subcause_503
{
response.headers_mut().insert(
http::HeaderName::from_static("x-rustfs-503-subcause"),
http::HeaderValue::from_static(subcause),
);
}
if track_plaintext_post_ssec && is_plaintext_ssec_refusal_response(&response) {
report_plaintext_ssec();
}
+101 -21
View File
@@ -75,24 +75,30 @@ pub(crate) async fn collect_probe_readiness(
HealthReadinessSource::ClusterWrite => collect_cluster_write_health_report().await,
HealthReadinessSource::ClusterRead => collect_cluster_read_health_report().await,
};
if probe == HealthProbe::Readiness
&& let Some(object_traffic_health) = object_traffic_health
{
apply_object_traffic_snapshot(&mut report, object_traffic_health.snapshot());
if let Some(object_traffic_health) = object_traffic_health {
apply_object_traffic_snapshot(&mut report, probe, object_traffic_health.snapshot());
}
Some(report)
}
fn apply_object_traffic_snapshot(report: &mut DependencyReadinessReport, snapshot: ObjectTrafficSnapshot) {
if snapshot.read_stalled {
fn apply_object_traffic_snapshot(report: &mut DependencyReadinessReport, probe: HealthProbe, snapshot: ObjectTrafficSnapshot) {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterRead) && snapshot.read_stalled {
let reason = ReadinessDegradedReason::ObjectReadStalled;
report.degraded_reasons.push(reason);
record_readiness_overlay_reason(reason);
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
}
if snapshot.write_stalled {
if matches!(probe, HealthProbe::Readiness | HealthProbe::ClusterWrite) && snapshot.write_stalled {
let reason = ReadinessDegradedReason::ObjectWriteStalled;
report.degraded_reasons.push(reason);
record_readiness_overlay_reason(reason);
if !report.degraded_reasons.contains(&reason) {
report.degraded_reasons.push(reason);
}
if probe == HealthProbe::Readiness {
record_readiness_overlay_reason(reason);
}
}
}
@@ -321,21 +327,25 @@ pub(crate) fn build_health_response_parts(
),
};
let readiness_overlay_degraded = degraded_reasons.iter().any(|reason| {
matches!(
reason,
ReadinessDegradedReason::ObjectReadStalled
| ReadinessDegradedReason::ObjectWriteStalled
| ReadinessDegradedReason::StartupFinalizationPending
)
});
if probe == HealthProbe::Readiness && (readiness_overlay_degraded || matches!(kms_ready, Some(false))) {
let startup_pending = degraded_reasons.contains(&ReadinessDegradedReason::StartupFinalizationPending);
let write_stalled = degraded_reasons.contains(&ReadinessDegradedReason::ObjectWriteStalled);
let read_stalled = degraded_reasons.contains(&ReadinessDegradedReason::ObjectReadStalled);
let readiness_overlay_degraded = match probe {
HealthProbe::Readiness => startup_pending || write_stalled || read_stalled || matches!(kms_ready, Some(false)),
HealthProbe::ClusterWrite => write_stalled,
HealthProbe::ClusterRead => read_stalled,
HealthProbe::Liveness => false,
};
if readiness_overlay_degraded {
health = HealthCheckState {
status_code: StatusCode::SERVICE_UNAVAILABLE,
status: "degraded",
ready: false,
};
if matches!(kms_ready, Some(false)) && !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady) {
if probe == HealthProbe::Readiness
&& matches!(kms_ready, Some(false))
&& !degraded_reasons.contains(&ReadinessDegradedReason::KmsNotReady)
{
degraded_reasons.push(ReadinessDegradedReason::KmsNotReady);
}
}
@@ -716,6 +726,7 @@ mod tests {
let mut report = ready_report();
apply_object_traffic_snapshot(
&mut report,
HealthProbe::Readiness,
ObjectTrafficSnapshot {
read_stalled: true,
write_stalled: false,
@@ -880,4 +891,73 @@ mod tests {
assert_eq!(payload["degradedReasons"], json!([]));
});
}
#[test]
#[serial]
fn cluster_probes_reflect_matching_traffic_stalls_without_startup_admission_overlay() {
with_var(rustfs_config::ENV_HEALTH_MINIMAL_RESPONSE_ENABLE, Some("false"), || {
let mut startup_report = ready_report();
startup_report
.degraded_reasons
.push(ReadinessDegradedReason::StartupFinalizationPending);
// Node readiness waits for S3 admission publication, while cluster probes continue
// reporting cluster quorum readiness before node-local publication.
let readiness = build_health_response_parts(
Method::GET,
HealthProbe::Readiness,
Some(&startup_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(readiness.status_code, StatusCode::SERVICE_UNAVAILABLE);
for probe in [HealthProbe::ClusterWrite, HealthProbe::ClusterRead] {
let parts = build_health_response_parts(Method::GET, probe, Some(&startup_report), "rustfs-endpoint", None, None);
assert_eq!(parts.status_code, StatusCode::OK, "{probe:?}");
}
let mut write_report = ready_report();
apply_object_traffic_snapshot(
&mut write_report,
HealthProbe::ClusterWrite,
ObjectTrafficSnapshot {
read_stalled: true,
write_stalled: true,
},
);
let write_parts = build_health_response_parts(
Method::GET,
HealthProbe::ClusterWrite,
Some(&write_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(write_parts.status_code, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
write_parts.payload.expect("cluster write payload")["degradedReasons"],
json!(["object_write_stalled"])
);
let mut read_report = ready_report();
apply_object_traffic_snapshot(
&mut read_report,
HealthProbe::ClusterRead,
ObjectTrafficSnapshot {
read_stalled: false,
write_stalled: true,
},
);
let read_parts = build_health_response_parts(
Method::GET,
HealthProbe::ClusterRead,
Some(&read_report),
"rustfs-endpoint",
None,
None,
);
assert_eq!(read_parts.status_code, StatusCode::OK);
});
}
}
+31
View File
@@ -2971,6 +2971,37 @@ pub(in crate::server) mod tests {
.is_empty()
);
let response = service
.call(
Request::builder()
.method(Method::GET)
.uri(MINIO_HEALTH_CLUSTER_READ_PATH)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster read request"),
)
.await
.expect("cluster read response");
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body = BodyExt::collect(response.into_body())
.await
.expect("cluster read body")
.to_bytes();
let payload: serde_json::Value = serde_json::from_slice(&body).expect("cluster read JSON");
assert_eq!(payload["ready"], false);
assert_eq!(payload["degradedReasons"], serde_json::json!(["object_read_stalled"]));
let response = service
.call(
Request::builder()
.method(Method::GET)
.uri(MINIO_HEALTH_CLUSTER_PATH)
.body(Full::<Bytes>::from(Bytes::new()))
.expect("cluster write request"),
)
.await
.expect("cluster write response");
assert_eq!(response.status(), StatusCode::OK);
let response = service
.call(
Request::builder()
+36 -1
View File
@@ -179,6 +179,7 @@ fn readiness_pending_dependency(stage: rustfs_common::SystemStage) -> &'static s
fn service_not_ready_response(stage: rustfs_common::SystemStage) -> Response<BoxBody> {
let pending = readiness_pending_dependency(stage);
rustfs_io_metrics::s3_http_metrics::record_s3_http_503_response("ServiceUnavailable", "readiness_pending");
let body: BoxBody = Full::new(Bytes::from(format!("Service not ready: waiting for {pending}")))
.map_err(|never| match never {})
.boxed_unsync();
@@ -197,6 +198,10 @@ fn service_not_ready_response(stage: rustfs_common::SystemStage) -> Response<Box
response
.headers_mut()
.insert(READINESS_PENDING_HEADER, HeaderValue::from_static(pending));
response.headers_mut().insert(
http::HeaderName::from_static("x-rustfs-503-subcause"),
HeaderValue::from_static("readiness_pending"),
);
response
}
@@ -2539,7 +2544,10 @@ mod tests {
#[tokio::test]
async fn service_not_ready_response_preserves_observable_contract() {
let response = service_not_ready_response(rustfs_common::SystemStage::Booting);
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let response =
metrics::with_local_recorder(&recorder, || service_not_ready_response(rustfs_common::SystemStage::Booting));
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
@@ -2570,6 +2578,33 @@ mod tests {
.and_then(|value| value.to_str().ok()),
Some("storage_quorum")
);
assert_eq!(
response
.headers()
.get("x-rustfs-503-subcause")
.and_then(|value| value.to_str().ok()),
Some("readiness_pending")
);
let counted = snapshotter
.snapshot()
.into_vec()
.into_iter()
.find_map(|(composite, _, _, value)| {
(composite.key().name() == "rustfs_s3_503_responses_total"
&& composite
.key()
.labels()
.any(|label| label.key() == "code" && label.value() == "ServiceUnavailable")
&& composite
.key()
.labels()
.any(|label| label.key() == "subcause" && label.value() == "readiness_pending"))
.then_some(value)
});
assert!(
matches!(counted, Some(DebugValue::Counter(1))),
"service_not_ready_response must increment rustfs_s3_503_responses_total once"
);
let body = match response.into_body().collect().await {
Ok(body) => body.to_bytes(),
Err(err) => panic!("not-ready body should collect: {err}"),
+1
View File
@@ -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"))
+1 -1
View File
@@ -1282,7 +1282,7 @@ impl ConcurrencyManager {
match state {
AdmissionState::Disabled => admission.with_reason("disk read permits disabled"),
AdmissionState::Saturated => admission.with_reason("all disk read permits are in use"),
AdmissionState::Saturated => admission.with_reason("all primary disk-backed GET permits are in use"),
_ => admission,
}
}
+102 -34
View File
@@ -315,27 +315,52 @@ macro_rules! log_internode_rpc_response_failure {
}
macro_rules! log_internode_put_file_stage_failure {
($stage:expr, $query:expr, $err:expr) => {
error!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "failed",
status_code = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_stage_failed",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %$err,
"internode rpc request failed"
);
};
($stage:expr, $query:expr, $err:expr) => {{
let err_ref: &(dyn std::error::Error + 'static) = $err;
let status = classify_put_file_stage_status($stage, err_ref);
if status == StatusCode::BAD_REQUEST {
tracing::debug!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "aborted_by_sender",
status_code = status.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_body_aborted",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %err_ref,
"internode put_file stream aborted by sender"
);
} else {
error!(
event = EVENT_RPC_REQUEST_FAILED,
component = LOG_COMPONENT_INTERNODE_RPC,
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
operation = INTERNODE_OPERATION_PUT_FILE_STREAM,
result = "failed",
status_code = status.as_u16(),
rpc_path = PUT_FILE_STREAM_PATH,
method = %Method::PUT,
reason = "put_file_stage_failed",
stage = $stage,
disk = %$query.disk,
volume = %$query.volume,
path = %$query.path,
append = $query.append,
size = $query.size,
error = %err_ref,
"internode rpc request failed"
);
}
status
}};
}
/// Answers the internode rpc paths itself and hands every other request to
@@ -2110,7 +2135,7 @@ where
cleanup.downcast_ref::<DiskError>(),
Some(DiskError::FileNotFound | DiskError::VolumeNotFound)
) {
log_internode_put_file_stage_failure!("cleanup_staging", query, cleanup);
let _ = log_internode_put_file_stage_failure!("cleanup_staging", query, cleanup.as_ref());
}
return Err((stage, primary));
}
@@ -2223,8 +2248,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(copied) => copied,
Err((stage, e)) => {
let message = put_file_stage_error_message(stage, &query, e.as_ref());
log_internode_put_file_stage_failure!(stage, query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!(stage, query, e.as_ref());
return response_with_status(status, message);
}
};
record_put_file_metrics(copied);
@@ -2239,8 +2264,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(file) => file,
Err(e) => {
let message = put_file_stage_error_message("append", &query, &e);
log_internode_put_file_stage_failure!("append", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("append", query, &e);
return response_with_status(status, message);
}
}
} else {
@@ -2248,8 +2273,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(file) => file,
Err(e) => {
let message = put_file_stage_error_message("create", &query, &e);
log_internode_put_file_stage_failure!("create", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("create", query, &e);
return response_with_status(status, message);
}
}
};
@@ -2260,8 +2285,8 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
Ok(copied) => copied,
Err(e) => {
let message = put_file_stage_error_message("write_body", &query, &e);
log_internode_put_file_stage_failure!("write_body", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("write_body", query, &e);
return response_with_status(status, message);
}
};
@@ -2273,14 +2298,14 @@ async fn handle_put_file(req: Request<Incoming>, require_auth: bool) -> Response
format!("body size mismatch: expected {} bytes, received {copied}", query.size),
);
let message = put_file_stage_error_message("verify_size", &query, &err);
log_internode_put_file_stage_failure!("verify_size", query, err);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("verify_size", query, &err);
return response_with_status(status, message);
}
if let Err(e) = file.flush().await {
let message = put_file_stage_error_message("flush", &query, &e);
log_internode_put_file_stage_failure!("flush", query, e);
return response_with_status(StatusCode::INTERNAL_SERVER_ERROR, message);
let status = log_internode_put_file_stage_failure!("flush", query, &e);
return response_with_status(status, message);
}
empty_ok()
@@ -2505,6 +2530,49 @@ fn put_body_size_mismatch(query: &PutFileQuery, copied: u64) -> bool {
!query.append && query.size > 0 && copied != u64::try_from(query.size).unwrap_or(u64::MAX)
}
fn classify_put_file_stage_status(stage: &str, err: &(dyn std::error::Error + 'static)) -> StatusCode {
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(cause) = current {
if let Some(disk_err) = cause.downcast_ref::<DiskError>()
&& matches!(
disk_err,
DiskError::Timeout
| DiskError::FaultyDisk
| DiskError::FaultyRemoteDisk
| DiskError::DiskNotFound
| DiskError::DiskFull
| DiskError::TooManyOpenFiles
| DiskError::DiskOngoingReq
)
{
return StatusCode::SERVICE_UNAVAILABLE;
}
if matches!(stage, "write_body" | "verify_size") {
if let Some(io_err) = cause.downcast_ref::<io::Error>()
&& matches!(
io_err.kind(),
io::ErrorKind::UnexpectedEof
| io::ErrorKind::ConnectionReset
| io::ErrorKind::BrokenPipe
| io::ErrorKind::ConnectionAborted
)
{
return StatusCode::BAD_REQUEST;
}
if let Some(hyper_err) = cause.downcast_ref::<hyper::Error>()
&& (hyper_err.is_body_write_aborted()
|| hyper_err.is_incomplete_message()
|| hyper_err.is_closed()
|| hyper_err.is_canceled())
{
return StatusCode::BAD_REQUEST;
}
}
current = cause.source();
}
StatusCode::INTERNAL_SERVER_ERROR
}
fn put_file_stage_error_message(stage: &str, query: &PutFileQuery, err: &dyn std::fmt::Display) -> String {
format!(
"{stage} file err {err} [disk={}, volume={}, path={}, append={}, size={}]",
+1 -1
View File
@@ -794,7 +794,7 @@ pub fn parse_etag(object_etag: &str) -> Result<HeaderValue, S3Error> {
let etag_quoted = format!("\"{}\"", etag_trimmed);
HeaderValue::from_str(&etag_quoted).map_err(|e| {
HeaderValue::from_bytes(etag_quoted.as_bytes()).map_err(|e| {
warn!(
"Failed to convert ETag to HeaderValue (ETag: {}): {}. The ETag header will be omitted from the response.",
etag_quoted, e
@@ -807,6 +807,17 @@ fn gateway_post_archive_encoding_uses_form_content_fields() {
.request("GET", &format!("/{BUCKET}/quoted-utf8"), b"", &[], Some(0))
.await;
assert_eq!(read.headers.get("content-type").map(String::as_str), Some("text/plain; name=\"café\""));
let overridden = root
.request(
"GET",
&format!("/{BUCKET}/quoted-utf8?response-content-type=text%2Fplain"),
b"",
&[],
Some(0),
)
.await;
assert_eq!(overridden.status, 200, "{}", overridden.body);
assert_eq!(overridden.headers.get("content-type").map(String::as_str), Some("text/plain"));
server.shutdown().await;
},
);
+21 -4
View File
@@ -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
+21
View File
@@ -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"
+56 -2
View File
@@ -286,18 +286,48 @@ marker="$GUARD_DIR/$host"
case "${QUEUE_FIXTURE:-quiet}" in
missing) exit 2 ;;
hung) exec sleep 60 ;;
diskstats-*)
QUEUE_SAMPLE_DIR="$(mktemp -d "$GUARD_DIR/diskstats.XXXXXXXX")"
export QUEUE_SAMPLE_DIR
trap 'rm -rf -- "$QUEUE_SAMPLE_DIR"' EXIT
printf '10.00 0.00\n' >"$QUEUE_SAMPLE_DIR/uptime"
cat >"$QUEUE_SAMPLE_DIR/diskstats" <<'STATS'
259 0 nvme0n1 0 0 0 0 20 0 80 40 0 0 100
259 1 nvme1n1 0 0 0 0 30 0 80 60 0 0 100
STATS
cp "$QUEUE_SAMPLE_DIR/diskstats" "$QUEUE_SAMPLE_DIR/after"
if [[ "$QUEUE_FIXTURE" != diskstats-idle ]]; then
writes=24
write_ms=48
case "$QUEUE_FIXTURE" in
diskstats-reset-count) writes=19 ;;
diskstats-reset-time) write_ms=39 ;;
esac
printf '259 0 nvme0n1 0 0 0 0 %s 0 96 %s 0 0 250\n' "$writes" "$write_ms" >"$QUEUE_SAMPLE_DIR/after"
printf '259 1 nvme1n1 0 0 0 0 46 0 128 76 0 0 150\n' >>"$QUEUE_SAMPLE_DIR/after"
fi
advance_diskstats() {
printf '15.00 0.00\n' >"$QUEUE_SAMPLE_DIR/uptime"
cp "$QUEUE_SAMPLE_DIR/after" "$QUEUE_SAMPLE_DIR/diskstats"
}
export -f advance_diskstats
command=$(printf '%s\n' "$command" | sed \
's@/proc/uptime@"$QUEUE_SAMPLE_DIR/uptime"@g; s@/proc/diskstats@"$QUEUE_SAMPLE_DIR/diskstats"@g; s@^sleep 5$@advance_diskstats@')
bash -c "$command"
exit
;;
reset)
n=0
[[ ! -f "$marker" ]] || read -r n < "$marker"
n=$((n+1))
printf '%s\n' "$n" > "$marker"
if [[ "$host" == host-b && "$n" == 2 ]]; then
echo '0.050000 0.800000'
echo '0.050000 0.800000 0 NA NA'
exit 0
fi
;;
esac
echo '0.050000 0.070000'
echo '0.050000 0.070000 0 NA NA'
SSH
cat > "$GUARD_BIN/curl" <<'CURL'
#!/usr/bin/env bash
@@ -369,4 +399,28 @@ if PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE=hung "$SCRIPT_DIR/wait_cluster_disk_que
fi
rg -q 'failed or timed out' "$TMP_DIR/queue-timeout.log"
queue_cmd=("$SCRIPT_DIR/wait_cluster_disk_queue.sh"
--target a=host-a --devices a=nvme0n1+nvme1n1 --timeout-secs 11)
for fixture in diskstats-write diskstats-idle; do
PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE="$fixture" "${queue_cmd[@]}" >"$TMP_DIR/$fixture.tsv"
printf 'sample\tnode\tmean_queue\tpeak_queue\tcompleted_writes\twrite_ms_per_op\tpeak_write_ms_per_op\n' >"$TMP_DIR/expected.tsv"
for sample in 1 2; do
if [[ "$fixture" == diskstats-write ]]; then
printf '%s\ta\t0.020000\t0.030000\t20\t1.200000\t2.000000\n' "$sample"
else
printf '%s\ta\t0.000000\t0.000000\t0\tNA\tNA\n' "$sample"
fi
done >>"$TMP_DIR/expected.tsv"
diff -u "$TMP_DIR/expected.tsv" "$TMP_DIR/$fixture.tsv"
done
for fixture in diskstats-reset-count diskstats-reset-time; do
if PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE="$fixture" "${queue_cmd[@]}" >"$TMP_DIR/$fixture.log" 2>&1; then
echo "expected $fixture to fail an otherwise quiet sample" >&2
exit 1
fi
rg -q 'disk queue sample failed or timed out' "$TMP_DIR/$fixture.log"
done
echo "object batch benchmark enhanced tests passed"
+37 -9
View File
@@ -73,6 +73,7 @@ trap 'exit 143' TERM
# Only validated device names are placed in the SSH command. The sampler uses
# monotonic uptime and the weighted I/O milliseconds from /proc/diskstats.
# Write completions and write milliseconds describe the same sampling window.
sample=$(cat <<'REMOTE'
set -eu
export LC_ALL=C
@@ -81,8 +82,8 @@ snapshot() {
BEGIN { n=split(devices,d," "); for(i=1;i<=n;i++) want[d[i]]=1 }
FNR==NR { t=$1; next }
$3 in want {
if (NF<14 || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14
if (NF<14 || $8 !~ /^[0-9]+$/ || $11 !~ /^[0-9]+$/ || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14,$8,$11
got++
}
END { if (got!=n) exit 2 }
@@ -93,10 +94,36 @@ sleep 5
after=$(snapshot)
printf '%s\n--\n%s\n' "$before" "$after" | awk '
$0=="--" { second=1; next }
!second { if ($1 in t) bad=1; t[$1]=$2; w[$1]=$3; count++; next }
{ if (!($1 in t) || seen[$1]++ || $2<=t[$1] || $3<w[$1]) { bad=1; next }
q=($3-w[$1])/(1000*($2-t[$1])); sum+=q; if(q>peak)peak=q; got++ }
END { if (bad||!count||got!=count) exit 2; printf "%.6f %.6f\n",sum/count,peak }
!second {
if ($1 in t) bad=1
t[$1]=$2; w[$1]=$3; writes[$1]=$4; write_ms[$1]=$5
count++
next
}
{
if (!($1 in t) || seen[$1]++ || $2<=t[$1] || $3<w[$1] || $4<writes[$1] || $5<write_ms[$1]) {
bad=1
next
}
q=($3-w[$1])/(1000*($2-t[$1]))
sum+=q
if (q>peak) peak=q
completed=$4-writes[$1]
if (completed>0) {
elapsed_ms=$5-write_ms[$1]
total_completed+=completed
total_write_ms+=elapsed_ms
await_ms=elapsed_ms/completed
if (await_ms>peak_write_ms) peak_write_ms=await_ms
}
got++
}
END {
if (bad||!count||got!=count) exit 2
printf "%.6f %.6f %.0f",sum/count,peak,total_completed
if (total_completed>0) printf " %.6f %.6f\n",total_write_ms/total_completed,peak_write_ms
else printf " NA NA\n"
}
'
REMOTE
)
@@ -104,7 +131,7 @@ REMOTE
end=$((SECONDS+budget))
streak=0
sample_number=0
printf 'sample\tnode\tmean_queue\tpeak_queue\n'
printf 'sample\tnode\tmean_queue\tpeak_queue\tcompleted_writes\twrite_ms_per_op\tpeak_write_ms_per_op\n'
while ((end-SECONDS >= 5)); do
sample_number=$((sample_number+1))
remaining=$((end-SECONDS))
@@ -125,12 +152,13 @@ while ((end-SECONDS >= 5)); do
quiet=true
for i in "${!targets[@]}"; do
result=$(cat "$artifacts/$i")
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([0-9]+\.[0-9]+)$ ]]; then
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([0-9]+\.[0-9]+)\ ([0-9]+)\ (NA|[0-9]+\.[0-9]+)\ (NA|[0-9]+\.[0-9]+)$ ]]; then
echo "invalid disk queue sample from ${targets[i]%%=*}" >&2; exit 1
fi
mean="${BASH_REMATCH[1]}"
peak="${BASH_REMATCH[2]}"
printf '%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak"
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak" \
"${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}" "${BASH_REMATCH[5]}"
if ! awk -v mean="$mean" -v peak="$peak" 'BEGIN {exit !(mean<=0.25 && peak<=0.75)}'; then quiet=false; fi
done
if [[ "$quiet" == true ]]; then