Compare commits

..

4 Commits

Author SHA1 Message Date
唐小鸭 29a0eb91b9 Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-12-02 00:27:11 +08:00
唐小鸭 5a5acedbee Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-12-01 12:17:18 +08:00
唐小鸭 51bd41a30b Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-11-30 11:10:12 +08:00
唐小鸭 49f01af16d fix(replication): replay deletes deferred by a held source lock
A live delete replication that cannot take the source object lock was dropped: the worker discarded the outcome, and the two lock skips before the target call were only logged at debug. A bulk delete keeps its key locks until the whole batch commits and keeps running after its client disconnects, so a retried bulk delete of the same keys made earlier markers lose the five second lock wait and never reach the target, or reach it without the result being recorded on the source.

Report how an attempt ended. When a source-side lock or read kept it from running, or from persisting its result, the worker journals the delete so the periodic MRF replay drives it again. Target failures stay with the persisted state and the scanner as before, so an unreachable target does not fill the journal. The three source-deferred skips now log at warn.
2026-11-29 22:59:11 +08:00
50 changed files with 743 additions and 1938 deletions
-15
View File
@@ -144,14 +144,6 @@ 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"
@@ -519,13 +511,6 @@ 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,4 +7,3 @@ self-hosted-runner:
- dind-sm-standard-2
- smoke-testing
- pf-testing
- rdma
-23
View File
@@ -296,29 +296,6 @@
"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`). `rdma-build.yml` owns `ci-nixl-rdma` on the `rdma` label and is the only job that saves 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`).
- 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.
+1 -3
View File
@@ -404,10 +404,8 @@ 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: 180
timeout-minutes: 90
env:
CI_PACKAGES: ${{ needs.classify-changes.outputs.packages }}
steps:
+2 -8
View File
@@ -190,8 +190,7 @@ 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.
# 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"
RUSTFLAGS: "-C target-feature=-crt-static"
steps:
- name: Checkout repository
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
@@ -202,7 +201,7 @@ jobs:
uses: ./.github/actions/setup
with:
rust-version: nightly
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-${{ 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
@@ -210,15 +209,10 @@ 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
@@ -1,139 +0,0 @@
# 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,8 +2,6 @@ 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
+225 -418
View File
File diff suppressed because it is too large Load Diff
+15 -17
View File
@@ -40,7 +40,6 @@ 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
@@ -193,13 +192,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.6.0"
http = "1.5.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.5.0" }
rustfs-kafka-async = { version = "1.4.1" }
slab = { version = "0.4.12" }
socket2 = { version = "0.6.5" }
tokio = { version = "1.54.1" }
@@ -225,7 +224,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.1"
byteorder = "1.5.0"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.3"
prost = "0.14.6"
@@ -270,7 +269,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.1.0" }
jiff = { version = "1.0.3" }
time = { version = "0.3.55" }
# Database
@@ -283,15 +282,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.18"
tar-framing = "0.0.18"
tar-codec = "0.0.17"
tar-framing = "0.0.17"
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.130.0" }
aws-sdk-sts = { default-features = false, version = "1.129.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" }
@@ -358,7 +357,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.1", default-features = false, features = ["std", "svg"] }
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
pin-project-lite = "0.2.18"
pretty_assertions = "1.4.1"
rand = { version = "0.10.4" }
@@ -379,7 +378,7 @@ siphasher = "1.0.4"
smallvec = { version = "1.16.6" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.2" }
starshard = { version = "2.4.1" }
strum = { version = "0.28.0" }
sync_wrapper = "1.0.2"
sysinfo = "0.40.5"
@@ -401,15 +400,15 @@ vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.1"
winapi-util = "0.1.11"
windows = { version = "0.101.0" }
windows-sys = "0.101.0"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
xxhash-rust = { version = "0.8.21" }
zip = "9.9.0"
zstd = "0.14.5"
# Observability and Metrics
metrics = "0.25.1"
metrics-util = "0.21"
metrics = "0.24.6"
metrics-util = "0.20"
dial9 = { version = "0.5.9", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
@@ -417,7 +416,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.2" }
opentelemetry-stdout = { version = "0.33.1" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
@@ -432,7 +431,7 @@ russh-sftp = "4.0.0"
dav-server = "0.12.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.6" }
rustfs-mimalloc = { version = "0.7.5" }
# 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
@@ -484,7 +483,6 @@ 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,9 +45,6 @@ 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";
@@ -97,9 +94,6 @@ 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;
+2 -10
View File
@@ -2944,14 +2944,6 @@ 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,
@@ -3427,7 +3419,7 @@ mod tests {
pause.reached().await;
let at_seed = overwrites.load(Ordering::SeqCst);
assert!(
read_test_ledger_synchronized(&job).await.scan_seed.is_some(),
read_test_ledger(&job).await.scan_seed.is_some(),
"the recount seeded over in-flight writes"
);
// Admitted after the seed and visible to the walk: counted twice.
@@ -3437,7 +3429,7 @@ mod tests {
pause.0.release.notify_one();
drain_reconciliation_scheduler(&job).await;
let published = read_test_ledger_synchronized(&job).await;
let published = read_test_ledger(&job).await;
let live = 10 + 35 + 1 + 5;
assert!(published.scan_seed.is_none(), "the overlapping recount published");
assert_eq!(
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
};
use super::replication_resyncer::{
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
replicate_object_with_outcome, update_resync_status_cas,
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
};
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::{
@@ -1329,12 +1329,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let storage = self.storage.clone();
let stats = self.stats.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1389,12 +1391,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1434,6 +1438,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
let handle = tokio::spawn(async move {
@@ -1453,7 +1458,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let Some(operation) = operation else { break };
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
self.task_handles.lock().await.push(handle);
@@ -1935,7 +1941,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -1953,7 +1966,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
.await;
}
}
@@ -1970,7 +1984,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -2539,6 +2560,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
stats: Arc<ReplicationStats>,
storage: Arc<S>,
in_flight: Arc<ReplicationInFlight>,
mrf_save_tx: &Sender<MrfReplicateEntry>,
) {
match operation {
ReplicationOperation::Object(obj_info) => {
@@ -2548,7 +2570,14 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
replicate_delete(*del_info, storage).await;
// The delete request already succeeded, so a source lock that is
// still held (a bulk delete keeps its key locks until the whole
// batch commits) must not cost the replication: journal it for
// the next MRF replay.
let retry_entry = del_info.to_mrf_entry();
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
}
}
}
}
@@ -4506,6 +4535,102 @@ mod tests {
}
}
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
async fn delete_worker_journal(
delete: DeletedObjectReplicationInfo,
writeback_error: EcstoreError,
) -> Vec<MrfReplicateEntry> {
let shared = empty_resync_shared_state();
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
process_replication_operation(
ReplicationOperation::Delete(Box::new(delete)),
Arc::new(ReplicationStats::new()),
storage,
Arc::new(ReplicationInFlight::default()),
&mrf_save_tx,
)
.await;
drop(mrf_save_tx);
let mut journaled = Vec::new();
while let Some(entry) = mrf_save_rx.recv().await {
journaled.push(entry);
}
journaled
}
fn purged_on_target_delete(
arn: &str,
version_id: Uuid,
target_status: VersionPurgeStatusType,
) -> DeletedObjectReplicationInfo {
DeletedObjectReplicationInfo {
bucket: "source".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "purged".to_string(),
version_id: Some(version_id),
replication_state: Some(ReplicationState {
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
..Default::default()
}),
..Default::default()
},
op_type: ReplicationType::Delete,
..Default::default()
}
}
#[tokio::test]
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
let arn = "arn:test";
let version_id = Uuid::new_v4();
// A bulk delete of the same key still holds the object lock.
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
));
let journaled =
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
assert_eq!(
journaled.len(),
1,
"a delete whose result never reached the source must be kept for replay"
);
let entry = &journaled[0];
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
assert_eq!(entry.version_id, Some(version_id));
assert_eq!(entry.op, MrfOpKind::Delete);
assert_eq!(entry.target_arns, vec![arn.to_string()]);
}
#[tokio::test]
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
let arn = "arn:test";
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
let completed = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
source_gone(),
)
.await;
assert!(completed.is_empty(), "a completed delete must not be replayed");
let target_pending = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
source_gone(),
)
.await;
assert!(
target_pending.is_empty(),
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
);
}
#[tokio::test]
async fn delete_worker_preserves_persisted_admission_without_live_config() {
let arn = "arn:test";
@@ -2422,12 +2422,40 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
let _ = replicate_delete_with_outcome(dobj, storage).await;
}
/// How one delete replication attempt ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeleteReplicationAttempt {
/// Every admitted target finished and the source state was persisted.
Completed,
/// The attempt did not finish for a reason another path already owns: a
/// target failure is recorded in the persisted state for the scanner, and
/// a force delete or delete-marker purge journals its own intent.
Unfinished,
/// A source-side lock or read kept the attempt from running, or from
/// persisting its result. Nothing durable records that, so the caller must
/// keep the delete for a later attempt.
SourceDeferred,
}
impl DeleteReplicationAttempt {
fn from_finished(finished: bool) -> Self {
if finished { Self::Completed } else { Self::Unfinished }
}
}
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> bool {
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
}
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> DeleteReplicationAttempt {
if dobj.delete_object.force_delete {
return replicate_force_delete_to_targets(&dobj, storage).await;
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
}
let bucket = dobj.bucket.clone();
@@ -2472,7 +2500,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::Unfinished;
}
};
let target_arns = dobj.admitted_target_arns();
@@ -2480,7 +2508,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// Batch expiry can return an empty state after removing the source.
// It owes no remote work or local writeback. Persisted target admission
// must still be honored even when the live configuration is gone.
return true;
return DeleteReplicationAttempt::Completed;
}
if dobj.delete_object.delete_marker
@@ -2502,7 +2530,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
reason = "source_not_delete_marker",
"Skipping stale delete-marker replication"
);
return true;
return DeleteReplicationAttempt::Completed;
}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
debug!(
@@ -2520,7 +2548,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// purge-intent replay landing here on purpose). Purge instead
// of just skipping; the result decides whether an MRF replay
// may acknowledge the entry.
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
}
Err(err) => {
// A transient source error (lock timeout, IO error) must not
@@ -2529,7 +2557,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// target mint one more delete marker (rustfs#6823). Fail the
// entry without touching the target; the MRF replay / heal
// scanner retries once the source is readable again.
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2554,7 +2582,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
}
}
@@ -2565,7 +2593,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
{
Ok(ns_lock) => ns_lock,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2589,14 +2617,14 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
Ok(lock_guard) => lock_guard,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2620,7 +2648,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
@@ -2858,7 +2886,12 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
}
};
replicate_delete_outcome(
if !state_persisted {
// The targets were driven, but the result never reached the source
// metadata, so a scanner pass would still see the pre-attempt state.
return DeleteReplicationAttempt::SourceDeferred;
}
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
expected_targets,
rinfos.targets.len(),
state_persisted,
@@ -2866,7 +2899,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// error returns early above instead of replicating unverified.
true,
&replication_status,
)
))
}
/// Reads the source version addressed by `delete_marker_version_id` so a
-11
View File
@@ -957,22 +957,11 @@ fn data_usage_contains_bucket(data_usage_info: &DataUsageInfo, bucket: &str) ->
}
fn advance_data_usage_last_update(data_usage_info: &mut DataUsageInfo) {
let previous = data_usage_info.snapshot_identity();
let now = SystemTime::now();
data_usage_info.last_update = Some(match data_usage_info.last_update {
Some(last_update) if last_update >= now => last_update.checked_add(Duration::from_nanos(1)).unwrap_or(now),
_ => now,
});
let current = data_usage_info.snapshot_identity();
// Namespace cleanup advances the root revision without rescanning the surviving buckets.
// Carry only observations bound to the root we read. Their sources and completion times stay intact.
data_usage_info.usage_snapshot_bucket_observations.retain(|_, observation| {
if observation.snapshot_identity != previous {
return false;
}
observation.snapshot_identity = current;
true
});
}
#[cfg(test)]
@@ -119,64 +119,6 @@ fn companion_only_observed_snapshot_does_not_create_a_legacy_quota_baseline() {
);
}
#[tokio::test]
async fn namespace_cleanup_preserves_the_observation_of_an_unrelated_bucket() {
let bucket = "pending-bucket";
let incarnation = uuid::Uuid::from_u128(31);
let original = companion_snapshot(bucket, incarnation);
let observation = &original.usage_snapshot_bucket_observations[bucket];
let store = UsageCasStore::default();
store.state.lock().await.object = Some((serde_json::to_vec(&original).expect("encode usage root"), 1));
remove_bucket_usage_from_object_with_retries(&store, DATA_USAGE_OBJ_NAME_PATH.as_str(), "new-bucket", 0, None, None)
.await
.expect("fence the new bucket's namespace");
let (mut saved, _) = load_data_usage_for_bucket_removal(&store, DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("read updated usage root")
.expect("usage root remains present");
assert!(saved.last_update > original.last_update);
assert_eq!(saved.scanner_cycle, original.scanner_cycle);
assert_eq!(saved.scanner_epoch, original.scanner_epoch);
assert_eq!(saved.buckets_usage[bucket], original.buckets_usage[bucket]);
let retained = &saved.usage_snapshot_bucket_observations[bucket];
assert_eq!(retained.completed_at, observation.completed_at);
assert_eq!(retained.sources, observation.sources);
assert_eq!(
saved.project_bucket_observations_for_admin(&HashMap::from([(bucket.to_string(), incarnation.to_string())])),
1
);
assert_eq!(saved.buckets_usage[bucket].size, observation.usage.size);
assert!(!saved.buckets_usage.contains_key("new-bucket"));
}
#[test]
fn namespace_cleanup_cannot_make_a_mismatched_observation_current() {
let bucket = "pending-bucket";
let incarnation = uuid::Uuid::from_u128(31);
let mut snapshot = companion_snapshot(bucket, incarnation);
let future = SystemTime::now() + Duration::from_secs(3600);
snapshot.last_update = Some(future);
// With a future root timestamp, the namespace fence advances it by one nanosecond.
let next = future + Duration::from_nanos(1);
snapshot
.usage_snapshot_bucket_observations
.get_mut(bucket)
.expect("test observation")
.snapshot_identity
.last_update = Some(next);
advance_data_usage_last_update(&mut snapshot);
assert_eq!(snapshot.last_update, Some(next));
assert_eq!(
snapshot.project_bucket_observations_for_admin(&HashMap::from([(bucket.to_string(), incarnation.to_string())])),
0
);
assert_eq!(snapshot.buckets_usage[bucket].size, 100);
}
#[test]
fn bucket_removal_discards_companions_even_without_a_canonical_entry() {
let mut snapshot = companion_snapshot("bucket", uuid::Uuid::from_u128(31));
+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: 1 };
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
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();
+2 -4
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: 1 };
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: true };
(*rename_info).RootDirectory = dst_parent.as_raw_handle();
(*rename_info).FileNameLength = file_name_length;
std::ptr::copy_nonoverlapping(
@@ -7753,9 +7753,7 @@ 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: u8::from(delete_file),
};
let mut disposition = FILE_DISPOSITION_INFORMATION { DeleteFile: 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();
@@ -3922,7 +3922,6 @@ 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);
@@ -4021,19 +4020,6 @@ 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(),
@@ -4042,8 +4028,6 @@ 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);
@@ -4136,7 +4120,6 @@ 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;
@@ -7624,35 +7607,6 @@ 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;
-20
View File
@@ -1,20 +0,0 @@
[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
@@ -1,82 +0,0 @@
// 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+"))
}));
}
}
}
+16 -9
View File
@@ -169,24 +169,34 @@ 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 covers the current local disk set
- and the per-disk cache is fully populated
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.
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.
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.
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.
### 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 preserves the last published cache and pending dirty marks.
- If a dirty-subset refresh reports partial errors, that cycle fails and the caller falls back to a full refresh to recover consistency.
## Relationship to the RustFS Main Flow
`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.
This crate provides capacity primitives only. The actual RustFS integration lives in `rustfs/src/capacity/service.rs`.
`crates/ecstore/src/set_disk/mod.rs` records capacity scopes so object writes, heal operations, and data movement can mark affected disks dirty.
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.
## Public API
@@ -278,7 +288,6 @@ 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 |
@@ -287,8 +296,6 @@ 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.
+16 -9
View File
@@ -169,24 +169,34 @@ crate 不是“超时就直接失败”的设计:
- `disk_cache_complete == true`
- 也就是系统已经完成过一次“无部分错误”的全盘刷新
- 并且每盘缓存覆盖当前本地盘集合
- 并且成功拿到了每盘缓存
首次刷新会建立聚合基线。没有脏盘且原基线仍适用时,定时刷新保持空闲。本地盘成员变化时触发全量刷新,包括盘数相同的替换。存在脏盘但每盘基线不完整时,也执行全量刷新。
若当前还没有任何聚合缓存,系统会先执行一次全盘刷新来建立初始值。已有聚合缓存后,定时刷新在没有脏盘时会保持 idle,不再重复遍历未变化的磁盘。若 per-disk cache 尚不完整但存在脏盘,系统仍执行全盘刷新,因为此时不能安全合并子集结果。
全盘刷新达到时间预算后,可以发布估算聚合值。拓扑变化后的全量刷新若超时或降级,会丢弃旧的每盘基线,并发布当前可用的聚合值。超时估算会确认扫描开始前的脏标记,扫描过程中记录的新标记仍会保留。
全盘刷新达到时间预算后,可以发布估算聚合值,但不会借此建立完整 per-disk 基线。该有界估算会确认扫描开始前的脏标记;扫描过程中记录的新标记仍会保留。这样既不会把估算值当成精确值,也不会让一个旧脏标记永久触发超时循环。
### 子集刷新后的合并规则
- 全盘刷新成功时,`per_disk` 会完整替换 `disk_cache`。
- dirty subset 刷新成功时,只更新对应脏盘的缓存条目。
- 总容量会基于更新后的 `disk_cache` 重新求和,而不是盲信子集扫描返回的局部和。
- 若脏盘子集刷新出现部分错误,则本轮失败,保留上次发布的缓存和待处理脏标记。
- 若 dirty subset 刷新出现 partial errors,则当前轮次失败,并回退到全盘刷新恢复一致性。
## 与 RustFS 主流程的关系
`rustfs/src/capacity/service.rs` 启动后台容量管理器,并在每轮定时刷新时发现当前本地盘。管理器通过 `rustfs_capacity_current_bytes` 发布缓存的容量估算值。管理接口的存储用量取自存储信息 API。
这个 crate 本身只提供容量能力,真正把它接到 RustFS 主流程的是 `rustfs/src/capacity/service.rs`。
`crates/ecstore/src/set_disk/mod.rs` 记录容量作用域,以便对象写入、修复和数据迁移标记受影响的磁盘。
上层使用方式大致如下:
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。
## 公开 API
@@ -278,7 +288,6 @@ 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` | 是否跟随符号链接 |
@@ -287,8 +296,6 @@ 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` 缓存:
+45 -154
View File
@@ -29,8 +29,6 @@ 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,
@@ -88,8 +86,6 @@ 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
@@ -157,8 +153,6 @@ 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(
@@ -291,11 +285,6 @@ 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 {
@@ -364,7 +353,8 @@ 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.
/// Independent of `is_estimated`, which describes how bytes were measured.
/// `is_estimated` only reflects sampling; this flag is the only carrier of
/// the "some disks failed to scan" fact (backlog#1014).
pub degraded: bool,
/// Whether the scan reached its time budget and returned a fallback estimate.
pub timed_out: bool,
@@ -764,6 +754,7 @@ 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
@@ -796,6 +787,7 @@ 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())),
}
@@ -819,46 +811,18 @@ 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, 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 {
pub async fn update_capacity(&self, mut update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
let start = Instant::now();
if !update.per_disk.is_empty() || update.degraded {
let mut disk_cache = self.disk_cache.write().await;
let replaces_cache = !update.per_disk.is_empty()
&& update.replaces_disk_cache
&& update.expected_disk_count == Some(update.per_disk.len());
if replaces_cache {
disk_cache.clear();
} 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();
}
}
let mut disk_cache_complete = self.disk_cache_complete.write().await;
// 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() {
let recompute = if !update.per_disk.is_empty()
&& update.replaces_disk_cache
&& update.expected_disk_count == Some(update.per_disk.len())
{
disk_cache.clear();
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
@@ -869,12 +833,35 @@ impl HybridCapacityManager {
},
);
}
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;
*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);
}
}
@@ -1064,33 +1051,15 @@ 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.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)))
*self.disk_cache_complete.read().await
}
/// 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.
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>
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>>,
@@ -1172,7 +1141,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.commit_capacity(update, source, full_scan_disks).await),
Ok(update) => Ok(self.update_capacity(update, source).await),
Err(err) => Err(err),
};
let refresh_duration = refresh_start.elapsed();
@@ -1458,8 +1427,8 @@ async fn run_scheduled_capacity_refresh(manager: Arc<HybridCapacityManager>, dis
"capacity refresh scheduled"
);
let result = manager
.refresh_or_join_for_disks(DataSource::Scheduled, (!dirty_subset).then_some(disks.as_slice()), || {
refresh_capacity_with_scope(&disks, dirty_subset)
.refresh_or_join(DataSource::Scheduled, move || async move {
refresh_capacity_with_scope(disks, dirty_subset).await
})
.await;
scheduled_refresh_was_clean(&result)
@@ -2507,84 +2476,6 @@ 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());
+52 -168
View File
@@ -12,8 +12,6 @@
// 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,
@@ -25,8 +23,6 @@ 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};
@@ -202,10 +198,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, limits: ScanLimits) -> DiskScanOutcome {
async fn scan_disk_used_capacity(disk: CapacityDiskRef) -> DiskScanOutcome {
let disk_label = disk_metric_label(&disk);
let start = Instant::now();
let result = get_dir_size_async(Path::new(&disk.drive_path), limits).await;
let result = get_dir_size_async(Path::new(&disk.drive_path)).await;
let disk = CapacityScopeDisk {
endpoint: disk.endpoint,
drive_path: disk.drive_path,
@@ -236,14 +232,7 @@ 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 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);
let mut scans = stream::iter(disks.iter().cloned().map(scan_disk_used_capacity)).buffer_unordered(concurrency_limit);
while let Some(outcome) = scans.next().await {
match outcome.result {
@@ -362,43 +351,38 @@ 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 capacity_manager.get_capacity().await.is_some() {
return if disks.is_empty() || capacity_manager.get_capacity().await.is_some() {
ScheduledCapacityRefresh::Idle
} else {
full_scan()
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
};
}
if cached_topology_matches.is_none() {
return full_scan();
if !capacity_manager.can_refresh_dirty_subset().await {
return ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
}
let dirty_set: HashSet<_> = dirty_disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
let dirty_set: HashSet<CapacityScopeDisk> = dirty_disks.into_iter().collect();
let selected: Vec<_> = disks
.iter()
.filter(|disk| dirty_set.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
.filter(|disk| dirty_set.contains(&disk_scope_key(disk)))
.cloned()
.collect();
if selected.is_empty() || selected.len() >= disks.len() {
full_scan()
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
} else {
ScheduledCapacityRefresh::Scan {
disks: selected,
@@ -420,13 +404,9 @@ pub async fn select_capacity_refresh_disks(
}
#[hotpath::measure]
pub async fn refresh_capacity_with_scope(
disks: impl AsRef<[CapacityDiskRef]>,
dirty_subset: bool,
) -> Result<CapacityUpdate, String> {
let disks = disks.as_ref();
pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subset: bool) -> Result<CapacityUpdate, String> {
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())?;
@@ -441,8 +421,8 @@ pub async fn refresh_capacity_with_scope(
/// Scan the provided local disk roots and return a summarized used-capacity result.
///
/// 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.
/// 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.
pub async fn scan_used_capacity_disks(
disks: &[CapacityDiskRef],
) -> Result<CapacityScanSummary, Box<dyn std::error::Error + Send + Sync>> {
@@ -571,8 +551,6 @@ struct ScanLimits {
sample_rate: usize,
enable_dynamic_timeout: bool,
follow_symlinks: bool,
#[cfg(target_os = "linux")]
mount_usage: Option<Arc<MountUsageSnapshot>>,
}
impl ScanLimits {
@@ -594,7 +572,6 @@ impl ScanLimits {
sample_rate
};
let follow_symlinks = get_follow_symlinks();
Self {
max_files_threshold: get_max_files_threshold(),
base_timeout: get_stat_timeout(),
@@ -602,15 +579,15 @@ impl ScanLimits {
max_timeout: get_max_timeout(),
sample_rate: effective_sample_rate,
enable_dynamic_timeout: get_enable_dynamic_timeout(),
follow_symlinks,
#[cfg(target_os = "linux")]
mount_usage: (get_use_mount_usage() && !follow_symlinks).then(|| Arc::new(MountUsageSnapshot::default())),
follow_symlinks: get_follow_symlinks(),
}
}
}
/// Filesystem usage at a device boundary. This check cannot establish sole
/// ownership or distinguish a whole filesystem from a cross-device bind mount.
/// 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.
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()?;
@@ -647,7 +624,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(
fallback_mount_path: Option<&Path>,
path: &Path,
reason: &'static str,
exact_prefix_bytes: u64,
overflow_sampled_bytes: u64,
@@ -662,7 +639,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 = fallback_mount_path.and_then(mount_point_used_bytes);
let disk_used = mount_point_used_bytes(path);
let used_bytes = combine_timeout_estimates(seen_estimate, disk_used, exact_prefix_bytes)?;
info!(
@@ -722,8 +699,9 @@ impl Drop for ScanCancellationGuard {
}
}
async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityScanResult, std::io::Error> {
async fn get_dir_size_async(path: &Path) -> 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
@@ -756,13 +734,6 @@ async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityS
}
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,
@@ -771,28 +742,13 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
sample_rate: effective_sample_rate,
enable_dynamic_timeout,
follow_symlinks,
..
} = *limits;
{
#[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()
});
}
if !path.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Directory not found: {:?}", path),
));
}
// Resolve the scan root before walking. A drive_path that is itself a
@@ -805,13 +761,7 @@ 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;
@@ -866,7 +816,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(
fallback_mount_path,
path,
"timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -1039,7 +989,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(
fallback_mount_path,
path,
"final_timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -1270,8 +1220,6 @@ mod tests {
sample_rate: 3,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
};
let result =
@@ -1288,7 +1236,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(Some(temp_dir.path()), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
let result = timeout_fallback_estimate(temp_dir.path(), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
.expect("sampled timeout should produce a fallback estimate");
assert!(result.timed_out);
@@ -1300,7 +1248,7 @@ mod tests {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
assert_eq!(size.used_bytes, 0);
assert_eq!(size.file_count, 0);
}
@@ -1317,7 +1265,7 @@ mod tests {
file.write_all(b"Hello, World!").unwrap();
drop(file);
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
assert_eq!(size.used_bytes, 13);
assert_eq!(size.file_count, 1);
}
@@ -1336,7 +1284,7 @@ mod tests {
file.write_all(b"test").unwrap();
}
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
assert_eq!(size.used_bytes, 40);
assert_eq!(size.file_count, 10);
}
@@ -1361,14 +1309,14 @@ mod tests {
f2.write_all(b"content2").unwrap();
drop(f2);
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
let size = get_dir_size_async(temp_dir.path()).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"), ScanLimits::from_env()).await;
let result = get_dir_size_async(Path::new("/nonexistent/path")).await;
assert!(result.is_err());
}
@@ -1476,45 +1424,12 @@ mod tests {
assert_eq!(combine_timeout_estimates(None, None, 40), None);
}
#[cfg(target_os = "linux")]
#[test]
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);
}
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);
}
#[test]
@@ -1537,8 +1452,6 @@ mod tests {
sample_rate: 1,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
}
}
@@ -1938,35 +1851,6 @@ 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)]
@@ -1985,7 +1869,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(), ScanLimits::from_env()).await
get_dir_size_async(scan_dir.path()).await
})
.await
.unwrap();
@@ -2010,7 +1894,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(), ScanLimits::from_env()).await
get_dir_size_async(scan_dir.path()).await
})
.await
.unwrap();
-2
View File
@@ -70,8 +70,6 @@ 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)]
+23 -109
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::{DiskInfo, IOStats, fs_type::get_fs_type};
use rustix::fs::{AtFlags, Mode, OFlags, StatFs, StatxAttributes, StatxFlags, fstatfs, open, statfs, statx};
use std::collections::{BTreeSet, HashMap, HashSet};
use rustix::fs::statfs;
use std::collections::BTreeSet;
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, Error, ErrorKind, Read};
@@ -27,10 +27,27 @@ 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 path = p.as_ref();
let stat = statfs(path)?;
let (total, free, used) = statfs_space_usage(&stat, path)?;
let st = rustix::fs::stat(path)?;
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())?;
Ok(DiskInfo {
total,
@@ -45,84 +62,6 @@ 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) {
@@ -511,31 +450,6 @@ 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();
+1 -3
View File
@@ -24,9 +24,7 @@ mod unix;
mod windows;
#[cfg(target_os = "linux")]
pub use linux::{
MountUsageSnapshot, check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk,
};
pub use linux::{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};
+36 -32
View File
@@ -13,7 +13,7 @@
# limitations under the License.
services:
# RustFS single-node single-disk (SNSD) service
# RustFS main service
rustfs:
image: rustfs/rustfs:latest
container_name: rustfs-server
@@ -23,29 +23,31 @@ services:
security_opt:
- "no-new-privileges:true"
ports:
- "${RUSTFS_S3_PORT:-9000}:9000" # S3 API port
- "${RUSTFS_CONSOLE_PORT:-9001}:9001" # Console port
- "9000:9000" # S3 API port
- "9001:9001" # Console port
environment:
- RUSTFS_VOLUMES=/data
- RUSTFS_VOLUMES=/data/rustfs{0...3}
- 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=${RUSTFS_ACCESS_KEY:-rustfsadmin} # CHANGEME
- RUSTFS_SECRET_KEY=${RUSTFS_SECRET_KEY:-rustfsadmin} # CHANGEME
- RUSTFS_ACCESS_KEY=rustfsadmin # CHANGEME
- RUSTFS_SECRET_KEY=rustfsadmin # CHANGEME
- RUSTFS_OBS_LOGGER_LEVEL=info
- RUSTFS_OBS_LOG_DIRECTORY=/logs
- RUSTFS_OBS_LOG_DIRECTORY=/app/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:/data
- logs:/logs
ulimits:
nofile:
soft: 65535
hard: 65535
- rustfs_data_0:/data/rustfs0
- rustfs_data_1:/data/rustfs1
- rustfs_data_2:/data/rustfs2
- rustfs_data_3:/data/rustfs3
- logs:/app/logs
networks:
- rustfs-network
restart: unless-stopped
@@ -61,21 +63,21 @@ services:
test:
[
"CMD",
"sh",
"-ec",
"host=\"$${RUSTFS_HEALTHCHECK_HOST:-127.0.0.1}\"; scheme=\"http\"; set -- -fsS --connect-timeout 3 --max-time 5; \
"sh", "-ec",
"host=\"$${RUSTFS_HEALTHCHECK_HOST:-127.0.0.1}\"; scheme=\"http\"; set -- -fsS; \
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\"; \
set -- \"$${@}\" --cacert \"$${ca_path}\" --resolve \"$${host}:9000:127.0.0.1\" --resolve \"$${host}:9001:127.0.0.1\"; \
else \
set -- \"$${@}\" -k; \
fi; \
fi; \
curl \"$${@}\" \"$${scheme}://$${host}:9000/health/ready\""
curl \"$${@}\" \"$${scheme}://$${host}:9000/health\" && \
curl \"$${@}\" \"$${scheme}://$${host}:9001/rustfs/console/health\""
]
interval: 30s
timeout: 10s
@@ -84,28 +86,30 @@ services:
# RustFS volume permissions fixer service
volume-permission-helper:
image: alpine:3.24
network_mode: none
image: alpine
volumes:
- rustfs_data:/data
- logs:/logs
- rustfs_data_0:/data/rustfs0
- rustfs_data_1:/data/rustfs1
- rustfs_data_2:/data/rustfs2
- rustfs_data_3:/data/rustfs3
- logs:/app/logs
command: >
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"
'
sh -c "
chown -R 10001:10001 /data/rustfs0 /data/rustfs1 /data/rustfs2 /data/rustfs3 /app/logs &&
echo 'Volume Permissions fixed' &&
exit 0
"
# 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:
rustfs_data_0:
rustfs_data_1:
rustfs_data_2:
rustfs_data_3:
logs:
@@ -11,10 +11,6 @@
## 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,8 +98,6 @@ 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,7 +65,6 @@ 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 |
+97 -238
View File
@@ -796,9 +796,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.163.0"
version = "1.162.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c"
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -825,7 +825,7 @@ dependencies = [
"lru",
"percent-encoding",
"regex-lite",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
"url",
]
@@ -924,7 +924,7 @@ dependencies = [
"http",
"p256",
"percent-encoding",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"time",
"tracing",
@@ -959,7 +959,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
]
@@ -1364,9 +1364,9 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "byteorder"
version = "1.5.1"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
[[package]]
name = "bytes"
@@ -1512,7 +1512,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -3014,7 +3014,7 @@ checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"subtle",
]
@@ -3636,7 +3636,7 @@ checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
dependencies = [
"cfg-if",
"libc",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -3656,9 +3656,9 @@ checksum = "b4db3c637c6c3cf7120ab641f12f83aa19dfa015679ac1b29e16b15684c7a3e3"
[[package]]
name = "http"
version = "1.6.0"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa",
@@ -3804,7 +3804,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.62.2",
"windows-core",
]
[[package]]
@@ -3957,9 +3957,9 @@ dependencies = [
[[package]]
name = "io-uring"
version = "0.7.17"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123"
checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@@ -3975,7 +3975,7 @@ dependencies = [
"socket2",
"widestring",
"windows-registry",
"windows-result 0.4.1",
"windows-result",
"windows-sys 0.61.2",
]
@@ -4041,23 +4041,23 @@ dependencies = [
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
name = "jiff"
version = "1.1.0"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92"
checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f"
dependencies = [
"jiff-core 1.1.0",
"jiff-static 1.1.0",
"jiff-core 1.0.2",
"jiff-static 1.0.3",
"jiff-tzdb-platform 1.0.0",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -4072,9 +4072,9 @@ dependencies = [
[[package]]
name = "jiff-core"
version = "1.1.0"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79"
checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f"
dependencies = [
"log",
]
@@ -4093,11 +4093,11 @@ dependencies = [
[[package]]
name = "jiff-static"
version = "1.1.0"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3"
checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8"
dependencies = [
"jiff-core 1.1.0",
"jiff-core 1.0.2",
"proc-macro2",
"quote",
"syn 3.0.9",
@@ -4147,7 +4147,7 @@ dependencies = [
"simd_cesu8",
"thiserror",
"walkdir",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -4527,9 +4527,9 @@ dependencies = [
[[package]]
name = "metrics"
version = "0.25.1"
version = "0.24.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb1b882a87a42420c952fbb7173ff4fa5d380b51eb26c95bf77435811201db7a"
checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2"
dependencies = [
"portable-atomic",
"rapidhash",
@@ -5055,7 +5055,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -5094,7 +5094,7 @@ dependencies = [
"libc",
"redox_syscall 0.5.18",
"smallvec",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -5106,7 +5106,7 @@ dependencies = [
"libc",
"redox_syscall 0.9.5",
"smallvec",
"windows-link 0.2.1",
"windows-link",
]
[[package]]
@@ -5422,7 +5422,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.3",
"sha2 0.11.2",
"stringprep",
]
@@ -6170,7 +6170,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -6253,7 +6253,7 @@ dependencies = [
"http",
"md-5",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"xxhash-rust",
]
@@ -6299,7 +6299,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
]
@@ -6317,7 +6317,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
]
@@ -6362,7 +6362,7 @@ dependencies = [
"hyper",
"hyper-rustls",
"hyper-util",
"jiff 1.1.0",
"jiff 1.0.3",
"lazy_static",
"libc",
"md-5",
@@ -6414,7 +6414,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"shadow-rs",
"slab",
"smallvec",
@@ -6432,7 +6432,7 @@ dependencies = [
"urlencoding",
"uuid",
"winapi-util",
"windows-sys 0.101.0",
"windows-sys 0.61.2",
"xxhash-rust",
]
@@ -6476,7 +6476,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"time",
"tokio",
@@ -6492,7 +6492,7 @@ dependencies = [
"arbitrary",
"bytes",
"http",
"jiff 1.1.0",
"jiff 1.0.3",
"libfuzzer-sys",
"quick-xml 0.42.0",
"rustfs-ecstore",
@@ -6510,7 +6510,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
"tokio",
"uuid",
@@ -6542,7 +6542,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
"twox-hash",
"unicode-normalization",
@@ -6592,9 +6592,9 @@ dependencies = [
[[package]]
name = "rustfs-kafka"
version = "1.5.0"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d66b41fff6ef985a310f7dac070fda947b7588e56decd837084c41edc24841a0"
checksum = "82dc39ba1a5a9f6b2e49decb0b54c23ebaebdfb08a899307c266694bfd269bf9"
dependencies = [
"base64 0.23.1",
"bytes",
@@ -6606,7 +6606,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"socket2",
"thiserror",
"tracing",
@@ -6617,21 +6617,20 @@ dependencies = [
[[package]]
name = "rustfs-kafka-async"
version = "1.5.0"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ceb19d7045aa067259792637be2f72c971aece9ccaf7f6c76ec7ac272904d37"
checksum = "684f5e78ea1421bbf915e4cd0515bdefd587cfa281da000e41ae4a434f90195a"
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.3",
"sha2 0.11.2",
"tokio",
"tokio-rustls",
"tracing",
@@ -6655,7 +6654,7 @@ dependencies = [
"chacha20poly1305",
"hex-simd",
"hotpath",
"jiff 1.1.0",
"jiff 1.0.3",
"md-5",
"metrics",
"moka",
@@ -6666,7 +6665,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"thiserror",
"tokio",
@@ -6725,7 +6724,7 @@ dependencies = [
"http",
"humantime",
"hyper",
"jiff 1.1.0",
"jiff 1.0.3",
"reqwest",
"rustfs-signer",
"serde",
@@ -6743,7 +6742,7 @@ dependencies = [
"form_urlencoded",
"hashbrown 0.17.2",
"hotpath",
"jiff 1.1.0",
"jiff 1.0.3",
"metrics",
"percent-encoding",
"quick-xml 0.42.0",
@@ -6796,7 +6795,7 @@ dependencies = [
"base64-simd",
"futures",
"ipnetwork",
"jiff 1.1.0",
"jiff 1.0.3",
"jsonwebtoken",
"moka",
"regex",
@@ -6879,7 +6878,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"tokio",
"tokio-util",
@@ -6920,7 +6919,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"time",
"tokio",
@@ -6972,7 +6971,7 @@ dependencies = [
"futures-core",
"hotpath",
"http",
"jiff 1.1.0",
"jiff 1.0.3",
"lz4",
"lz4_flex",
"memchr",
@@ -7017,7 +7016,7 @@ dependencies = [
name = "rustfs-scanner-metrics"
version = "1.0.8"
dependencies = [
"jiff 1.1.0",
"jiff 1.0.3",
"metrics",
"rmp-serde",
"rustfs-heal-contracts",
@@ -7093,7 +7092,7 @@ dependencies = [
"hotpath",
"hyper",
"hyper-rustls",
"jiff 1.1.0",
"jiff 1.0.3",
"lapin",
"libc",
"metrics",
@@ -7115,7 +7114,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"snap",
"sysinfo",
"thiserror",
@@ -7140,7 +7139,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"serde",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror",
"tokio",
"tracing",
@@ -7149,9 +7148,8 @@ dependencies = [
[[package]]
name = "rustfs-uring"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba"
version = "0.3.0"
source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf"
dependencies = [
"io-uring",
"libc",
@@ -7185,14 +7183,14 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"siphasher",
"snap",
"tokio",
"tracing",
"transform-stream",
"url",
"windows 0.101.0",
"windows",
"zstd 0.14.5",
]
@@ -7553,9 +7551,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.3"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -7786,9 +7784,9 @@ dependencies = [
[[package]]
name = "starshard"
version = "2.4.2"
version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adc82b6d069d07eb9b6433ccabdaf31ea1508cd240f6fe12284e0dd3d7609bd5"
checksum = "b0883700b50fd0b62120ebc4c07230e02f0cf1ead474c3b3b44eaa13e0a999ea"
dependencies = [
"async-trait",
"hashbrown 0.17.2",
@@ -7904,9 +7902,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.5"
version = "0.40.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
dependencies = [
"libc",
"memchr",
@@ -7915,7 +7913,7 @@ dependencies = [
"objc2-io-kit",
"objc2-open-directory",
"rayon",
"windows 0.62.2",
"windows",
]
[[package]]
@@ -8158,7 +8156,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-postgres",
"tokio-rustls",
@@ -8849,24 +8847,10 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"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",
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
]
[[package]]
@@ -8875,16 +8859,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"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",
"windows-core",
]
[[package]]
@@ -8893,24 +8868,11 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"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",
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
@@ -8919,20 +8881,9 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"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",
"windows-core",
"windows-link",
"windows-threading",
]
[[package]]
@@ -8946,17 +8897,6 @@ 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"
@@ -8968,56 +8908,20 @@ 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 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",
"windows-core",
"windows-link",
]
[[package]]
@@ -9026,9 +8930,9 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
"windows-link",
"windows-result",
"windows-strings",
]
[[package]]
@@ -9037,16 +8941,7 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"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",
"windows-link",
]
[[package]]
@@ -9055,16 +8950,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"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",
"windows-link",
]
[[package]]
@@ -9082,16 +8968,7 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"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",
"windows-link",
]
[[package]]
@@ -9116,25 +8993,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"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",
"windows-link",
]
[[package]]
+1 -65
View File
@@ -16,7 +16,7 @@ path = "src/lib.rs"
[dependencies]
arbitrary = { version = "1", features = ["derive"] }
bytes = "1.12.2"
http = "1.6.0"
http = "1.5.0"
jiff = { version = "1.0.2", features = ["serde"] }
libfuzzer-sys = "0.4"
quick-xml = { version = "0.42.0", features = ["serialize", "serde-types", "encoding"] }
@@ -50,70 +50,6 @@ 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.6"
rustfs-mimalloc-sys = "0.7.5"
[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"] }
+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_bytes(format!("{prefix}\"{}\"", self.opaque).as_bytes())
http::HeaderValue::from_str(&format!("{prefix}\"{}\"", self.opaque))
}
pub(super) fn from_stored(value: &str) -> Self {
+1 -2
View File
@@ -85,8 +85,7 @@ pub(crate) fn post_metadata_headers(
}
}
if let Some(value) = content_type {
let wire =
HeaderValue::from_bytes(value.as_bytes()).map_err(|_| s3_error!(InvalidArgument, "Invalid POST content field"))?;
let wire = HeaderValue::from_str(value).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_bytes(value.as_bytes()).is_ok().then_some(value)
http::HeaderValue::from_str(&value).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_bytes(header.as_bytes()).is_ok());
assert!(http::HeaderValue::from_str(&header).is_ok());
assert!(header.contains("保留策略"));
}
@@ -152,14 +152,6 @@ 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()
@@ -176,23 +168,12 @@ 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,
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"),
..Default::default()
})
})
.collect::<S3Result<_>>()?;
@@ -211,8 +192,6 @@ 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,36 +84,6 @@ 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])] {
-23
View File
@@ -135,18 +135,6 @@ 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
@@ -282,17 +270,6 @@ 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, preserve_opaque_header, resp, row};
use super::{OpRow, Served, 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::{AMZ_EXPIRATION, SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
use rustfs_utils::http::{SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
use std::sync::Arc;
pub(super) const ROWS: &[OpRow] = &[
@@ -63,18 +63,9 @@ 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
.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
});
.await;
head_result(result)
}
}
@@ -104,19 +95,10 @@ 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
.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
}),
.await,
);
result.inspect_err(log_error)
}
@@ -240,7 +222,6 @@ 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 {
@@ -290,7 +271,6 @@ 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, preserve_opaque_header, row};
use super::{OpRow, Served, row};
use crate::app::RequestEnvelope;
use crate::app::multipart_usecase::{DefaultMultipartUsecase, UploadPartTarget, UploadPartWriteInput, UploadPartWriteOutput};
use crate::app::object::FrameTrailers;
@@ -275,7 +275,6 @@ 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
-1
View File
@@ -2383,7 +2383,6 @@ 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
@@ -794,7 +794,7 @@ pub fn parse_etag(object_etag: &str) -> Result<HeaderValue, S3Error> {
let etag_quoted = format!("\"{}\"", etag_trimmed);
HeaderValue::from_bytes(etag_quoted.as_bytes()).map_err(|e| {
HeaderValue::from_str(&etag_quoted).map_err(|e| {
warn!(
"Failed to convert ETag to HeaderValue (ETag: {}): {}. The ETag header will be omitted from the response.",
etag_quoted, e
@@ -807,17 +807,6 @@ 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;
},
);
+4 -21
View File
@@ -31,7 +31,6 @@
# 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
@@ -46,7 +45,6 @@ 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]*)
@@ -64,15 +62,6 @@ 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"
@@ -137,10 +126,7 @@ PY
if [ "$SKIP_BUILD" != "1" ]; then
set --
if [ -n "${CARGO_TARGET_DIR:-}" ]; then
set -- "$@" --target-dir "$CARGO_TARGET_DIR"
fi
if [ -n "$FUZZ_CODEGEN_UNITS" ]; then
set -- "$@" --codegen-units "$FUZZ_CODEGEN_UNITS"
set -- --target-dir "$CARGO_TARGET_DIR"
fi
if [ "$targets" = "$registered_targets" ]; then
# A single Cargo invocation shares the instrumented dependency build across all harnesses.
@@ -222,14 +208,11 @@ 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
set -- "$@" --target-dir "$CARGO_TARGET_DIR"
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/"
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,25 +140,4 @@ 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"
+2 -56
View File
@@ -286,48 +286,18 @@ 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 0 NA NA'
echo '0.050000 0.800000'
exit 0
fi
;;
esac
echo '0.050000 0.070000 0 NA NA'
echo '0.050000 0.070000'
SSH
cat > "$GUARD_BIN/curl" <<'CURL'
#!/usr/bin/env bash
@@ -399,28 +369,4 @@ 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"
+9 -37
View File
@@ -73,7 +73,6 @@ 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
@@ -82,8 +81,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 || $8 !~ /^[0-9]+$/ || $11 !~ /^[0-9]+$/ || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14,$8,$11
if (NF<14 || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14
got++
}
END { if (got!=n) exit 2 }
@@ -94,36 +93,10 @@ 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; 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"
}
!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 }
'
REMOTE
)
@@ -131,7 +104,7 @@ REMOTE
end=$((SECONDS+budget))
streak=0
sample_number=0
printf 'sample\tnode\tmean_queue\tpeak_queue\tcompleted_writes\twrite_ms_per_op\tpeak_write_ms_per_op\n'
printf 'sample\tnode\tmean_queue\tpeak_queue\n'
while ((end-SECONDS >= 5)); do
sample_number=$((sample_number+1))
remaining=$((end-SECONDS))
@@ -152,13 +125,12 @@ 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]+)\ ([0-9]+)\ (NA|[0-9]+\.[0-9]+)\ (NA|[0-9]+\.[0-9]+)$ ]]; then
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([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\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak" \
"${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}" "${BASH_REMATCH[5]}"
printf '%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak"
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