Compare commits

..

6 Commits

Author SHA1 Message Date
Hauser Zhi 55d58086d6 Merge branch 'main' into houseme/rename-quarantine 2026-11-21 01:19:59 +08:00
Hauser Zhi 6b98e0c8bd fix(ecstore): expose rename quarantine fault metrics
Keep admission timeouts and quarantine lifecycle visible when detailed PUT diagnostics are disabled. Tie released accounting to permit ownership so runtime cancellation cannot leave the active gauge stale.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
2026-11-20 22:17:42 +08:00
Hauser Zhi 5bb2d9c38d Merge origin/main into houseme/rename-quarantine
Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
2026-11-20 21:12:33 +08:00
Hauser Zhi 85c58c9abf Merge origin/main into houseme/rename-quarantine
Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
2026-11-20 13:14:26 +08:00
Hauser Zhi c8ad0be2fd Merge origin/main into houseme/rename-quarantine
Co-Authored-By: heihutu <heihutu@gmail.com>

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
2026-11-20 10:52:46 +08:00
Hauser Zhi 96a16c697d fix(ecstore): harden remote rename handling
Start a fresh bounded quarantine when a dispatched rename becomes ambiguous so detached disk work cannot be immediately replaced after the RPC deadline. Pre-size inline FileInfo MessagePack buffers from their resident payload to avoid proven growth without changing wire bytes or durability semantics.

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

Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
2026-11-20 10:50:32 +08:00
516 changed files with 18366 additions and 57388 deletions
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-linux=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
sha256-darwin=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
sha256-linux=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
sha256-darwin=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
+2 -2
View File
@@ -1,2 +1,2 @@
sha256-darwin=d5f2a266740f695cf6734965a4d25b390e669aaaa2fc87805c45e42de83f13ca
sha256-linux=448ac2ebd537def9f2a63b8961d80a6521f7ef05f952834ec997faed52bfb901
sha256-darwin=9ccb03f4139e99ec11a63810523d504df39191b86e74b28a72dd9a075682293b
sha256-linux=5ef052b03a03afbd00ebfcbbdcb754bbde414b7e6151aae3e2ee78024ce1d0b6
+1 -1
View File
@@ -1 +1 @@
sha256=a304838fe8ded98a781d7e2e1cf5b22a5cbc11ddfdc4fbaeea91149e5f88d699
sha256=fd5683273bba1eae3b4402a4e854a5d168ace845bd0e5fc801f8e336485a4394
+4 -5
View File
@@ -253,7 +253,7 @@ threads-required = "num-test-threads"
# peers complete durable IO. Reserve capacity from unrelated test processes;
# the shared fixture's durable_iam_state_ prefix keeps the whole family together.
[[profile.default.overrides]]
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::tests::durable_iam_state_/)'
threads-required = "num-test-threads"
# Real target-repair and rebalance-stop fixtures commit durable metadata while
@@ -582,7 +582,7 @@ threads-required = "num-test-threads"
# Keep the same IAM/state fixture capacity reservation in CI without changing the
# production lock deadline, internal concurrency, assertions, or retry policy.
[[profile.ci.overrides]]
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::tests::durable_iam_state_/)'
threads-required = "num-test-threads"
# Match the real admin fixture capacity reservation without retries or changes
@@ -731,7 +731,7 @@ test-group = 'ecstore-serial-flaky'
[profile.e2e-smoke]
default-filter = """
package(e2e_test) & (
test(/^(access_request_validation|delete_marker_migration_semantics|version_id_regression|list_objects_v2_pagination|list_object_versions_regression|list_objects_duplicates|list_buckets_double_slash|list_buckets_auth|list_buckets_iam_filter|leading_slash_key|special_chars|create_bucket_region|delete_objects_versioning|head_object_consistency|head_object_range|copy_object_metadata|copy_object_tagging|copy_source_invalid_date|content_encoding|compression|multipart_storage_class|multipart_upload_id|storage_class_capability|ssec_copy|anonymous_access|bucket_policy_check|presigned_negative|negative_sigv4|admin_auth|notification_webhook|tls_hot_reload|console_smoke|admin_iam_crud|admin_pools|sts_query_compat|data_usage)_test::|^fake_s3_target::/)
test(/^(delete_marker_migration_semantics|version_id_regression|list_objects_v2_pagination|list_object_versions_regression|list_objects_duplicates|list_buckets_double_slash|list_buckets_auth|list_buckets_iam_filter|leading_slash_key|special_chars|create_bucket_region|delete_objects_versioning|head_object_consistency|head_object_range|copy_object_metadata|copy_object_tagging|copy_source_invalid_date|content_encoding|compression|multipart_storage_class|multipart_upload_id|storage_class_capability|ssec_copy|anonymous_access|bucket_policy_check|presigned_negative|negative_sigv4|admin_auth|notification_webhook|tls_hot_reload|console_smoke|admin_iam_crud|admin_pools|sts_query_compat|data_usage)_test::|^fake_s3_target::/)
| test(/^replication_extension_test::(test_replication_check_succeeds_with_remote_target|test_replication_check_rejects_target_without_object_lock|test_set_remote_target_rejects_unversioned_source_bucket|test_replication_check_rejects_unversioned_source_bucket|test_replication_check_rejects_missing_replication_config|test_replication_check_rejects_invalid_bucket|test_set_remote_target_rejects_same_bucket_on_same_deployment|test_set_remote_target_rejects_unversioned_target_bucket|test_set_remote_target_update_requires_arn|test_set_remote_target_update_rejects_missing_target|test_set_remote_target_rejects_invalid_target_url|test_set_remote_target_rejects_self_signed_https_target_without_skip_tls_verify|test_set_remote_target_rejects_private_ca_https_target_without_ca_cert_pem|test_list_remote_targets_rejects_empty_bucket|test_list_remote_targets_rejects_invalid_bucket|test_remove_remote_target_rejects_missing_target|test_remove_remote_target_rejects_missing_arn|test_remove_remote_target_rejects_invalid_bucket|test_remove_remote_target_rejects_target_used_by_replication|test_delete_bucket_replication_removes_remote_target)$/)
| test(/^reliant::lifecycle::/)
| test(/^conditional_delete_objects_test::/)
@@ -960,11 +960,10 @@ path = "junit.xml"
# differential picks side A (shell-script stand-ins, no server, no reference
# binary). They already run on every pull request in e2e-smoke, so e2e-full
# excludes them to keep its selection digest unchanged.
# ACL admission protocol tests already run on every PR in e2e-smoke.
[profile.e2e-full]
default-filter = """
package(e2e_test)
& !test(/^(protocols|access_request_validation_test)::/)
& !test(/^protocols::/)
& !test(/^(admin_timeout_regression_test|cluster_concurrency_test|cluster_multidrive_pool_test|degraded_listing_availability_test|namespace_lock_quorum_test|object_lambda_test|stale_multipart_cleanup_cluster_test)::/)
& !test(/^distributed::/)
& !test(/^replication_extension_test::/)
-1
View File
@@ -57,7 +57,6 @@ rustfs-scanner 1392 20
rustfs-scanner-metrics 90 0
rustfs-security-governance 20 0
rustfs-signer 34 0
rustfs-sse 145 0
rustfs-storage-api 34 0
rustfs-targets 612 26
rustfs-test-utils 1 0
+2 -3
View File
@@ -6,9 +6,8 @@ runs:
- name: Install runtime tools
shell: bash
run: |
# These runners have no IPv6 route to the Git PPA inherited from the image.
sudo apt-get -o Acquire::ForceIPv4=true update
sudo apt-get -o Acquire::ForceIPv4=true install -y libssl-dev ripgrep
sudo apt-get update
sudo apt-get install -y libssl-dev ripgrep
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
- name: Install cargo-nextest
-2
View File
@@ -22,8 +22,6 @@ Identify the tested commit and any local changes. When testing a prebuilt binary
List relevant checks not run and the remaining risk. Use the validation tier in AGENTS.md; do not run broader checks solely to fill this section. For documentation-only changes, list the applicable documentation checks. Use N/A only when verification is not applicable.
-->
**auto-testing regression coverage** <!-- For each issue-backed bug fix, give the added or extended case ID or PR link, the existing case ID/path and assertion that catches the bug, or "Skipped" with a brief reason. Omit this line for other changes, including documentation-only fixes. -->
## Impact
<!--
Describe user-facing, compatibility, API, deployment, configuration, or documentation impact. Use N/A when there is no expected impact.
-24
View File
@@ -523,30 +523,6 @@
"monitor_reason": "Event-driven or operator-requested work has no periodic freshness obligation.",
"origin": "baseline"
},
{
"workflow": ".github/workflows/agent-v1-protocol-regression.yml",
"name": "Agent v1 protocol regression",
"roles": [
"pr",
"push",
"manual"
],
"events": [
"pull_request",
"push",
"workflow_dispatch"
],
"cadence": "event",
"timezone": "UTC",
"schedule": [],
"owner": "@overtrue",
"policy": "active",
"monitor": "none",
"result_owner": "agent-v1-protocol-regression.yml",
"disposition": "validates Agent v1 schemas and fixture integrity",
"monitor_reason": "Runs on changes to the Agent v1 contract and on request.",
"origin": "added"
},
{
"workflow": ".github/workflows/connect-diagnostic-schedule-acceptance.yml",
"name": "Connect diagnostic scheduler receipt acceptance",
@@ -1,47 +0,0 @@
name: Agent v1 protocol regression
on:
pull_request:
paths:
- "protocol/agent/v1/**"
- "scripts/test_agent_v1_*.py"
- "scripts/verify_agent_v1_fixtures.py"
- "scripts/run_agent_v1_regression.sh"
- "rustfs/src/connect/diagnostics/job.rs"
- "rustfs/src/connect/diagnostics/job_delivery.rs"
- ".github/workflows/agent-v1-protocol-regression.yml"
push:
paths:
- "protocol/agent/v1/**"
- "scripts/test_agent_v1_*.py"
- "scripts/verify_agent_v1_fixtures.py"
- "scripts/run_agent_v1_regression.sh"
- "rustfs/src/connect/diagnostics/job.rs"
- "rustfs/src/connect/diagnostics/job_delivery.rs"
- ".github/workflows/agent-v1-protocol-regression.yml"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: agent-v1-protocol-${{ github.ref }}
cancel-in-progress: true
jobs:
protocol-regression:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
with:
python-version: "3.12"
cache: pip
cache-dependency-path: protocol/agent/v1/requirements.txt
- name: Install test dependencies
run: python -m pip install -r protocol/agent/v1/requirements.txt
- name: Run Agent v1 contract regression suite
run: scripts/run_agent_v1_regression.sh
+1 -1
View File
@@ -231,7 +231,7 @@ jobs:
# --all-targets links the same test binaries as the reader lane.
CARGO_BUILD_JOBS: "2"
run: |
cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2
cargo build -p rustfs -p rustfs-ecstore --all-targets --features rio-v2
cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
# Readers: the swift and sftp legs of test-and-lint-protocols. Built in
+12 -2
View File
@@ -563,7 +563,7 @@ jobs:
run: chmod go-w "$(realpath "$HOME")"
- name: Run rio-v2 clippy lints
run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2 -- -D warnings
run: cargo clippy -p rustfs -p rustfs-ecstore --all-targets --features rio-v2 -- -D warnings
- name: Run rio-v2 feature tests
shell: bash
@@ -580,7 +580,7 @@ jobs:
rm -f target/nextest/ci/junit.xml
./scripts/ci/resource_sampler.sh start nextest-rio-v2
trap './scripts/ci/resource_sampler.sh stop' EXIT
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore --features rio-v2 \
2>&1 | tee artifacts/workspace/nextest.log
cargo test -p rustfs --doc --features rio-v2
@@ -1370,6 +1370,15 @@ jobs:
# the intermediate 4-object plateau requires 4*lc_interval < 5*debug_day, i.e.
# debug_day > 8. A smaller value lets the Days=5 rule fire inside the Days=1
# poll window so the count collapses straight to 2 and the test fails (#4764).
#
# RUSTFS_DATA_USAGE_UPDATE_DIR_CYCLES=1 is also required. A compacted directory
# is only re-descended (and its objects re-evaluated for ILM) once every
# DATA_USAGE_UPDATE_DIR_CYCLES scanner cycles (default 16). At the accelerated
# RUSTFS_SCANNER_CYCLE=2 that is ~32s between evaluations, so a Days=1 object
# that becomes due at debug_day (10s) is not actually expired until the next
# ~32s boundary (~42s), landing just past the 4*lc_interval (40s) poll window
# and making the count stall at 6 (#4767). Forcing every-cycle re-descent
# evaluates ILM within ~2s of the due time, well inside the poll window.
s3-lifecycle-behavior-tests:
name: S3 Lifecycle Behavior Tests
# Also gated on e2e-tests, matching s3-implemented-tests: when the e2e smoke
@@ -1411,6 +1420,7 @@ jobs:
RUSTFS_ILM_PROCESS_TIME=1 \
RUSTFS_SCANNER_ENABLED=true \
RUSTFS_SCANNER_CYCLE=2 \
RUSTFS_DATA_USAGE_UPDATE_DIR_CYCLES=1 \
RUSTFS_SCANNER_START_DELAY_SECS=0 \
RUSTFS_API_STALE_UPLOADS_CLEANUP_INTERVAL=2s \
S3_PORT="${S3_PORT}" \
+6 -37
View File
@@ -1,7 +1,10 @@
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.
# The `nixl` and `cuobject` features are off in every other build, so the code
# behind them is compiled nowhere else. This job compiles the `nixl` half on
# Linux and runs rustfs-nixl's unit tests; nixl-sys builds through its stub
# fallback, so no NIXL SDK is needed.
# The cuObject half needs the NVIDIA cuObject SDK and is not compiled here.
# Not a required check and not part of the `Test and Lint` aggregate.
on:
@@ -9,7 +12,6 @@ on:
paths:
- "crates/nixl/**"
- "crates/cuobject/**"
- "crates/cuobject-sys/**"
- "rustfs/src/storage/rpc/nixl*"
- "rustfs/src/app/object/cuobject.rs"
- "rustfs/src/app/object/get.rs"
@@ -68,42 +70,9 @@ jobs:
- name: Run the rustfs-nixl unit tests
run: cargo test --locked -p rustfs-nixl --features sys
cuobject-check:
name: cuObject server SDK and unit tests
runs-on: ubuntu-24.04
timeout-minutes: 60
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
with:
persist-credentials: false
- uses: ./.github/actions/setup
with:
rust-version: stable
cache-shared-key: ci-feat-cuobject
cache-save-if: 'false'
install-build-packaging-tools: 'false'
- name: Check the cuObject crates without the NVIDIA SDK
run: cargo check --locked -p rustfs-cuobject -p rustfs-cuobject-sys
- name: Install the NVIDIA server SDK
working-directory: ${{ runner.temp }}
run: |
sudo apt-get update
sudo apt-get install --no-install-recommends -y libibverbs-dev librdmacm-dev
repo=https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64
for pkg in libcuobjserver libcuobjserver-dev; do
curl --fail --location --retry 3 "$repo/${pkg}_2.1.0.101-1_amd64.deb" -o "$pkg.deb"
done
sha256sum --check <<'DIGESTS'
39e6271118717e8e726233ae5ac29ee3b83e335e1fbe96b097bb458a4a52393a libcuobjserver.deb
73d4f187e58b784c7cf64633d7e76c2ac59dea5b475fd981cc6897c34cb9876f libcuobjserver-dev.deb
DIGESTS
sudo dpkg -i libcuobjserver.deb libcuobjserver-dev.deb
- name: Test the server bridge
run: cargo test --locked -p rustfs-cuobject --features server
alert-on-failure:
name: Alert on scheduled failure
needs: [nixl-check, cuobject-check]
needs: [nixl-check]
# Only scheduled runs open or update the tracking issue; pull-request and
# manual runs stay quiet.
if: always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure')
-12
View File
@@ -80,18 +80,6 @@ Do not commit one-shot plans, trackers, migration ledgers, benchmark snapshots,
Select checks from the final task-owned diff. Scoped `AGENTS.md` files may add a concrete path-specific check, but must not replace this tiering with a generic full-workspace gate.
### Issue Fixes and External Regression Coverage
After fixing a bug tracked by an issue and running the applicable local checks, ask the developer once per fixed issue whether to cover it in [rustfs/auto-testing](https://github.com/rustfs/auto-testing). Ask before opening or updating the fix PR, or before reporting completion if there is no PR. Reuse a choice already made for that fix. Investigation alone and documentation-only changes do not trigger this prompt.
When presenting the three choices, describe the failing scenario and the assertion that would catch it.
- **Add or extend a case.** Prefer extending an existing scenario when it can exercise the regression. Record the resulting case ID or auto-testing PR link.
- **Already covered.** Cite the existing auto-testing case ID or path and the assertion that would catch this bug.
- **Skip.** Record the developer's one-line reason and continue with the fix.
Record the choice in the PR's Verification section or in the completion report for work without a PR. All three choices retain the applicable RustFS verification requirements below.
### Documentation and Instructions
For prose, comments, agent instructions, and skill metadata that cannot affect runtime/build output:
+1 -1
View File
@@ -94,7 +94,7 @@ refactors.
|--------|--------------------------|----------------|
| Foundation | `checksums`, `common`, `config`, `data-usage`, `heal-contracts`, `scanner-metrics`, `utils` | Shared configuration, data-usage models, heal domain contracts, scanner telemetry types, utilities, and checksums. |
| I/O and storage | `concurrency`, `ecstore`, `filemeta`, `heal`, `io-core`, `io-metrics`, `lifecycle`, `lock`, `object-capacity`, `object-data-cache`, `replication`, `rio`, `rio-v2`, `s3-client`, `scanner`, `storage-api` | Erasure-coded object storage, metadata, recovery, lifecycle, replication, locking, cache, I/O pipelines, and the engine-side S3 client for remote tier/transition targets. |
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `sse`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, server-side encryption key resolution, TLS, and security contracts. |
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, TLS, and security contracts. |
| Protocols and contracts | `extension-schema`, `madmin`, `protos`, `protocols`, `s3-ops`, `s3-types`, `s3select-api`, `s3select-query` | Admin, inter-node, S3, S3 Select, and optional protocol contracts. |
| Operations and integration | `audit`, `notify`, `obs`, `targets`, `zip` | Auditing, observability, event delivery, notification targets, and archive support. |
| Test support | `e2e_test`, `test-utils` | End-to-end validation and shared test bootstrap utilities. |
-3
View File
@@ -46,8 +46,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **SSE-C multipart and copy responses no longer carry `x-amz-server-side-encryption`**: `CreateMultipartUpload`, `UploadPart`, `UploadPartCopy` and `CompleteMultipartUpload` on an SSE-C upload, and `CopyObject` to an SSE-C destination, answered with `x-amz-server-side-encryption: AES256` next to the customer-key headers, so a client reading the response saw an SSE-S3 object. They now return only `x-amz-server-side-encryption-customer-algorithm` and `x-amz-server-side-encryption-customer-key-MD5`, as `PutObject`, `GetObject` and `HeadObject` already did. SSE-S3 and SSE-KMS responses are unchanged.
- **Vault KMS backends no longer fail when the server answers reads from a replica**: a Vault or OpenBao node that serves reads locally (an OpenBao standby, a Vault Enterprise performance standby) can return the state from before a write for a short while after acknowledging it. Against such a node the KV2 backend failed every key creation with `404 Key not found` while leaving the key stored without its description and tags, failed operations issued right after a create or update with `Key not found` or `Concurrent modification`, and the Transit backend failed a disable followed quickly by an enable. Key creation on the KV2 backend is now a single create-only write that carries the description and tags. Both backends now re-read a key record when the answer is older than a write the same RustFS node made in the previous five seconds, pause before re-reading after a lost check-and-set write and allow five attempts instead of three, and retry a Transit key delete that is refused because the deletion switch is not visible yet. A different RustFS node reading the same replica can still observe the earlier state until the replica catches up; see [OpenBao as the Vault KMS backend](docs/operations/kms-openbao-compatibility.md).
- **KMS keys could not be described by ARN through the path route**: `GET /rustfs/admin/v3/kms/keys/{key_id}` read the path segment verbatim, so a key id that has to be percent-encoded to fit in one segment — an AWS key ARN, with its `:` and `/` — was looked up, authorized and audited under its encoded spelling and answered `404`. The segment is now percent-decoded first; a segment that is not valid UTF-8 after decoding is refused with `400 InvalidArgument`. The `describe-key?keyId=` form was unaffected.
@@ -118,7 +116,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Four-layer regression-prevention tests guard against silent feature deletion: compile-time module assertion, module-presence unit test, cross-module `Protocol` enum assertion, end-to-end SSH banner test against the running binary
### Changed
- **Startup reports the state of `RUSTFS_SSE_S3_MASTER_KEY`**: the server now checks the local SSE-S3 master key when it starts and logs one `sse_local_master_key` event with `state` `loaded`, `not_set`, or `invalid`. An unusable value used to surface only as a `400 InvalidRequest` on the first SSE-S3 request served without a KMS; it is now logged as an error at startup with the reason. Startup still succeeds and request behavior is unchanged. The line "Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3 (KMS not configured)", logged when the key was first used, is replaced by this event.
- **Scanner bucket walkers are no longer tied to the disk count**: a new scanner key `walkers_per_disk` (`RUSTFS_SCANNER_WALKERS_PER_DISK`, `1` through `16`, default `1`) spawns that many bucket walkers per local disk of an erasure set, so a single-disk deployment can walk several buckets at once instead of one bucket, one object at a time. The walkers of one disk share its scanner admission, so a peer still sees one scan session per physical disk, and remote disks keep one walker. The walker count is what `max_concurrent_disk_scans` caps and the disk count stays the floor; the `disk_concurrency_budget` log line now reports `walkers_per_disk`, `walkers`, and the `reason` for the effective limit. The default keeps today's I/O profile because a local disk cannot yet report whether it is rotational; the design intends a higher default on flash once it can (`docs/architecture/scanner-per-bucket-convergence.md`). As groundwork for pacing, the raw-enumeration page writer inserts into its building page in place and commits pages without copying them, and a regression test pins the cost of recording 20,000 entries in one prefix so the quadratic bookkeeping removed by [#8114](https://github.com/rustfs/rustfs/pull/8114) (rustfs#8113) cannot return. No persisted format, protocol or admin API changes beyond the additional config key, which older releases preserve and ignore.
- **Encryption and KMS work merged since `1.0.0-rc.5`** (entries were missing from this section):
- **Persisted KMS configuration secrets** are sealed field-by-field with `RUSTFS_KMS_CONFIG_SECRET`. **When the variable is unset the secrets are persisted in cleartext and the server only warns** (`persisted KMS configuration carries cleartext secrets`); it never refuses the write. Set it, identically, on every node, and re-save the configuration to seal an existing one.
Generated
+218 -326
View File
File diff suppressed because it is too large Load Diff
+26 -34
View File
@@ -23,7 +23,6 @@ members = [
"crates/connect-symbol-catalog", # Release-only CPU profile symbol catalog generator
"crates/credentials", # Credential management system
"crates/crypto", # Cryptography and security features
"crates/cuobject-sys", # Native NVIDIA cuObject server SDK bindings
"crates/cuobject", # NVIDIA cuObject S3-over-RDMA staging and transfers (optional)
"crates/nixl", # NIXL/UCX S3-over-RDMA server side (optional)
"crates/ecstore", # Erasure coding storage implementation
@@ -61,7 +60,6 @@ members = [
"crates/security-governance", # Security governance contracts
"crates/extension-schema", # Extension schema contracts
"crates/signer", # client signer
"crates/sse", # S3 server-side encryption key resolution and metadata
"crates/storage-api", # Storage API contracts
"crates/test-utils", # Shared test bootstrap helpers (dev-dependency only)
"crates/targets", # Target-specific configurations and utilities
@@ -110,7 +108,6 @@ rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.5" }
rustfs-credentials = { path = "crates/credentials", version = "1.0.5" }
rustfs-crypto = { path = "crates/crypto", version = "1.0.5" }
rustfs-cuobject = { path = "crates/cuobject", version = "1.0.5" }
rustfs-cuobject-sys = { path = "crates/cuobject-sys", version = "1.0.5" }
rustfs-nixl = { path = "crates/nixl", version = "1.0.5" }
rustfs-ecstore = { path = "crates/ecstore", version = "1.0.5" }
rustfs-filemeta = { path = "crates/filemeta", version = "1.0.5" }
@@ -143,7 +140,6 @@ rustfs-scanner = { path = "crates/scanner", version = "1.0.5" }
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.5" }
rustfs-extension-schema = { path = "crates/extension-schema", version = "1.0.5" }
rustfs-signer = { path = "crates/signer", version = "1.0.5" }
rustfs-sse = { path = "crates/sse", version = "1.0.5" }
rustfs-storage-api = { path = "crates/storage-api", version = "1.0.5" }
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.5" }
rustfs-targets = { path = "crates/targets", version = "1.0.5" }
@@ -156,16 +152,16 @@ rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
# engine crates move onto from s3s (rustfs/backlog#2745). The one pin of the
# gateway in this workspace; no crate may enable a `compat-s3s*` feature except
# the s3s-facing edge of the rustfs binary.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.2.0", default-features = false }
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.42.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.2.0", default-features = false }
# The gateway framework itself, consumed for its extension traits by the ring-2
# adapter. `default-features = false` keeps the `server` feature, and with it the
# server crate, out of the build.
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.66.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.66.0", default-features = false }
# Test-only: builds the `EffectiveHost` a host-resolution test queries with.
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "810c39fa41347ea27d1b1310201b3f941f0e3310", version = "0.13.0", default-features = false }
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.63.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.13.0", default-features = false }
# Async Runtime and Networking
async-channel = "2.5.0"
@@ -179,9 +175,9 @@ futures = "0.3.34"
futures-core = "0.3.34"
futures-lite = "2.6.1"
futures-util = "0.3.34"
pollster = "1.0.3"
pollster = "1.0.2"
pulsar = { default-features = false, version = "=6.9.0" }
lapin = { default-features = false, version = "4.13.0" }
lapin = { default-features = false, version = "4.12.3" }
hyper = { version = "1.12.0" }
h2 = { version = "0.4.20" }
hyper-rustls = { default-features = false, version = "0.27.10" }
@@ -220,7 +216,7 @@ csv-core = "0.1.13"
bytesize = "2.7.0"
byteorder = "1.5.0"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.3"
form_urlencoded = "1.2.2"
prost = "0.14.6"
quick-xml = "0.42.0"
rmp = { version = "0.8.15" }
@@ -262,7 +258,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.0.2" }
jiff = { version = "1.0.1" }
time = { version = "0.3.55" }
# Database
@@ -282,15 +278,15 @@ atomic_enum = "0.3.0"
aws-config = { version = "1.13.3" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.133.0" }
aws-sdk-s3 = { default-features = false, version = "1.161.0" }
aws-sdk-sts = { default-features = false, version = "1.128.0" }
aws-sdk-s3 = { default-features = false, version = "1.160.0" }
aws-sdk-sts = { default-features = false, version = "1.127.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
aws-smithy-runtime-api = { version = "1.22.0" }
aws-smithy-types = { version = "1.9.4" }
base64-simd = "0.8.0"
brotli = "9.1.3"
clap = { version = "4.6.9" }
clap = { version = "4.6.8" }
const-str = { version = "1.1.0" }
convert_case = "0.12.0"
criterion = { version = "0.8" }
@@ -302,12 +298,12 @@ datafusion = { default-features = false, version = "55.3.0" }
derive_builder = "0.20.2"
ed25519-dalek = "3.0.0"
enumset = "1.1.15"
faster-hex = "2.0.0"
faster-hex = "1.0.0"
flate2 = "1.1.11"
glob = "0.3.4"
google-cloud-storage = "1.22.0"
google-cloud-auth = "1.19.0"
hashbrown = { version = "0.17.2" }
hashbrown = { version = "0.17.1" }
# Base32 for RFC 6238 TOTP shared secrets (RFC 4648 unpadded, the alphabet
# every authenticator app expects). Already in the graph transitively.
data-encoding = "2.11.1"
@@ -317,8 +313,7 @@ hostname = "0.4.2"
ipnetwork = { version = "0.21.1" }
lazy_static = "1.5.1"
libc = "0.2.191"
cxx = "1"
cxx-build = "1"
cuobject = { version = "0.1.0", default-features = false }
libsystemd = "0.7.2"
local-ip-address = "0.6.13"
log = "0.4"
@@ -342,7 +337,7 @@ percent-encoding = "2.3.2"
# CLI needs its own QR encoder. No default features: the image/render backends
# pull in an image stack this only needs SVG and text output from.
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
pin-project-lite = "0.2.18"
pin-project-lite = "0.2.17"
pretty_assertions = "1.4.1"
rand = { version = "0.10.4" }
ratelimit = "2.0.0"
@@ -365,7 +360,7 @@ legacy-s3s = { package = "s3s", git = "https://github.com/s3s-project/s3s", rev
serial_test = "4.0.1"
shadow-rs = { default-features = false, version = "2.0.0" }
siphasher = "1.0.4"
smallvec = { version = "1.16.6" }
smallvec = { version = "1.16.5" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.1" }
@@ -383,23 +378,23 @@ tracing-error = "0.2.1"
tracing-opentelemetry = { version = "0.34.0" }
tracing-subscriber = { version = "0.3.23" }
transform-stream = "0.3.1"
url = "2.5.9"
url = "2.5.8"
urlencoding = "2.1.3"
uuid = { version = "1.29.3" }
vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.1"
walkdir = "2.5.0"
winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
xxhash-rust = { version = "0.8.21" }
zip = "9.8.1"
zip = "9.7.0"
zstd = "0.14.4"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
dial9 = { version = "0.5.9", default-features = false }
dial9 = { version = "0.5.8", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
opentelemetry-otlp = { version = "0.33.1" }
@@ -410,12 +405,12 @@ opentelemetry-stdout = { version = "0.33.1" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
libunftp = { version = "0.25.1" }
libunftp = { version = "0.25.0" }
unftp-core = "0.1.1"
suppaftp = { version = "13.0.0" }
rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] }
russh = { version = "0.65.4" }
russh-sftp = "4.0.0"
russh = { version = "0.65.2" }
russh-sftp = "3.0.1"
# WebDAV
dav-server = "0.12.0"
@@ -428,10 +423,7 @@ hotpath = { version = "0.32.1", default-features = false }
insta = { version = "1.49" }
[workspace.metadata.cargo-shear]
# The `#[path]` test modules under `rustfs/src/server/http/tests/` are linked by
# rustc (including the `http.rs` + `http/` sibling-directory rule), but cargo-shear
# resolves those nested `#[path]` attributes against the wrong base directory.
ignored-paths = ["rustfs/src/server/http/tests/**/*.rs"]
ignored = ["hotpath", "rustfs"]
[profile.dev]
# Full debuginfo roughly doubles compile+link time and produces multi-GB
+4 -3
View File
@@ -15,11 +15,12 @@ workspace = true
[features]
default = []
hotpath = ["rustfs-io-core/hotpath"]
hotpath-alloc = ["hotpath", "rustfs-io-core/hotpath-alloc"]
hotpath-cpu = ["hotpath", "rustfs-io-core/hotpath-cpu"]
hotpath = ["hotpath/hotpath", "hotpath/tokio", "rustfs-io-core/hotpath"]
hotpath-alloc = ["hotpath", "hotpath/hotpath-alloc", "rustfs-io-core/hotpath-alloc"]
hotpath-cpu = ["hotpath", "hotpath/hotpath-cpu", "rustfs-io-core/hotpath-cpu"]
[dependencies]
hotpath.workspace = true
# Internal crates
rustfs-io-core = { workspace = true }
serde = { workspace = true, features = ["derive"] }
-6
View File
@@ -129,12 +129,6 @@ when restoring `/rustfs/console` for a custom OEM build.
- `RUSTFS_SCANNER_MAX_CONCURRENT_SET_SCANS` (canonical)
- `RUSTFS_SCANNER_MAX_CONCURRENT_DISK_SCANS` (canonical)
- `RUSTFS_SCANNER_WALKERS_PER_DISK` (canonical)
- `RUSTFS_SCANNER_READ_ONLY_HANDOFF` (canonical, default `false`)
Read-only restart continuity:
- `RUSTFS_SCANNER_READ_ONLY_HANDOFF=true` enables reuse of unpublished scanner progress across verified read-only process restarts. Unset, false or invalid values disable both identity restoration and receipt creation. Existing receipts are still durably consumed before recovery starts, even when the feature is disabled.
- Deploy receipt-aware readers to every possible writer before enabling this flag. Before rolling back to an older binary, disable it on every node, start each node with all its drives present, wait for readiness, and shut down cleanly. Do not start the older binary until every node completes this preparation. Direct rollback after enabling receipt writes is unsupported: older startup/recovery paths can write without durably invalidating the receipt. See [the receipt and rollback contract](../../docs/architecture/scanner-usage-publication.md#read-only-restart-continuity).
Scanner cycle budget controls:
-5
View File
@@ -21,11 +21,6 @@ pub const APP_NAME: &str = "RustFS";
/// Cargo package version for this workspace member.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
/// Defaults to false. Enable only after all possible writers support receipt
/// consumption; disable and restart before rolling back to an older writer.
pub const ENV_SCANNER_READ_ONLY_HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
/// Default configuration logger level
/// Default value: error
/// Environment variable: RUSTFS_OBS_LOGGER_LEVEL
-3
View File
@@ -32,9 +32,6 @@ pub const DEFAULT_HEAL_BITROT_CYCLE_SECS: u64 = 30 * 24 * 60 * 60;
/// - Note: Enabling auto-heal can improve system resilience by automatically addressing issues, but may increase resource usage; evaluate based on your operational requirements.
pub const ENV_HEAL_AUTO_HEAL_ENABLE: &str = "RUSTFS_HEAL_AUTO_HEAL_ENABLE";
/// Colon-separated Linux mount roots for automatic replacement of data directories below a mount point.
pub const ENV_HEAL_REPLACEMENT_MOUNT_ROOTS: &str = "RUSTFS_HEAL_REPLACEMENT_MOUNT_ROOTS";
/// Environment variable name that specifies the heal queue size.
///
/// - Purpose: Set the maximum number of heal requests that can be queued.
+4 -2
View File
@@ -349,8 +349,10 @@ pub const DEFAULT_INTERNODE_DATA_TRANSPORT: &str = "tcp-http";
/// Legacy alias for "tcp-http". Both values select the TCP/HTTP transport backend.
pub const INTERNODE_DATA_TRANSPORT_TCP: &str = "tcp";
/// Shard reads and writes use NIXL/UCX and require an active NIXL agent on both peers.
/// Format metadata, directory walks and scanner requests use the control transport.
/// Internode reads whose data moves over NIXL/UCX (InfiniBand rails or RoCE by
/// LID/GID, no IP needed); requests, writes and walks stay on TCP/HTTP. Requires
/// a binary built with the `nixl` feature and `RUSTFS_NIXL_ENABLE`; until the
/// NIXL agent is up, and for any read it cannot serve, it uses TCP/HTTP.
pub const INTERNODE_DATA_TRANSPORT_NIXL: &str = "nixl";
/// Known internode transport backend names accepted by the config parser.
-22
View File
@@ -1,22 +0,0 @@
[package]
name = "rustfs-cuobject-sys"
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
version.workspace = true
description = "Native bindings to the NVIDIA cuObject server SDK"
links = "cuobjserver"
[lints]
workspace = true
[dependencies]
cxx = { workspace = true, optional = true }
libc = { workspace = true, optional = true }
[build-dependencies]
cxx-build = { workspace = true, optional = true }
[features]
server = ["dep:cxx", "dep:cxx-build", "dep:libc"]
-41
View File
@@ -1,41 +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.
fn main() {
#[cfg(feature = "server")]
build_server();
}
#[cfg(feature = "server")]
fn build_server() {
use std::{env, path::PathBuf};
println!("cargo:rerun-if-env-changed=CUOBJSERVER_ROOT");
for file in ["src/sdk.rs", "native/server.h", "native/server.cc"] {
println!("cargo:rerun-if-changed={file}");
}
let mut build = cxx_build::bridge("src/sdk.rs");
if let Some(root) = env::var_os("CUOBJSERVER_ROOT").map(PathBuf::from) {
build.include(root.join("include"));
for subdir in ["lib", "lib64"] {
println!("cargo:rustc-link-search=native={}", root.join(subdir).display());
}
}
build
.include(".")
.file("native/server.cc")
.std("c++17")
.compile("rustfs_cuobject_server");
println!("cargo:rustc-link-lib=cuobjserver");
}
-143
View File
@@ -1,143 +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.
#include "rustfs-cuobject-sys/src/sdk.rs.h"
#include <cuobjserver.h>
#include <array>
#include <cerrno>
#include <limits>
#include <stdexcept>
#include <system_error>
#include <sys/mman.h>
namespace rustfs::cuobject {
class Server {
public:
Server(std::string address, std::uint16_t port, int channels, std::uint32_t depth)
: address_(std::move(address)) {
cuObjRDMATunable options;
if (channels > 0) options.setNumDcis(channels);
if (depth > 0) options.setCqDepth(depth);
sdk = std::make_unique<cuObjServer>(address_.c_str(), port, CUOBJ_PROTO_RDMA_DC_V1, options);
}
// The SDK may retain the address string through server teardown.
const std::string address_;
std::unique_ptr<cuObjServer> sdk;
};
std::uint32_t header_version() noexcept {
return CUOBJ_SERVER_MAJOR_VERSION * 1000 + CUOBJ_SERVER_MINOR_VERSION;
}
std::shared_ptr<Server> open_server(rust::Str addr, std::uint16_t port, int channels, std::uint32_t depth) {
return std::make_shared<Server>(std::string(addr), port, channels, depth);
}
class Buffer {
public:
std::shared_ptr<Server> owner;
std::shared_ptr<Buffer> base;
rdma_buffer* handle = nullptr;
void* mapping = MAP_FAILED;
std::size_t length = 0;
static void destroy(Buffer* buffer) noexcept {
try {
if (buffer->handle) {
if (buffer->base) buffer->owner->sdk->putRDMABufferFromSgList(buffer->handle);
else buffer->owner->sdk->deRegisterBuffer(buffer->handle);
}
} catch (...) {
// The SDK may still reference the mapping and its owning server.
return;
}
if (buffer->mapping != MAP_FAILED) munmap(buffer->mapping, buffer->length);
delete buffer;
}
};
std::shared_ptr<Buffer> register_buffer(std::shared_ptr<Server> server, std::size_t length) {
if (!server || !length) throw std::invalid_argument("invalid host registration");
auto buffer = std::shared_ptr<Buffer>(new Buffer, Buffer::destroy);
buffer->owner = std::move(server);
buffer->length = length;
buffer->mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (buffer->mapping == MAP_FAILED) throw std::system_error(errno, std::generic_category(), "mmap");
buffer->handle = buffer->owner->sdk->registerBuffer(buffer->mapping, length);
if (!buffer->handle) throw std::runtime_error("NVIDIA memory registration failed");
return buffer;
}
std::shared_ptr<Buffer> scatter_list(std::shared_ptr<Buffer> base, rust::Slice<const Range> ranges) {
if (!base || base->base || ranges.empty() || ranges.size() > 10) throw std::invalid_argument("invalid scatter list");
auto list = std::shared_ptr<Buffer>(new Buffer, Buffer::destroy);
list->owner = base->owner;
list->base = std::move(base);
std::vector<cuObjScatterGatherEntryWithOffset_t> entries;
entries.reserve(ranges.size());
for (auto range : ranges) {
if (!range.size || range.offset > list->base->length || range.size > list->base->length - range.offset ||
range.offset > std::numeric_limits<loff_t>::max() || range.size > SIZE_MAX - list->length)
throw std::invalid_argument("invalid scatter range");
entries.push_back({static_cast<loff_t>(range.offset), range.size});
list->length += range.size;
}
list->handle = list->owner->sdk->getRDMABufferFromSgList(list->base->handle, std::move(entries));
if (!list->handle) throw std::runtime_error("NVIDIA scatter list registration failed");
return list;
}
std::uint8_t* data(const Buffer& buffer) noexcept { return static_cast<std::uint8_t*>(buffer.mapping); }
std::size_t size(const Buffer& buffer) noexcept { return buffer.length; }
std::uint16_t lease_channel(const Server& server) { return server.sdk->allocateChannelId(); }
void release_channel(const Server& server, std::uint16_t channel) noexcept {
try { server.sdk->freeChannelId(channel); } catch (...) { /* SDK owns the channel. */ }
}
int completion_fd(const Server& server, std::uint16_t channel) noexcept {
try { return server.sdk->getCompletionFd(channel); } catch (...) { return -EIO; }
}
int drain(const Server& server, int fd, rust::Slice<Completion> out) noexcept {
std::array<cuObjAsyncEvent_t, 8> events{};
if (out.empty() || out.size() > events.size()) return -EINVAL;
try {
const int count = server.sdk->processCompletions(events.data(), static_cast<int>(out.size()), fd);
if (count > static_cast<int>(out.size())) return -EIO;
for (int i = 0; i < count; ++i) {
out[i] = {reinterpret_cast<std::uintptr_t>(events[i].async_handle), events[i].status};
}
return count;
} catch (...) { return -EIO; }
}
Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept {
if (buffer.owner.get() != &server || !op.length || op.offset > buffer.length ||
op.length > buffer.length - op.offset || (buffer.base && (op.offset || op.length != buffer.length)))
return {-EINVAL, 0, false};
ibv_wc_status verbs = IBV_WC_SUCCESS;
bool submitted_to_sdk = false;
try {
const std::string key(op.key), token(op.token);
void* handle = reinterpret_cast<void*>(op.handle);
auto& sdk = *server.sdk;
submitted_to_sdk = true;
const ssize_t moved = op.put
? sdk.handlePutObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle)
: sdk.handleGetObject(key, buffer.handle, op.address, op.length, token, op.channel, op.offset, &verbs, handle);
return {moved, static_cast<int>(verbs), false};
} catch (...) { return {-EIO, static_cast<int>(verbs), submitted_to_sdk}; }
}
}
-40
View File
@@ -1,40 +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.
#pragma once
#include "rust/cxx.h"
#include <cstddef>
#include <cstdint>
#include <memory>
namespace rustfs::cuobject {
class Server;
class Buffer;
struct Range;
struct Completion;
struct Operation;
struct Outcome;
std::uint32_t header_version() noexcept;
std::shared_ptr<Server> open_server(rust::Str address, std::uint16_t port, int channels, std::uint32_t depth);
std::shared_ptr<Buffer> register_buffer(std::shared_ptr<Server> server, std::size_t length);
std::shared_ptr<Buffer> scatter_list(std::shared_ptr<Buffer> base, rust::Slice<const Range> ranges);
std::uint8_t* data(const Buffer& buffer) noexcept;
std::size_t size(const Buffer& buffer) noexcept;
std::uint16_t lease_channel(const Server& server);
void release_channel(const Server& server, std::uint16_t channel) noexcept;
int completion_fd(const Server& server, std::uint16_t channel) noexcept;
int drain(const Server& server, int fd, rust::Slice<Completion> events) noexcept;
Outcome transfer(const Server& server, const Buffer& buffer, const Operation& op) noexcept;
}
-22
View File
@@ -1,22 +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.
//! Native bindings and SDK handle ownership for the NVIDIA cuObject server.
#![cfg(feature = "server")]
pub use cxx::Exception;
// SAFETY: this module declares the SDK ABI and the ownership of native handles.
#[allow(unsafe_code)]
mod sdk;
pub use sdk::*;
-149
View File
@@ -1,149 +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.
//! Private ABI for the NVIDIA server SDK.
use cxx::SharedPtr;
use std::io;
use std::os::fd::{AsRawFd, RawFd};
#[cxx::bridge(namespace = "rustfs::cuobject")]
mod ffi {
#[derive(Clone, Copy, Debug)]
struct Range {
offset: usize,
size: usize,
}
#[derive(Clone, Copy, Default)]
struct Completion {
handle: usize,
status: isize,
}
struct Operation<'a> {
key: &'a str,
token: &'a str,
address: u64,
offset: usize,
length: usize,
channel: u16,
handle: usize,
put: bool,
}
struct Outcome {
count: isize,
verbs: i32,
uncertain: bool,
}
// SAFETY: native registrations own their server and mapping. Scatter views
// also own their base. The caller keeps DMA ranges exclusive until completion.
unsafe extern "C++" {
include!("native/server.h");
type Server;
type Buffer;
fn header_version() -> u32;
fn open_server(address: &str, port: u16, channels: i32, depth: u32) -> Result<SharedPtr<Server>>;
fn register_buffer(server: SharedPtr<Server>, length: usize) -> Result<SharedPtr<Buffer>>;
fn scatter_list(base: SharedPtr<Buffer>, ranges: &[Range]) -> Result<SharedPtr<Buffer>>;
fn size(buffer: &Buffer) -> usize;
fn data(buffer: &Buffer) -> *mut u8;
fn lease_channel(server: &Server) -> Result<u16>;
fn release_channel(server: &Server, channel: u16);
fn completion_fd(server: &Server, channel: u16) -> i32;
fn drain(server: &Server, fd: i32, events: &mut [Completion]) -> i32;
unsafe fn transfer(server: &Server, buffer: &Buffer, op: &Operation) -> Outcome;
}
}
// SAFETY: the SDK supports concurrent transfers on separately leased channels.
// Server and registration metadata stay immutable after construction. Sharing a
// handle gives no safe access to the host bytes.
unsafe impl Send for ffi::Server {}
unsafe impl Sync for ffi::Server {}
unsafe impl Send for ffi::Buffer {}
unsafe impl Sync for ffi::Buffer {}
pub use ffi::{Completion, Operation, Outcome, Range, data, header_version, open_server, register_buffer, scatter_list, size};
pub type ServerHandle = SharedPtr<ffi::Server>;
pub type BufferHandle = SharedPtr<ffi::Buffer>;
pub fn errno(status: isize) -> io::Error {
match status.checked_neg().and_then(|code| i32::try_from(code).ok()) {
Some(code) => io::Error::from_raw_os_error(code),
None => io::Error::other("invalid NVIDIA error status"),
}
}
pub struct Channel {
server: SharedPtr<ffi::Server>,
id: u16,
}
impl Channel {
pub fn lease(server: &SharedPtr<ffi::Server>) -> io::Result<Self> {
let id = ffi::lease_channel(server).map_err(io::Error::other)?;
if id == u16::MAX {
return Err(io::Error::from_raw_os_error(libc::EBUSY));
}
Ok(Self {
server: server.clone(),
id,
})
}
pub fn fd(&self) -> Option<CompletionFd> {
let fd = ffi::completion_fd(&self.server, self.id);
(fd >= 0).then(|| CompletionFd {
fd,
server: self.server.clone(),
})
}
/// Submits a transfer to the leased channel.
///
/// # Safety
/// The caller must exclusively own the local range, keep the remote token valid,
/// and retain the channel and registrations until the SDK confirms completion.
/// An unknown submission or undelivered completion must preserve those owners.
pub unsafe fn submit(&mut self, buffer: &ffi::Buffer, mut op: ffi::Operation<'_>) -> ffi::Outcome {
op.channel = self.id;
// SAFETY: the caller holds the range and the exclusive channel lease.
unsafe { ffi::transfer(&self.server, buffer, &op) }
}
}
impl Drop for Channel {
fn drop(&mut self) {
ffi::release_channel(&self.server, self.id);
}
}
pub struct CompletionFd {
fd: RawFd,
server: SharedPtr<ffi::Server>,
}
impl AsRawFd for CompletionFd {
fn as_raw_fd(&self) -> RawFd {
self.fd
}
}
impl CompletionFd {
pub fn drain(&self, events: &mut [ffi::Completion]) -> io::Result<usize> {
let count = ffi::drain(&self.server, self.fd, events);
usize::try_from(count).map_err(|_| errno(count as isize))
}
}
+2 -2
View File
@@ -16,11 +16,11 @@ workspace = true
[dependencies]
bytes = { workspace = true, optional = true }
rustfs-cuobject-sys = { workspace = true, features = ["server"], optional = true }
cuobject = { workspace = true, default-features = false, optional = true }
parking_lot = { workspace = true, optional = true }
thiserror = { workspace = true, optional = true }
tokio = { workspace = true, features = ["net", "rt-multi-thread", "sync", "time"], optional = true }
[features]
# Compiles the cuObject server bindings (needs the NVIDIA cuObject SDK).
server = ["dep:bytes", "dep:rustfs-cuobject-sys", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
server = ["dep:bytes", "dep:cuobject", "cuobject/server", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
+224 -650
View File
File diff suppressed because it is too large Load Diff
+3 -72
View File
@@ -1235,66 +1235,23 @@ impl Serialize for DataUsageEntry {
where
S: serde::Serializer,
{
self.serialize_fields(serializer, &self.children, &self.replication_stats, &self.all_tier_stats)
}
}
struct OrderedUsageEntry<'a>(&'a DataUsageEntry);
impl Serialize for OrderedUsageEntry<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut children: Vec<_> = self.0.children.iter().collect();
children.sort_unstable();
// MessagePack decoders accept struct fields as positional sequences.
// Include the nested target and tier maps in stable order as well.
let replication = self.0.replication_stats.as_ref().map(|stats| {
let ReplicationAllStats {
targets,
replica_size,
replica_count,
} = stats;
let targets: std::collections::BTreeMap<_, _> = targets.iter().collect();
(targets, replica_size, replica_count)
});
let tiers = self.0.all_tier_stats.as_ref().map(|stats| {
let AllTierStats { tiers } = stats;
let tiers: std::collections::BTreeMap<_, _> = tiers.iter().collect();
(tiers,)
});
self.0.serialize_fields(serializer, &children, &replication, &tiers)
}
}
impl DataUsageEntry {
/// Stable MessagePack encoding for independently reusable scanner checkpoint pages.
pub fn ordered_encoding(&self) -> impl Serialize + '_ {
OrderedUsageEntry(self)
}
fn serialize_fields<S: serde::Serializer, C: Serialize, R: Serialize, T: Serialize>(
&self,
serializer: S,
children: &C,
replication: &R,
tiers: &T,
) -> Result<S::Ok, S::Error> {
// Keep entries map-encoded so older readers can ignore fields appended
// by newer scanner versions during rolling upgrades. The derived
// (array) encoding made any appended field a decode error for them.
let mut state = serializer.serialize_map(Some(
11 + usize::from(self.unknown_tier_stats.is_some()) + usize::from(self.tier_accounting_proof.is_some()),
))?;
state.serialize_entry("children", children)?;
state.serialize_entry("children", &self.children)?;
state.serialize_entry("size", &self.size)?;
state.serialize_entry("objects", &self.objects)?;
state.serialize_entry("versions", &self.versions)?;
state.serialize_entry("delete_markers", &self.delete_markers)?;
state.serialize_entry("obj_sizes", &self.obj_sizes)?;
state.serialize_entry("obj_versions", &self.obj_versions)?;
state.serialize_entry("replication_stats", replication)?;
state.serialize_entry("replication_stats", &self.replication_stats)?;
state.serialize_entry("compacted", &self.compacted)?;
state.serialize_entry("failed_objects", &self.failed_objects)?;
state.serialize_entry("all_tier_stats", tiers)?;
state.serialize_entry("all_tier_stats", &self.all_tier_stats)?;
// Keep the legacy no-unknown shape byte-for-byte stable. Once unknown
// accounting exists, append its map field before the optional proof.
if let Some(unknown_tier_stats) = self.unknown_tier_stats.as_ref() {
@@ -2577,32 +2534,6 @@ mod tests {
entry
}
#[test]
fn ordered_checkpoint_entry_round_trips_and_stays_identical_after_reload() {
let mut entry = DataUsageEntry::default();
let mut replication = ReplicationAllStats {
replica_size: 998,
replica_count: 3,
..Default::default()
};
let mut tiers = AllTierStats::default();
for index in 1..=32 {
let key = format!("source-{index}");
entry.children.insert(key.clone());
replication.targets.insert(key.clone(), ReplicationTargetUsage::default());
tiers.tiers.insert(key, TierStats::default());
}
entry.replication_stats = Some(replication);
entry.all_tier_stats = Some(tiers);
let bytes = rmp_serde::to_vec(&entry.ordered_encoding()).expect("encode ordered checkpoint");
let reloaded: DataUsageEntry = rmp_serde::from_slice(&bytes).expect("read with the existing codec");
assert_eq!(reloaded.children, entry.children);
let replicas = reloaded.replication_stats.as_ref().expect("replication stats");
assert_eq!((replicas.targets.len(), replicas.replica_size, replicas.replica_count), (32, 998, 3));
assert_eq!(reloaded.all_tier_stats.as_ref().expect("tier stats").tiers.len(), 32);
assert_eq!(rmp_serde::to_vec(&reloaded.ordered_encoding()).expect("encode reloaded entry"), bytes);
}
#[test]
fn tier_stats_survive_entry_merge() {
let mut left = tier_entry(
@@ -171,70 +171,6 @@ impl DataUsageBucketObservation {
}
impl DataUsageInfo {
/// Hide values that cannot be bound to the current storage-owned identity.
///
/// `incarnations` contains canonical non-nil identities read from storage;
/// a missing entry means identity was unavailable. Neither legacy values
/// without identity nor metadata read failures establish confirmed zero.
/// Changed responses are display-only and cannot authorize quota or writes.
/// If retained counters overflow, all values remain unknown.
/// Returns the number of canonical values removed.
pub fn retain_current_bucket_usage_for_admin(&mut self, incarnations: &HashMap<String, String>) -> usize {
let original_count = self.buckets_usage.len();
let original_observation_count = self.usage_snapshot_bucket_observations.len();
let matches_current = |bucket: &String, usage: &BucketUsageInfo| {
incarnations.get(bucket).is_some_and(|current| {
!current.is_empty()
&& current != "00000000-0000-0000-0000-000000000000"
&& usage.bucket_incarnation.as_ref() == Some(current)
})
};
self.buckets_usage.retain(|bucket, usage| matches_current(bucket, usage));
self.usage_snapshot_bucket_observations.retain(|bucket, observation| {
matches_current(bucket, &observation.usage)
&& observation
.sources
.iter()
.all(|source| incarnations.get(bucket) == Some(&source.bucket_incarnation))
});
if original_count == self.buckets_usage.len()
&& original_observation_count == self.usage_snapshot_bucket_observations.len()
{
return 0;
}
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
Some([
total[0].checked_add(usage.size)?,
total[1].checked_add(usage.objects_count)?,
total[2].checked_add(usage.versions_count)?,
total[3].checked_add(usage.delete_markers_count)?,
])
});
let [size, objects, versions, markers] = totals.unwrap_or_else(|| {
self.buckets_usage.clear();
self.usage_snapshot_bucket_observations.clear();
[0; 4]
});
self.bucket_sizes = self
.buckets_usage
.iter()
.map(|(bucket, usage)| (bucket.clone(), usage.size))
.collect();
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
self.objects_total_size = size;
self.objects_total_count = objects;
self.versions_total_count = versions;
self.delete_markers_total_count = markers;
self.replication_info.clear();
self.tier_stats = None;
self.unknown_tier_stats = None;
self.usage_snapshot_complete = false;
self.usage_snapshot_partial = true;
self.usage_snapshot_converged = Some(false);
self.usage_snapshot_admin_projection = true;
original_count.saturating_sub(self.buckets_usage.len())
}
/// Overlay validated companions on an owned admin response only.
///
/// `incarnations` must come from current storage metadata, not the companion.
@@ -321,110 +321,3 @@ fn provenance_and_companions_change_candidate_bytes_and_round_trip_as_maps() {
let restored: DataUsageInfo = rmp_serde::from_slice(&named).expect("read named map with additive fields");
assert_eq!(restored, canonical);
}
#[test]
fn current_identity_filter_preserves_an_unchanged_complete_snapshot() {
let mut candidate = snapshot();
let original = candidate.clone();
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&incarnations()), 0);
assert_eq!(candidate, original);
assert!(candidate.is_complete_bucket_usage_snapshot());
}
#[test]
fn current_identity_filter_hides_unbound_values_without_confirming_zero() {
for identity in [
None,
Some(""),
Some("corrupt"),
Some("00000000-0000-0000-0000-000000000000"),
Some("22222222-2222-4222-8222-222222222222"),
] {
let mut candidate = snapshot();
candidate.usage_snapshot_bucket_observations.clear();
candidate
.buckets_usage
.get_mut("bucket")
.expect("canonical")
.bucket_incarnation = identity.map(str::to_string);
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&incarnations()),
1,
"identity {identity:?}"
);
assert!(!candidate.buckets_usage.contains_key("bucket"));
assert!(!candidate.bucket_sizes.contains_key("bucket"));
assert_eq!(candidate.usage_snapshot_converged, Some(false));
assert!(candidate.usage_snapshot_admin_projection);
assert!(!candidate.is_complete_bucket_usage_snapshot());
assert!(!candidate.is_valid_partial_snapshot());
}
for current in ["", "00000000-0000-0000-0000-000000000000"] {
let mut candidate = snapshot();
candidate
.buckets_usage
.get_mut("bucket")
.expect("canonical")
.bucket_incarnation = Some(current.to_string());
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&HashMap::from([("bucket".to_string(), current.to_string())])),
1
);
assert!(candidate.usage_snapshot_admin_projection);
}
let mut candidate = snapshot();
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&HashMap::new()), 1);
assert!(candidate.usage_snapshot_bucket_observations.is_empty());
assert_eq!(candidate.usage_snapshot_converged, Some(false));
}
#[test]
fn current_identity_filter_keeps_healthy_buckets_and_recalculates_partial_totals() {
let mut candidate = snapshot();
candidate.buckets_usage.insert("cold".to_string(), usage(7));
candidate.buckets_count = 2;
candidate.bucket_sizes.insert("cold".to_string(), 7);
candidate.calculate_totals();
candidate.replication_info.insert("target".to_string(), Default::default());
candidate.tier_stats = Some(Default::default());
candidate.unknown_tier_stats = Some(Default::default());
assert_eq!(
candidate.retain_current_bucket_usage_for_admin(&HashMap::from([("cold".to_string(), INCARNATION.to_string())])),
1
);
assert_eq!(candidate.buckets_usage.len(), 1);
assert_eq!(candidate.buckets_usage["cold"].size, 7);
assert_eq!(candidate.bucket_sizes, HashMap::from([("cold".to_string(), 7)]));
assert_eq!(
(
candidate.buckets_count,
candidate.objects_total_size,
candidate.objects_total_count,
candidate.versions_total_count
),
(1, 7, 7, 7)
);
assert!(candidate.replication_info.is_empty());
assert!(candidate.tier_stats.is_none());
assert!(candidate.unknown_tier_stats.is_none());
assert!(candidate.usage_snapshot_admin_projection);
assert_eq!(candidate.usage_snapshot_converged, Some(false));
}
#[test]
fn current_identity_filter_overflow_leaves_totals_unknown() {
let mut candidate = snapshot();
candidate.buckets_usage.insert("large".to_string(), usage(u64::MAX));
candidate.buckets_usage.insert("small".to_string(), usage(1));
candidate.buckets_count = 3;
let current = HashMap::from([
("large".to_string(), INCARNATION.to_string()),
("small".to_string(), INCARNATION.to_string()),
]);
assert_eq!(candidate.retain_current_bucket_usage_for_admin(&current), 3);
assert!(candidate.buckets_usage.is_empty());
assert!(candidate.bucket_sizes.is_empty());
assert_eq!(candidate.usage_snapshot_converged, Some(false));
assert!(candidate.usage_snapshot_admin_projection);
assert!(!candidate.is_complete_bucket_usage_snapshot());
}
-2
View File
@@ -140,8 +140,6 @@ clap = { workspace = true, features = ["derive", "env"] }
[dev-dependencies]
serde-value.workspace = true
s3s = { workspace = true, features = ["minio"] }
s3s-sigv4.workspace = true
url.workspace = true
async-compression = { workspace = true, features = ["tokio", "bzip2", "lz4", "xz"] }
aws-config = { workspace = true }
aws-sdk-sts = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
@@ -1,585 +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.
// Exercise the production validator at the protocol boundary without importing the server crate.
#[path = "../../../rustfs/src/storage/authorization/admission/request_validation.rs"]
mod request_validation;
use async_trait::async_trait;
use http::{Extensions, HeaderMap, Method, Request, StatusCode, Uri};
use http_body_util::BodyExt;
use request_validation::{RequestViolation, validate_method_subresource};
use s3s::access::{S3Access, S3AccessContext};
use s3s::auth::SimpleAuth;
use s3s::dto::{
AbortMultipartUploadInput, AbortMultipartUploadOutput, DeleteBucketInput, DeleteBucketOutput, DeleteBucketPolicyInput,
DeleteBucketPolicyOutput, DeleteObjectInput, DeleteObjectOutput, DeleteObjectTaggingInput, DeleteObjectTaggingOutput,
GetBucketAclInput, GetBucketAclOutput, GetObjectAclInput, GetObjectAclOutput, GetObjectInput, GetObjectOutput,
HeadBucketInput, HeadBucketOutput, PutBucketAclInput, PutBucketAclOutput, PutObjectAclInput, PutObjectAclOutput,
StreamingBlob,
};
use s3s::host::SingleDomain;
use s3s::route::S3Route;
use s3s::service::{S3Service, S3ServiceBuilder};
use s3s::{Body, S3Request, S3Response, S3Result, s3_error};
use s3s_sigv4::{
AmzDate, EMPTY_STRING_SHA256_HASH, Payload, calculate_signature, create_canonical_request,
create_presigned_canonical_request, create_string_to_sign,
};
use std::sync::{Arc, Mutex};
use time::{OffsetDateTime, macros::format_description};
#[derive(Default)]
struct State {
object_deleted: bool,
bucket_deleted: bool,
calls: Vec<(&'static str, Option<String>)>,
}
#[derive(Clone, Default)]
struct ProbeS3(Arc<Mutex<State>>);
#[async_trait]
impl s3s::S3 for ProbeS3 {
async fn delete_object(&self, req: S3Request<DeleteObjectInput>) -> S3Result<S3Response<DeleteObjectOutput>> {
let mut state = self.0.lock().expect("probe state");
state.object_deleted = true;
state.calls.push(("DeleteObject", req.input.version_id));
Ok(S3Response::new(DeleteObjectOutput::default()))
}
async fn delete_bucket(&self, _: S3Request<DeleteBucketInput>) -> S3Result<S3Response<DeleteBucketOutput>> {
let mut state = self.0.lock().expect("probe state");
state.bucket_deleted = true;
state.calls.push(("DeleteBucket", None));
Ok(S3Response::new(DeleteBucketOutput::default()))
}
async fn get_object(&self, _: S3Request<GetObjectInput>) -> S3Result<S3Response<GetObjectOutput>> {
if self.0.lock().expect("probe state").object_deleted {
return Err(s3_error!(NoSuchKey));
}
Ok(S3Response::new(GetObjectOutput {
body: Some(StreamingBlob::from(Body::from("original object".to_owned()))),
..Default::default()
}))
}
async fn head_bucket(&self, _: S3Request<HeadBucketInput>) -> S3Result<S3Response<HeadBucketOutput>> {
if self.0.lock().expect("probe state").bucket_deleted {
return Err(s3_error!(NoSuchBucket));
}
Ok(S3Response::new(HeadBucketOutput::default()))
}
async fn delete_object_tagging(
&self,
req: S3Request<DeleteObjectTaggingInput>,
) -> S3Result<S3Response<DeleteObjectTaggingOutput>> {
self.0
.lock()
.expect("probe state")
.calls
.push(("DeleteObjectTagging", req.input.version_id));
Ok(S3Response::new(DeleteObjectTaggingOutput::default()))
}
async fn abort_multipart_upload(
&self,
req: S3Request<AbortMultipartUploadInput>,
) -> S3Result<S3Response<AbortMultipartUploadOutput>> {
self.0
.lock()
.expect("probe state")
.calls
.push(("AbortMultipartUpload", Some(req.input.upload_id)));
Ok(S3Response::new(AbortMultipartUploadOutput::default()))
}
async fn delete_bucket_policy(
&self,
_: S3Request<DeleteBucketPolicyInput>,
) -> S3Result<S3Response<DeleteBucketPolicyOutput>> {
self.0.lock().expect("probe state").calls.push(("DeleteBucketPolicy", None));
Ok(S3Response::new(DeleteBucketPolicyOutput::default()))
}
async fn get_object_acl(&self, _: S3Request<GetObjectAclInput>) -> S3Result<S3Response<GetObjectAclOutput>> {
self.0.lock().expect("probe state").calls.push(("GetObjectAcl", None));
Ok(S3Response::new(GetObjectAclOutput::default()))
}
async fn put_object_acl(&self, _: S3Request<PutObjectAclInput>) -> S3Result<S3Response<PutObjectAclOutput>> {
self.0.lock().expect("probe state").calls.push(("PutObjectAcl", None));
Ok(S3Response::new(PutObjectAclOutput::default()))
}
async fn get_bucket_acl(&self, _: S3Request<GetBucketAclInput>) -> S3Result<S3Response<GetBucketAclOutput>> {
self.0.lock().expect("probe state").calls.push(("GetBucketAcl", None));
Ok(S3Response::new(GetBucketAclOutput::default()))
}
async fn put_bucket_acl(&self, _: S3Request<PutBucketAclInput>) -> S3Result<S3Response<PutBucketAclOutput>> {
self.0.lock().expect("probe state").calls.push(("PutBucketAcl", None));
Ok(S3Response::new(PutBucketAclOutput::default()))
}
}
struct CustomRoute;
struct MethodValidation;
#[async_trait]
impl S3Access for MethodValidation {
async fn check(&self, context: &mut S3AccessContext<'_>) -> S3Result<()> {
validate_method_subresource(context.method(), context.uri().query()).map_err(|violation| match violation {
RequestViolation::DeleteAcl => s3_error!(MethodNotAllowed),
})
}
}
#[derive(Clone)]
struct CustomRouteMatched;
#[async_trait]
impl S3Route for CustomRoute {
fn is_match(&self, _: &Method, uri: &Uri, _: &HeaderMap, extensions: &mut Extensions) -> bool {
if uri.path() == "/custom" {
extensions.insert(CustomRouteMatched);
return true;
}
false
}
async fn check_access(&self, req: &mut S3Request<Body>) -> S3Result<()> {
assert!(req.extensions.get::<CustomRouteMatched>().is_some());
if req.headers.contains_key("x-test-deny") {
return Err(s3_error!(AccessDenied));
}
assert!(req.credentials.is_some(), "custom route retains verified credentials");
Ok(())
}
async fn call(&self, req: S3Request<Body>) -> S3Result<S3Response<Body>> {
assert!(req.extensions.get::<CustomRouteMatched>().is_some());
Ok(S3Response::new(Body::from("custom route".to_owned())))
}
}
fn service(virtual_host: bool) -> (S3Service, ProbeS3) {
let probe = ProbeS3::default();
let mut builder = S3ServiceBuilder::new(probe.clone());
builder.set_auth(SimpleAuth::from_single("test-key", "test-secret"));
builder.set_access(MethodValidation);
builder.set_route(CustomRoute);
let mut config = s3s::config::S3Config::default();
config.enable_sig_v2 = true;
config.normalize_forward_slash_path = true;
builder.set_config(Arc::new(s3s::config::StaticConfigProvider::new(Arc::new(config))));
if virtual_host {
builder.set_host(SingleDomain::new("s3.example.test").expect("test domain"));
}
(builder.build(), probe)
}
fn signed_request(method: Method, uri: &str, presigned: bool, secret: &str) -> Request<Body> {
signed_request_with_credentials(method, uri, presigned, "test-key", secret)
}
fn signed_request_with_credentials(method: Method, uri: &str, presigned: bool, access_key: &str, secret: &str) -> Request<Body> {
let uri: Uri = uri.parse().expect("test URI");
let host = uri.authority().expect("test authority").as_str();
let timestamp = OffsetDateTime::now_utc()
.format(format_description!("[year][month][day]T[hour][minute][second]Z"))
.expect("format SigV4 timestamp");
let date = AmzDate::parse(&timestamp).expect("test date");
let credential = format!("{access_key}/{}/us-east-1/s3/aws4_request", date.fmt_date());
let mut query: Vec<(String, String)> = url::form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes())
.into_owned()
.collect();
let mut request = Request::builder()
.method(method.clone())
.header("host", host)
.header("content-length", "0");
if presigned {
query.extend([
("X-Amz-Algorithm".into(), "AWS4-HMAC-SHA256".into()),
("X-Amz-Credential".into(), credential),
("X-Amz-Date".into(), timestamp),
("X-Amz-Expires".into(), "300".into()),
("X-Amz-SignedHeaders".into(), "host".into()),
]);
let canonical = create_presigned_canonical_request(method.as_str(), uri.path(), &query, [("host", host)]);
let to_sign = create_string_to_sign(&canonical, &date, "us-east-1", "s3");
query.push(("X-Amz-Signature".into(), calculate_signature(&to_sign, secret, &date, "us-east-1", "s3")));
let query = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(&query)
.finish();
request = request.uri(format!("http://{host}{}?{query}", uri.path()));
} else {
let canonical = create_canonical_request(
method.as_str(),
uri.path(),
&query,
[
("host", host),
("x-amz-content-sha256", EMPTY_STRING_SHA256_HASH),
("x-amz-date", &timestamp),
],
Payload::SingleChunk(EMPTY_STRING_SHA256_HASH),
);
let to_sign = create_string_to_sign(&canonical, &date, "us-east-1", "s3");
let signature = calculate_signature(&to_sign, secret, &date, "us-east-1", "s3");
request = request
.uri(uri.clone())
.header("x-amz-date", timestamp)
.header("x-amz-content-sha256", EMPTY_STRING_SHA256_HASH)
.header("authorization", format!("AWS4-HMAC-SHA256 Credential={credential}, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature={signature}"));
}
request.body(Body::empty()).expect("signed request")
}
async fn response(service: &S3Service, request: Request<Body>) -> (StatusCode, String) {
let response = service.call(request).await.expect("S3 service response");
let status = response.status();
let bytes = response.into_body().collect().await.expect("response body").to_bytes();
(status, String::from_utf8(bytes.to_vec()).expect("UTF-8 test response"))
}
#[tokio::test]
async fn delete_acl_preserves_objects_and_buckets_for_signed_requests() {
for virtual_host in [false, true] {
let base = if virtual_host {
"http://bucket.s3.example.test"
} else {
"http://s3.example.test/bucket"
};
for presigned in [false, true] {
let (service, probe) = service(virtual_host);
for path in ["", "/", "/key"] {
for query in [
"acl",
"acl=",
"%61cl",
"a%63l=anything",
"acl&acl=",
"acl&versionId=version-1",
"acl&tagging",
"acl&uploadId=upload-1",
] {
let uri = format!("{base}{path}?{query}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{uri}: {body}");
assert!(body.contains("<Code>MethodNotAllowed</Code>"), "{uri}: {body}");
}
let operation = if path == "/key" { "DeleteObject" } else { "DeleteBucket" };
let uri = format!("{base}{path}?acl&x-id={operation}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{uri}: {body}");
}
assert!(
probe.0.lock().expect("probe state").calls.is_empty(),
"refused requests must not reach S3 handlers"
);
let (status, body) =
response(&service, signed_request(Method::GET, &format!("{base}/key"), presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "original object");
let (status, _) =
response(&service, signed_request(Method::HEAD, &format!("{base}/"), presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK, "bucket must still exist");
}
}
}
#[tokio::test]
async fn delete_acl_keeps_signature_verification_before_method_rejection() {
let (service, probe) = service(false);
for presigned in [false, true] {
for query in ["acl", "versionId=version-1"] {
let uri = format!("http://s3.example.test/bucket/key?{query}");
let (status, body) = response(&service, signed_request(Method::DELETE, &uri, presigned, "wrong-secret")).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert!(body.contains("<Code>SignatureDoesNotMatch</Code>"), "{body}");
}
}
assert!(probe.0.lock().expect("probe state").calls.is_empty());
}
#[tokio::test]
async fn delete_acl_keeps_supported_s3_operations_and_parameters() {
for presigned in [false, true] {
for (method, path, operation, parameter) in [
(Method::DELETE, "/bucket/key", "DeleteObject", None),
(Method::DELETE, "/bucket/key?versionId=version-1", "DeleteObject", Some("version-1")),
(
Method::DELETE,
"/bucket/key?versionId=null&x-id=DeleteObject",
"DeleteObject",
Some("null"),
),
(Method::DELETE, "/bucket/key?custom=value&other=acl", "DeleteObject", None),
(Method::DELETE, "/bucket/key?ACL&acl-extra&%2561cl", "DeleteObject", None),
(
Method::DELETE,
"/bucket/key?tagging&versionId=version-1",
"DeleteObjectTagging",
Some("version-1"),
),
(Method::DELETE, "/bucket/key?uploadId=upload-1", "AbortMultipartUpload", Some("upload-1")),
(Method::DELETE, "/bucket", "DeleteBucket", None),
(Method::DELETE, "/bucket?policy", "DeleteBucketPolicy", None),
(Method::GET, "/bucket/key?acl", "GetObjectAcl", None),
(Method::PUT, "/bucket/key?acl", "PutObjectAcl", None),
(Method::GET, "/bucket?acl", "GetBucketAcl", None),
(Method::PUT, "/bucket?acl", "PutBucketAcl", None),
] {
let (service, probe) = service(false);
let uri = format!("http://s3.example.test{path}");
let (status, body) = response(&service, signed_request(method, &uri, presigned, "test-secret")).await;
assert!(status.is_success(), "{operation} {uri}: {status} {body}");
assert_eq!(probe.0.lock().expect("probe state").calls, [(operation, parameter.map(str::to_owned))]);
}
}
}
#[tokio::test]
async fn delete_acl_preserves_custom_route_matching_and_access() {
let (service, probe) = service(false);
for presigned in [false, true] {
let uri = "http://s3.example.test/custom?acl";
let (status, body) = response(&service, signed_request(Method::DELETE, uri, presigned, "test-secret")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "custom route");
let mut denied = signed_request(Method::DELETE, uri, presigned, "test-secret");
denied
.headers_mut()
.insert("x-test-deny", http::HeaderValue::from_static("true"));
let (status, body) = response(&service, denied).await;
assert_eq!(status, StatusCode::FORBIDDEN);
assert!(body.contains("<Code>AccessDenied</Code>"));
}
assert!(probe.0.lock().expect("probe state").calls.is_empty());
}
#[tokio::test]
async fn delete_acl_preserves_sigv2_header_and_query_authentication() {
for presigned in [false, true] {
for (query, secret, expected_status, expected_code) in [
("acl", "test-secret", StatusCode::METHOD_NOT_ALLOWED, Some("MethodNotAllowed")),
("acl", "wrong-secret", StatusCode::FORBIDDEN, Some("SignatureDoesNotMatch")),
("versionId=version-1", "test-secret", StatusCode::NO_CONTENT, None),
] {
let (service, probe) = service(false);
let date = OffsetDateTime::now_utc()
.format(format_description!(
"[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT"
))
.expect("format SigV2 HTTP date");
let request = Request::builder()
.method(Method::DELETE)
.uri(format!("http://s3.example.test/bucket/key?{query}"))
.header("host", "s3.example.test")
.header("content-length", "0")
.header("date", date)
.body(Body::empty())
.expect("SigV2 request");
let request = if presigned {
let mut request =
rustfs_signer::try_pre_sign_v2(request, "test-key", secret, 60, false).expect("presign SigV2 request");
let uri = request.uri().to_string();
let (prefix, signature) = uri.rsplit_once("&Signature=").expect("SigV2 signature");
let encoded = url::form_urlencoded::Serializer::new(String::new())
.append_pair("Signature", signature)
.finish();
*request.uri_mut() = format!("{prefix}&{encoded}").parse().expect("encoded SigV2 URI");
request
} else {
rustfs_signer::try_sign_v2(request, 0, "test-key", secret, false).expect("sign SigV2 request")
};
let (status, body) = response(&service, request).await;
assert_eq!(status, expected_status, "{query}: {body}");
if let Some(code) = expected_code {
assert!(body.contains(&format!("<Code>{code}</Code>")), "{body}");
assert!(probe.0.lock().expect("probe state").calls.is_empty());
} else {
assert_eq!(probe.0.lock().expect("probe state").calls, [("DeleteObject", Some("version-1".into()))]);
}
}
}
}
async fn live_delete(
env: &crate::common::RustFSTestEnvironment,
path: &str,
presigned: bool,
secret: &str,
) -> (StatusCode, String) {
let request =
signed_request_with_credentials(Method::DELETE, &format!("{}{path}", env.url), presigned, &env.access_key, secret);
let response = crate::common::local_http_client()
.delete(request.uri().to_string())
.headers(request.headers().clone())
.send()
.await
.expect("send signed DELETE to RustFS");
let status = response.status();
(status, response.text().await.expect("read DELETE response"))
}
#[tokio::test]
async fn delete_acl_admission_through_gateway_edge() {
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{BucketVersioningStatus, Tag, Tagging, VersioningConfiguration};
let mut env = crate::common::RustFSTestEnvironment::new()
.await
.expect("isolated S3 environment");
env.start_rustfs_server_without_cleanup_with_env(&[("RUSTFS_REGION", "us-east-1")])
.await
.expect("start RustFS");
let client = env.create_s3_client();
let bucket = "acl-admission";
let empty_bucket = "acl-admission-empty";
env.create_test_bucket(bucket).await.expect("create object bucket");
env.create_test_bucket(empty_bucket).await.expect("create empty bucket");
client
.put_bucket_versioning()
.bucket(bucket)
.versioning_configuration(
VersioningConfiguration::builder()
.status(BucketVersioningStatus::Enabled)
.build(),
)
.send()
.await
.expect("enable versioning");
let object = client
.put_object()
.bucket(bucket)
.key("key")
.body(ByteStream::from_static(b"original object"))
.send()
.await
.expect("create preserved object");
let version = object.version_id().expect("versioned object ID");
let version_query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("versionId", version)
.finish();
// The gateway wire parser refuses escaped parameter names before signature verification.
let encoded_path = format!("/{bucket}/key?%61cl&{version_query}");
let (status, body) = live_delete(&env, &encoded_path, false, &env.secret_key).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{encoded_path}: {body}");
assert!(body.contains("<Code>InvalidArgument</Code>"), "{body}");
for presigned in [false, true] {
// SigV4 canonicalization rejects repeated parameter names before admission.
let repeated_path = format!("/{bucket}/key?acl&acl=&tagging");
let (status, body) = live_delete(&env, &repeated_path, presigned, &env.secret_key).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{repeated_path}: {body}");
assert!(body.contains("<Code>AuthorizationHeaderMalformed</Code>"), "{body}");
for path in [
format!("/{empty_bucket}?acl"),
format!("/{bucket}/key?acl&{version_query}"),
format!("/{bucket}/key?acl&tagging"),
format!("/{bucket}/key?acl&uploadId=upload-1"),
] {
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED, "{path}: {body}");
assert!(body.contains("<Code>MethodNotAllowed</Code>"), "{body}");
let (status, body) = live_delete(&env, &path, presigned, "wrong-secret").await;
assert_eq!(status, StatusCode::FORBIDDEN, "{path}: {body}");
assert!(body.contains("<Code>SignatureDoesNotMatch</Code>"), "{body}");
}
client
.head_bucket()
.bucket(empty_bucket)
.send()
.await
.expect("refused DELETE preserves empty bucket");
let current = client
.get_object()
.bucket(bucket)
.key("key")
.send()
.await
.expect("refused DELETE leaves the current object readable");
assert_eq!(current.version_id(), Some(version));
let body = current.body.collect().await.expect("read preserved object").into_bytes();
assert_eq!(body.as_ref(), b"original object");
client
.put_object_tagging()
.bucket(bucket)
.key("key")
.version_id(version)
.tagging(
Tagging::builder()
.tag_set(Tag::builder().key("test").value("acl").build().expect("tag"))
.build()
.expect("tagging"),
)
.send()
.await
.expect("set object tags");
let path = format!("/{bucket}/key?tagging&{version_query}");
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert!(status.is_success(), "{path}: {body}");
let tags = client
.get_object_tagging()
.bucket(bucket)
.key("key")
.version_id(version)
.send()
.await
.expect("read cleared tags");
assert!(tags.tag_set().is_empty());
let upload = client
.create_multipart_upload()
.bucket(bucket)
.key("upload")
.send()
.await
.expect("start multipart upload");
let query = url::form_urlencoded::Serializer::new(String::new())
.append_pair("uploadId", upload.upload_id().expect("upload ID"))
.finish();
let path = format!("/{bucket}/upload?{query}");
let (status, body) = live_delete(&env, &path, presigned, &env.secret_key).await;
assert!(status.is_success(), "{path}: {body}");
let uploads = client
.list_multipart_uploads()
.bucket(bucket)
.send()
.await
.expect("list remaining uploads");
assert!(uploads.uploads().is_empty());
}
let path = format!("/{bucket}/key?{version_query}");
let (status, body) = live_delete(&env, &path, false, &env.secret_key).await;
assert_eq!(status, StatusCode::NO_CONTENT, "{path}: {body}");
let versions = client
.list_object_versions()
.bucket(bucket)
.send()
.await
.expect("list remaining versions");
assert!(versions.versions().is_empty());
let (status, body) = live_delete(&env, &format!("/{empty_bucket}"), false, &env.secret_key).await;
assert_eq!(status, StatusCode::NO_CONTENT, "{body}");
env.stop_server();
}
+1 -52
View File
@@ -34,10 +34,7 @@
#[cfg(test)]
mod tests {
use crate::common::{
AdminTransport, RustFSTestEnvironment, admin_attach_user_policy_via, admin_create_user, admin_request_with_session_token,
init_logging, local_http_client, parse_assume_role_credentials,
};
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
use hmac::{Hmac, KeyInit as _, Mac};
use http::header::HOST;
use rustfs_s3_types::Body;
@@ -399,54 +396,6 @@ mod tests {
let (status, _) = signed_request(&env.url, http::Method::GET, ACCOUNT_INFO_PATH, None, user_ak, old_sk).await?;
assert!(status.is_client_error(), "the old secret must stop working, status: {status}");
env.stop_server();
drop(env);
console_session_rotates_the_iam_password_and_revokes_the_old_session().await
}
async fn console_session_rotates_the_iam_password_and_revokes_the_old_session() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server(vec![]).await?;
let user = "console-password-user";
let old_password = uuid::Uuid::new_v4().to_string();
let new_password = uuid::Uuid::new_v4().to_string();
admin_create_user(&env, user, &old_password).await?;
admin_attach_user_policy_via(AdminTransport::Signed, &env.url, &env.access_key, &env.secret_key, "readonly", user)
.await?;
let (status, response) = assume_role(&env.url, user, &old_password, None).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the current password must sign in");
let (session_key, session_secret, token) = parse_assume_role_credentials(&response)?;
let session_request = |method, path, body| {
admin_request_with_session_token(&env.url, method, path, body, &session_key, &session_secret, Some(&token))
};
let password_request = |current: &str| {
Some(serde_json::json!({ "current_secret_key": current, "new_secret_key": new_password }).to_string())
};
let (status, body) =
session_request(http::Method::POST, ACCOUNT_PASSWORD_PATH, password_request(&session_secret)).await?;
assert_eq!(
status,
reqwest::StatusCode::BAD_REQUEST,
"the session secret must not be accepted as the IAM password"
);
assert!(body.contains("InvalidRequest") && body.contains("the current secret key is incorrect"));
let (status, body) = session_request(http::Method::POST, ACCOUNT_PASSWORD_PATH, password_request(&old_password)).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the same session must accept the current IAM password");
assert_eq!(serde_json::from_str::<serde_json::Value>(&body)?["sessions_revoked"], 1);
let (status, _) = session_request(http::Method::GET, ACCOUNT_INFO_PATH, None).await?;
assert_eq!(status, reqwest::StatusCode::FORBIDDEN, "the pre-rotation session must be revoked");
let (status, _) = assume_role(&env.url, user, &old_password, None).await?;
assert_eq!(status, reqwest::StatusCode::FORBIDDEN, "the old password must no longer sign in");
let (status, response) = assume_role(&env.url, user, &new_password, None).await?;
assert_eq!(status, reqwest::StatusCode::OK, "the new password must sign in");
parse_assume_role_credentials(&response)?;
env.stop_server();
Ok(())
}
-1
View File
@@ -36,7 +36,6 @@ mod replication_delete_marker_test;
mod replication_quota_test;
mod s3_basic_test;
mod s3_during_data_movement_test;
mod scanner_cluster_observation_test;
mod scanner_heal_topology_fixture;
mod scanner_heal_topology_test;
mod scanner_heal_topology_tier_test;
@@ -159,7 +159,6 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
let info_body = cluster_admin_ok(&dist.cluster, Method::GET, "/rustfs/admin/v3/info", None).await?;
let info: Value = serde_json::from_str(&info_body)?;
assert!(info.get("inventory").is_none(), "inventory requires explicit opt-in");
let servers = info["info"]["servers"]
.as_array()
.ok_or_else(|| format!("admin info omitted servers: {info}"))?;
@@ -201,24 +200,6 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
assert!(sample.finally, "node {node_idx} metrics sample was not terminal");
assert!(sample.errors.is_empty(), "node {node_idx} metrics reported errors: {:?}", sample.errors);
assert!(!sample.hosts.is_empty(), "node {node_idx} metrics omitted hosts");
assert!(sample.scanner_node.is_none(), "default metrics must not expose the internal peer sample");
wait_until(
Duration::from_secs(30),
|| async {
let frame: Value = serde_json::from_str(
&node_admin_body(&dist, node_idx, "/rustfs/admin/v3/realtime?scope=cluster&types=1&n=1").await?,
)?;
assert_eq!(frame["final"], true);
let summary = &frame["cluster_scanner"];
assert_eq!(summary["nodes_total"], 4, "known cluster membership");
assert!(summary["sampled_at"].as_str().is_some());
assert!(matches!(summary["state"].as_str(), Some("scanning" | "idle" | "unknown")));
assert_eq!(summary["current"].is_object(), summary["state"] == "scanning");
Ok(summary["nodes_responded"] == 4)
},
"every request node reaches the full scanner peer set",
)
.await?;
}
let targets_body = cluster_admin_ok(&dist.cluster, Method::GET, "/rustfs/admin/v3/audit/target/list", None).await?;
@@ -253,38 +234,6 @@ async fn four_node_health_inventory_metrics_and_audit_delivery_are_consistent()
"audit entry leaked the root secret key"
);
let pending = unique_bucket("inventory");
dist.create_bucket(&pending).await?;
let listed = dist.client(1)?.list_buckets().send().await?;
assert_eq!(listed.buckets().len(), 2, "expected the two test buckets");
wait_until(
Duration::from_secs(30),
|| async {
let body = node_admin_body(&dist, 1, "/rustfs/admin/v3/info?include=inventory").await?;
let response: Value = serde_json::from_str(&body)?;
let inventory: rustfs_madmin::ClusterInventory = serde_json::from_value(response["inventory"].clone())?;
if inventory.current_buckets != Some(2) {
return Ok(false);
}
match inventory.measured_buckets {
None | Some(0) => {
assert_eq!(inventory.measured_objects, None);
assert_eq!(inventory.measured_bytes, None);
}
Some(1 | 2) => {
assert!(inventory.measured_objects.is_some_and(|objects| objects <= 1));
}
Some(count) => panic!("measured {count} buckets across a two-bucket namespace"),
}
if inventory.measured_buckets != Some(2) {
assert_ne!(inventory.converged, Some(true));
}
Ok(true)
},
"inventory reflects the current namespace and reports scanner coverage independently",
)
.await?;
let result = verify_write_observations_during_peer_failure(&dist, &bucket).await;
collector.abort();
result
@@ -1,111 +0,0 @@
// Copyright 2026 RustFS Team
// SPDX-License-Identifier: Apache-2.0
use super::harness::{NODE_COUNT, TestResult, wait_until};
use super::scanner_peer_bucket_fixture::PeerBucketRun;
use crate::common::init_logging;
use futures::future::try_join_all;
use serde_json::Value;
use std::time::Duration;
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
const CLUSTER_SCANNER: &str = "/rustfs/admin/v3/realtime?n=1&types=1&scope=cluster";
const OBSERVATION_TIMEOUT: Duration = Duration::from_secs(35);
async fn scanner_frames(run: &PeerBucketRun) -> TestResult<Vec<Value>> {
try_join_all((0..NODE_COUNT).map(|node| run.admin_json(node, CLUSTER_SCANNER))).await
}
fn full_sample(frame: &Value) -> bool {
frame["final"] == true
&& frame["cluster_scanner"]["nodes_total"] == NODE_COUNT
&& frame["cluster_scanner"]["nodes_responded"] == NODE_COUNT
}
#[tokio::test]
async fn followers_report_the_coordinators_active_progress_and_committed_completion() -> TestResult {
init_logging();
let mut run = PeerBucketRun::start("cluster-scanner-observation").await?;
let baseline = run.quiet_baseline().await?;
let leader = run.leader().await?;
let pid = run.pid(leader)?;
let hot = run.buckets[2].clone();
run.barrier.arm("before_start_snapshot", pid, None)?;
run.barrier.start_session(&run.buckets)?;
// All four child processes and the harness use the same host clock.
let written_after = OffsetDateTime::now_utc();
run.put(leader, &hot, "wake-cluster-observation", 149).await?;
let start = run.barrier.wait_stage("before_start_snapshot", pid, None, true).await?;
let epoch = start["detail"]["epoch"].as_u64().ok_or("start gate omitted epoch")?;
let cycle = start["detail"]["cycle"].as_u64().ok_or("start gate omitted cycle")?;
if baseline.scanner_epoch != Some(epoch) || baseline.scanner_cycle.is_none_or(|previous| previous >= cycle) {
return Err("controlled cycle did not follow the quiet baseline under the same coordinator".into());
}
run.barrier.arm("root_durable", pid, Some((epoch, cycle)))?;
run.barrier.release("before_start_snapshot", pid)?;
run.barrier
.wait_stage("root_durable", pid, Some((epoch, cycle)), true)
.await?;
// The leader is held after the real walk and before committing its cycle completion.
// Each ingress node maintains its own short-lived cluster sample cache.
let expected_leader = &run.dist.cluster.nodes[leader].url;
let active = wait_until(
OBSERVATION_TIMEOUT,
|| async {
let frames = scanner_frames(&run).await?;
let started = frames[leader]["cluster_scanner"]["current"]["started_at"].as_str();
let consistent = started.is_some()
&& frames.iter().all(|frame| {
let summary = &frame["cluster_scanner"];
let current = &summary["current"];
full_sample(frame)
&& summary["state"] == "scanning"
&& current["cycle"] == cycle
&& current["leader"].as_str() == Some(expected_leader.as_str())
&& current["started_at"].as_str() == started
&& current["objects_scanned"].as_u64().is_some_and(|objects| objects > 0)
});
if !consistent {
tracing::info!(
?frames,
cycle,
expected_leader,
"waiting for active scanner progress on every ingress node"
);
}
Ok(consistent)
},
"leader and all three followers report the identified active cycle with nonzero work",
)
.await;
run.barrier.disarm()?;
run.barrier.release("root_durable", pid)?;
active?;
wait_until(
OBSERVATION_TIMEOUT,
|| async {
let frames = scanner_frames(&run).await?;
let settled = frames.iter().all(|frame| {
let summary = &frame["cluster_scanner"];
full_sample(frame)
&& summary["state"] == "idle"
&& summary.get("current").is_none()
&& summary["last_attempt"]["cycle"] == cycle
&& summary["last_attempt"]["result"] == "success"
&& summary["last_success_at"].as_str().is_some_and(|value| {
OffsetDateTime::parse(value, &Rfc3339).is_ok_and(|completed| completed >= written_after)
})
});
if !settled {
tracing::info!(?frames, cycle, "waiting for the controlled scanner cycle to finish");
}
Ok(settled)
},
"every ingress node reports the completed cycle and an idle cluster scanner",
)
.await
}
-6
View File
@@ -12,9 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(test)]
mod access_request_validation_test;
#[cfg(test)]
mod storage_metric_ownership_test;
@@ -108,9 +105,6 @@ mod replication_target_matrix_test;
#[cfg(test)]
mod data_usage_test;
#[cfg(test)]
mod scanner_wide_directory_test;
// KMS-specific test modules
#[cfg(test)]
mod kms;
@@ -864,70 +864,6 @@ async fn test_webhook_event_delivery_and_filtering() -> TestResult {
Ok(())
}
#[tokio::test]
async fn test_webhook_subscriptions_follow_bucket_incarnation() -> TestResult {
init_logging();
let (endpoint, mut rx, collector) = spawn_event_collector().await?;
let allowed_origin = endpoint_origin(&endpoint)?;
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &[(ENV_OUTBOUND_ALLOW_ORIGINS, allowed_origin.as_str())])
.await?;
enable_notify_module(&env).await?;
let target = "incarnation";
configure_webhook_target(&env, target, &endpoint).await?;
wait_for_target_registered(&env, target).await?;
let client = env.create_s3_client();
let bucket = "notify-incarnation";
let control_bucket = "notify-incarnation-control";
for name in [bucket, control_bucket] {
client.create_bucket().bucket(name).send().await?;
put_notification_config(&client, name, target, "events/", ".txt").await?;
}
let put = |bucket, key| {
client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from_static(b"event fixture"))
.send()
};
let wait = Duration::from_secs(20);
let original_key = "events/original.txt";
put(bucket, original_key).await?;
wait_for_event(&mut rx, original_key, "s3:ObjectCreated:", wait).await?;
assert!(client.delete_bucket().bucket(bucket).send().await.is_err());
let after_failed_delete = "events/retained.txt";
put(bucket, after_failed_delete).await?;
wait_for_event(&mut rx, after_failed_delete, "s3:ObjectCreated:", wait).await?;
for key in [original_key, after_failed_delete] {
client.delete_object().bucket(bucket).key(key).send().await?;
}
client.delete_bucket().bucket(bucket).send().await?;
client.create_bucket().bucket(bucket).send().await?;
let config = client.get_bucket_notification_configuration().bucket(bucket).send().await?;
assert!(config.queue_configurations().is_empty());
let new_key = "events/fresh.txt";
let sentinel_key = "events/sentinel.txt";
put(bucket, new_key).await?;
put(control_bucket, sentinel_key).await?;
let events = collect_until(&mut rx, sentinel_key, wait, Duration::from_secs(2)).await;
assert!(events.iter().any(|event| event_key(event).as_deref() == Some(sentinel_key)));
assert!(events.iter().all(|event| event_key(event).as_deref() != Some(new_key)));
put_notification_config(&client, bucket, target, "events/", ".txt").await?;
let subscribed_key = "events/subscribed.txt";
put(bucket, subscribed_key).await?;
wait_for_event(&mut rx, subscribed_key, "s3:ObjectCreated:", wait).await?;
env.stop_server();
collector.abort();
Ok(())
}
/// An event queued while the target endpoint rejects delivery survives on the
/// durable store and is redelivered once the endpoint comes back.
#[tokio::test]
@@ -1026,101 +962,3 @@ async fn test_webhook_redelivers_event_after_target_recovers() -> TestResult {
handle.abort();
Ok(())
}
#[tokio::test]
async fn test_webhook_metadata_mutations_keep_verified_bucket_identity() -> TestResult {
init_logging();
let (endpoint, mut rx, collector) = spawn_event_collector().await?;
let allowed_origin = endpoint_origin(&endpoint)?;
let mut env = RustFSTestEnvironment::new().await?;
env.start_rustfs_server_with_env(vec![], &[(ENV_OUTBOUND_ALLOW_ORIGINS, allowed_origin.as_str())])
.await?;
enable_notify_module(&env).await?;
let target = "metadata-events";
configure_webhook_target(&env, target, &endpoint).await?;
wait_for_target_registered(&env, target).await?;
let client = env.create_s3_client();
let bucket = "metadata-event-identity";
let key = "object";
client.create_bucket().bucket(bucket).send().await?;
client
.put_object()
.bucket(bucket)
.key(key)
.body(ByteStream::from_static(b"metadata"))
.send()
.await?;
let queue = QueueConfiguration::builder()
.id("metadata-events")
.queue_arn(target_arn(target))
.events(Event::from("s3:ObjectTagging:*"))
.events(Event::from("s3:ObjectAcl:Put"))
.events(Event::from("s3:BucketRemoved:*"))
.build()?;
client
.put_bucket_notification_configuration()
.bucket(bucket)
.notification_configuration(NotificationConfiguration::builder().queue_configurations(queue).build())
.send()
.await?;
let tagging = aws_sdk_s3::types::Tagging::builder()
.tag_set(aws_sdk_s3::types::Tag::builder().key("kind").value("test").build()?)
.build()?;
client
.put_object_tagging()
.bucket(bucket)
.key(key)
.tagging(tagging)
.send()
.await?;
assert_eq!(
client
.get_object_tagging()
.bucket(bucket)
.key(key)
.send()
.await?
.tag_set()
.len(),
1
);
wait_for_event(&mut rx, key, "s3:ObjectTagging:Put", Duration::from_secs(20)).await?;
client.delete_object_tagging().bucket(bucket).key(key).send().await?;
assert!(
client
.get_object_tagging()
.bucket(bucket)
.key(key)
.send()
.await?
.tag_set()
.is_empty()
);
wait_for_event(&mut rx, key, "s3:ObjectTagging:Delete", Duration::from_secs(20)).await?;
client
.put_object_acl()
.bucket(bucket)
.key(key)
.acl(aws_sdk_s3::types::ObjectCannedAcl::Private)
.send()
.await?;
wait_for_event(&mut rx, key, "s3:ObjectAcl:Put", Duration::from_secs(20)).await?;
client.delete_object().bucket(bucket).key(key).send().await?;
client.delete_bucket().bucket(bucket).send().await?;
let removed = timeout(Duration::from_secs(20), async {
loop {
let event = rx.recv().await.expect("bucket-event collector remains open");
if event["EventName"]
.as_str()
.is_some_and(|name| name.starts_with("s3:BucketRemoved:"))
{
break event;
}
}
})
.await?;
assert_eq!(removed["Records"][0]["s3"]["bucket"]["name"].as_str(), Some(bucket));
env.stop_server();
collector.abort();
Ok(())
}
@@ -24,7 +24,7 @@
#[cfg(all(test, target_os = "linux"))]
mod tests {
use crate::chaos::{VersionShardCensus, census_object_version_on_disk};
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment, admin_request, init_logging, local_http_client};
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment, admin_request, init_logging};
use aws_sdk_s3::Client;
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::types::{BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, VersioningConfiguration};
@@ -412,7 +412,7 @@ mod tests {
.arg(test_binary)
.arg("--exact")
.arg(test_name)
.arg("--include-ignored")
.arg("--ignored")
.arg("--nocapture")
.env(NAMESPACE_ENV, "1")
.status()?;
@@ -1524,110 +1524,6 @@ mod tests {
assert!(assert_no_replacement_status_records_in_status(&definitive, target).is_ok());
}
/// Linux mount namespaces are per-thread; keep mount setup and process
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
#[tokio::test(flavor = "current_thread")]
async fn test_privileged_4x1_subdirectory_replacement_waits_for_write_quorum() -> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
if !privileged_run_enabled()? {
return Ok(());
}
if std::env::var_os(NAMESPACE_ENV).is_none() {
return run_current_test_in_mount_namespace(
"replacement_privileged_e2e_test::tests::test_privileged_4x1_subdirectory_replacement_waits_for_write_quorum",
);
}
let mut mounts = MountNamespaceGuard::new()?;
let mut cluster = RustFSTestClusterEnvironment::new(4).await?;
let filesystem: serde_json::Value = serde_json::from_str(&run_command_stdout(
"findmnt",
&["--json", "--target", &cluster.temp_dir, "--output", "TARGET,FSTYPE"],
)?)?;
let xfs_root = filesystem["filesystems"][0]["target"]
.as_str()
.filter(|root| *root != "/" && filesystem["filesystems"][0]["fstype"] == "xfs");
for (index, node) in cluster.nodes.iter_mut().enumerate() {
let mount = PathBuf::from(&node.data_dir);
if xfs_root.is_none() {
mounts.mount_tmpfs(&mount, &format!("rustfs-replacement-4x1-{index}"))?;
}
let data = mount.join("data");
fs::create_dir(&data)?;
node.data_dir = path_to_string(&data, "replacement subdirectory")?;
node.data_dirs[0] = node.data_dir.clone();
}
let target = PathBuf::from(&cluster.nodes[TARGET_NODE].data_dir);
let mount = xfs_root.unwrap_or(target.parent().and_then(Path::to_str).ok_or("missing target mount root")?);
eprintln!(
"4x1 replacement fixture filesystem = {}",
if xfs_root.is_some() { "xfs" } else { "tmpfs" }
);
cluster.set_node_env(TARGET_NODE, "RUSTFS_HEAL_REPLACEMENT_MOUNT_ROOTS", mount)?;
cluster.set_env("RUSTFS_STORAGE_CLASS_STANDARD", "EC:2");
cluster.set_env("RUSTFS_HEAL_ENABLED", "true");
cluster.set_env("RUSTFS_HEAL_INTERVAL_SECS", "1");
cluster.set_env("RUSTFS_SCANNER_START_DELAY_SECS", "0");
cluster.set_env("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", "false");
cluster.start().await?;
let clients = cluster.create_all_clients()?;
let versions = seed_baseline(&clients[0], &target, 0).await?;
cluster.stop_node_gracefully(TARGET_NODE).await?;
cluster.stop_node_gracefully(0).await?;
fs::remove_dir_all(&target)?;
fs::create_dir(&target)?;
let metadata = ["format.json", "pool.bin/xl.meta", "pool.bin.identity/xl.meta"];
let system_dir = Path::new(".rustfs.sys");
let survivor_files = cluster.nodes[2..]
.iter()
.flat_map(|node| metadata.map(|name| Path::new(&node.data_dir).join(system_dir).join(name)))
.map(|file| fs::read(&file).map(|bytes| (file, bytes)))
.collect::<std::io::Result<Vec<_>>>()?;
cluster.start_node_process(TARGET_NODE).await?;
let write_health = format!("{}/minio/health/cluster", cluster.nodes[2].url);
let http = local_http_client();
timeout(Duration::from_secs(30), async {
loop {
let status = http.get(&write_health).send().await?.status();
if status.as_u16() == 503 {
break;
}
sleep(Duration::from_millis(200)).await;
}
Ok::<_, reqwest::Error>(())
})
.await??;
verify_bodies(&clients[2], &versions).await?;
let version = &versions[0];
let failed_delete = clients[2]
.delete_object()
.bucket(&version.bucket)
.key(&version.key)
.send()
.await
.expect_err("two of four drives must not delete an existing object");
assert_eq!(failed_delete.raw_response().map(|response| response.status().as_u16()), Some(503));
for name in metadata {
assert!(!target.join(system_dir).join(name).try_exists()?, "unadmitted target published {name}");
}
for (file, before) in survivor_files {
assert_eq!(fs::read(&file)?, before, "surviving pool evidence changed below write quorum");
}
cluster.start_node(0).await?;
wait_for_completed_replacement_with_census(&cluster, &target, &versions, 90).await?;
for name in metadata {
assert!(fs::metadata(target.join(system_dir).join(name))?.is_file());
}
cluster.stop_node_gracefully(TARGET_NODE).await?;
cluster.start_node(TARGET_NODE).await?;
assert!(incomplete_versions(&target, &versions)?.is_empty());
verify_bodies(&clients[TARGET_NODE], &versions).await
}
/// Linux mount namespaces are per-thread; keep mount setup and process
/// spawning on one OS thread so child RustFS nodes inherit the test mounts.
#[tokio::test(flavor = "current_thread")]
+10 -331
View File
@@ -2075,18 +2075,12 @@ fn replication_response_hold() -> (ReplicationResponseHoldRuntime, ReplicationRe
)
}
#[derive(Clone)]
struct ReplicationProxyGate {
enabled: watch::Receiver<bool>,
blocked_admin_commit_path: Option<&'static str>,
}
async fn forward_replication_proxy_request(
request: Request<Incoming>,
backend_url: &str,
client: &reqwest::Client,
request_count: &AtomicU64,
mut gate: ReplicationProxyGate,
mut replication_enabled: watch::Receiver<bool>,
mut held_tagging: watch::Receiver<Option<String>>,
mut response_hold: ReplicationResponseHoldRuntime,
) -> Response<Full<bytes::Bytes>> {
@@ -2097,8 +2091,8 @@ async fn forward_replication_proxy_request(
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"REPLICA"));
if is_replication {
request_count.fetch_add(1, Ordering::Relaxed);
while !*gate.enabled.borrow() {
if gate.enabled.changed().await.is_err() {
while !*replication_enabled.borrow() {
if replication_enabled.changed().await.is_err() {
return proxy_error_response("replication gate closed");
}
}
@@ -2123,12 +2117,6 @@ async fn forward_replication_proxy_request(
Ok(body) => body.to_bytes(),
Err(error) => return proxy_error_response(error),
};
if gate.blocked_admin_commit_path == Some(parts.uri.path())
&& !*gate.enabled.borrow()
&& serde_json::from_slice::<serde_json::Value>(&body).is_ok_and(|payload| payload["phase"] == "commit")
{
return proxy_error_response("admin commit blocked by replication gate");
}
let mut forwarded = client.request(parts.method, format!("{backend_url}{path_and_query}"));
for (name, value) in &parts.headers {
forwarded = forwarded.header(name, value);
@@ -2165,7 +2153,7 @@ async fn start_replication_counting_proxy(
tasks: &mut JoinSet<()>,
) -> Result<(String, Arc<AtomicU64>, watch::Sender<bool>), Box<dyn Error + Send + Sync>> {
let (proxy_url, request_count, replication_enabled, _held_tagging, _response_hold) =
start_replication_counting_proxy_with_tag_hold(backend_url, tasks, None).await?;
start_replication_counting_proxy_with_tag_hold(backend_url, tasks).await?;
Ok((proxy_url, request_count, replication_enabled))
}
@@ -2173,11 +2161,9 @@ async fn start_replication_counting_proxy(
/// returned `watch::Sender<Option<String>>` holds `Some(tagging)`, replication
/// requests whose `x-amz-tagging` equals `tagging` are parked (and still
/// counted); all other traffic flows. Send `None` to release them.
/// An optional admin commit path rejects its commit phase while the replication gate is closed.
async fn start_replication_counting_proxy_with_tag_hold(
backend_url: &str,
tasks: &mut JoinSet<()>,
blocked_admin_commit_path: Option<&'static str>,
) -> Result<
(
String,
@@ -2194,10 +2180,6 @@ async fn start_replication_counting_proxy_with_tag_hold(
let request_count = Arc::new(AtomicU64::new(0));
let task_request_count = request_count.clone();
let (replication_enabled, task_replication_enabled) = watch::channel(true);
let gate = ReplicationProxyGate {
enabled: task_replication_enabled,
blocked_admin_commit_path,
};
let (held_tagging, task_held_tagging) = watch::channel(None);
let (response_hold_runtime, response_hold) = replication_response_hold();
tasks.spawn(async move {
@@ -2210,7 +2192,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
let backend_url = backend_url.clone();
let client = client.clone();
let request_count = task_request_count.clone();
let gate = gate.clone();
let replication_enabled = task_replication_enabled.clone();
let held_tagging = task_held_tagging.clone();
let response_hold = response_hold_runtime.clone();
connections.spawn(async move {
@@ -2218,7 +2200,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
let backend_url = backend_url.clone();
let client = client.clone();
let request_count = request_count.clone();
let gate = gate.clone();
let replication_enabled = replication_enabled.clone();
let held_tagging = held_tagging.clone();
let response_hold = response_hold.clone();
async move {
@@ -2228,7 +2210,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
&backend_url,
&client,
&request_count,
gate,
replication_enabled,
held_tagging,
response_hold,
)
@@ -2270,309 +2252,6 @@ async fn site_replication_remove(
Ok(serde_json::from_slice(&response.bytes().await?)?)
}
async fn decommission_site_v2(
env: &RustFSTestEnvironment,
request: &rustfs_madmin::SRRemoveV2Req,
) -> Result<rustfs_madmin::SRRemoveV2Status, Box<dyn Error + Send + Sync>> {
let response = signed_request(
http::Method::PUT,
&format!("{}/rustfs/admin/v3/site-replication/remove-v2", env.url),
&env.access_key,
&env.secret_key,
Some(serde_json::to_vec(request)?),
Some("application/json"),
)
.await?;
if response.status() != StatusCode::OK {
return Err(format!("decommission failed: {} {}", response.status(), response.text().await?).into());
}
Ok(response.json().await?)
}
#[tokio::test]
async fn test_site_decommission_dead_peer_recovers_pending_remove_and_bucket_delete() -> Result<(), Box<dyn Error + Send + Sync>>
{
init_logging();
let mut source = RustFSTestEnvironment::new().await?;
let mut target = RustFSTestEnvironment::new().await?;
let mut env = replication_fast_env();
env.extend_from_slice(FAST_SCANNER_ENV);
env.extend_from_slice(LOOPBACK_REPLICATION_TARGET_ENV);
source.start_rustfs_server_with_env(vec![], &env).await?;
target.start_rustfs_server_without_cleanup_with_env(&env).await?;
let added = site_replication_add(
&source,
&[
PeerSite {
name: "survivor".to_string(),
endpoint: source.url.clone(),
access_key: source.access_key.clone(),
secret_key: source.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "retired".to_string(),
endpoint: target.url.clone(),
access_key: target.access_key.clone(),
secret_key: target.secret_key.clone(),
..Default::default()
},
],
)
.await?;
assert!(added.success, "{added:?}");
let source_client = source.create_s3_client();
let target_client = target.create_s3_client();
let bucket = "decommission-pending-delete";
source_client.create_bucket().bucket(bucket).send().await?;
wait_for_bucket_on_target(&target_client, bucket).await?;
let version = source_client
.put_object()
.bucket(bucket)
.key("data")
.body(ByteStream::from_static(b"decommission data survives until purge"))
.send()
.await?
.version_id
.ok_or("site bucket must be versioned")?;
wait_for_object_on_target(&target_client, bucket, "data").await?;
target.stop_server();
source_client
.delete_object()
.bucket(bucket)
.key("data")
.version_id(&version)
.send()
.await?;
let blocked = source_client
.delete_bucket()
.bucket(bucket)
.send()
.await
.expect_err("pending version must block delete");
assert_eq!(blocked.code(), Some("BucketNotEmpty"));
let legacy = site_replication_remove(
&source,
&SRRemoveReq {
site_names: vec!["retired".to_string()],
..Default::default()
},
)
.await?;
assert_eq!(legacy.status, "Partial");
assert!(site_replication_info(&source).await?.pending_operation.is_some());
let mut request = rustfs_madmin::SRRemoveV2Req {
mode: "dry-run".to_string(),
sites: vec!["retired".to_string()],
..Default::default()
};
let preview = decommission_site_v2(&source, &request).await?;
assert_eq!(preview.status, "planned");
request.mode = "execute".to_string();
request.operation_id = Some(preview.operation_id.clone());
request.preflight_token = Some(preview.preflight_token);
let removed = decommission_site_v2(&source, &request).await?;
assert_eq!(removed.status, "success", "{removed:?}");
assert_site_replication_bucket_detached(&source, bucket).await?;
assert!(site_replication_info(&source).await?.pending_operation.is_none());
source.restart_server_preserving_data(vec![], &env).await?;
let replay = decommission_site_v2(&source, &request).await?;
assert_eq!(replay.status, "success");
assert_eq!(replay.operation_id, removed.operation_id);
let deadline = tokio::time::Instant::now() + Duration::from_secs(120);
loop {
match source_client.delete_bucket().bucket(bucket).send().await {
Ok(_) => break,
Err(err) if err.code() == Some("BucketNotEmpty") && tokio::time::Instant::now() < deadline => {
tokio::time::sleep(Duration::from_millis(250)).await;
}
Err(err) => return Err(err.into()),
}
}
assert!(source_client.head_bucket().bucket(bucket).send().await.is_err());
Ok(())
}
#[tokio::test]
async fn test_site_decommission_preserves_two_live_sites_and_bidirectional_replication()
-> Result<(), Box<dyn Error + Send + Sync>> {
init_logging();
let mut a = RustFSTestEnvironment::new().await?;
let mut b = RustFSTestEnvironment::new().await?;
let mut c = RustFSTestEnvironment::new().await?;
let mut env = replication_fast_env();
env.extend_from_slice(FAST_SCANNER_ENV);
env.extend_from_slice(LOOPBACK_REPLICATION_TARGET_ENV);
a.start_rustfs_server_with_env(vec![], &env).await?;
b.start_rustfs_server_without_cleanup_with_env(&env).await?;
c.start_rustfs_server_without_cleanup_with_env(&env).await?;
let mut proxy_tasks = JoinSet::new();
let (c_proxy, _, allow_peer_removal, _, _) = start_replication_counting_proxy_with_tag_hold(
&c.url,
&mut proxy_tasks,
Some("/minio/admin/v3/site-replication/peer/remove-v2"),
)
.await?;
let added = site_replication_add(
&a,
&[
PeerSite {
name: "a".to_string(),
endpoint: a.url.clone(),
access_key: a.access_key.clone(),
secret_key: a.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "b".to_string(),
endpoint: b.url.clone(),
access_key: b.access_key.clone(),
secret_key: b.secret_key.clone(),
..Default::default()
},
PeerSite {
name: "c".to_string(),
endpoint: c.url.clone(),
access_key: c.access_key.clone(),
secret_key: c.secret_key.clone(),
..Default::default()
},
],
)
.await?;
assert!(added.success, "{added:?}");
let info = wait_for_site_replication_enabled(&a, 3).await?;
let retired_id = info
.sites
.iter()
.find(|peer| peer.name == "b")
.ok_or("site b is missing")?
.deployment_id
.clone();
let mut survivor = info
.sites
.into_iter()
.find(|peer| peer.name == "c")
.ok_or("site c is missing")?;
let survivor_id = survivor.deployment_id.clone();
survivor.endpoint = c_proxy;
let edited = site_replication_edit(&a, "", &survivor).await?;
assert!(edited.success, "{edited:?}");
let ca = a.create_s3_client();
let cb = b.create_s3_client();
let cc = c.create_s3_client();
let bucket = "decommission-preserve-live-peers";
let operator_bucket = "decommission-operator-target";
cc.create_bucket().bucket(operator_bucket).send().await?;
enable_bucket_versioning(&c, operator_bucket).await?;
ca.create_bucket().bucket(bucket).send().await?;
wait_for_bucket_on_target(&cb, bucket).await?;
wait_for_bucket_on_target(&cc, bucket).await?;
let operator_arn = set_replication_target(&a, bucket, &c, operator_bucket).await?;
put_bucket_replication(&a, bucket, &operator_arn).await?;
ca.put_object()
.bucket(bucket)
.key("baseline")
.body(ByteStream::from_static(b"baseline"))
.send()
.await?;
wait_for_object_on_target(&cc, bucket, "baseline").await?;
wait_for_object_on_target(&cc, operator_bucket, "baseline").await?;
let retired_rule_id = format!("site-repl-{retired_id}");
let retired_arn = ca
.get_bucket_replication()
.bucket(bucket)
.send()
.await?
.replication_configuration
.ok_or("source bucket replication is missing")?
.rules
.into_iter()
.find(|rule| rule.id.as_deref() == Some(retired_rule_id.as_str()))
.and_then(|rule| rule.destination)
.ok_or("site b replication rule is missing")?
.bucket;
b.stop_server();
let preview_request = rustfs_madmin::SRRemoveV2Req {
mode: "dry-run".to_string(),
sites: vec!["b".to_string()],
..Default::default()
};
let preview = decommission_site_v2(&a, &preview_request).await?;
let request = rustfs_madmin::SRRemoveV2Req {
mode: "execute".to_string(),
operation_id: Some(preview.operation_id.clone()),
preflight_token: Some(preview.preflight_token),
..preview_request.clone()
};
allow_peer_removal.send(false)?;
let partial = decommission_site_v2(&a, &request).await?;
assert_eq!(partial.status, "Partial", "{partial:?}");
assert!(partial.local_cleanup_complete, "{partial:?}");
assert_eq!(partial.pending_peers, [survivor_id]);
assert!(partial.errors.iter().any(|error| error.contains("admin commit blocked")), "{partial:?}");
let prepared = site_replication_info(&c)
.await?
.pending_operation
.ok_or("site c must have prepared")?;
assert_eq!(prepared.id, preview.operation_id);
a.restart_server_preserving_data(vec![], &env).await?;
let restored = decommission_site_v2(&a, &preview_request).await?;
assert_eq!(restored.operation_id, preview.operation_id);
assert_eq!(restored.status, "Partial", "{restored:?}");
assert!(restored.local_cleanup_complete, "{restored:?}");
assert_eq!(restored.pending_peers, partial.pending_peers);
allow_peer_removal.send(true)?;
let result = decommission_site_v2(&a, &request).await?;
assert_eq!(result.status, "success", "{result:?}");
let ia = site_replication_info(&a).await?;
let ic = site_replication_info(&c).await?;
assert!(ia.enabled && ic.enabled);
assert!(ia.pending_operation.is_none() && ic.pending_operation.is_none());
assert_eq!(
ia.sites
.iter()
.map(|peer| peer.deployment_id.clone())
.collect::<std::collections::BTreeSet<_>>(),
ic.sites.iter().map(|peer| peer.deployment_id.clone()).collect()
);
assert!(!ia.sites.iter().any(|peer| peer.name == "b"));
let targets: Vec<serde_json::Value> = list_replication_targets_request(&a, Some(bucket))
.await?
.error_for_status()?
.json()
.await?;
assert!(
targets
.iter()
.any(|target| target["arn"] == operator_arn && target["targetbucket"] == operator_bucket),
"operator target {operator_arn} must survive decommission"
);
assert!(
!targets.iter().any(|target| target["arn"] == retired_arn),
"retired site target {retired_arn} must be removed"
);
ca.put_object()
.bucket(bucket)
.key("a-to-c")
.body(ByteStream::from_static(b"a to c survives"))
.send()
.await?;
assert_eq!(wait_for_object_on_target(&cc, bucket, "a-to-c").await?, b"a to c survives");
assert_eq!(wait_for_object_on_target(&cc, operator_bucket, "a-to-c").await?, b"a to c survives");
cc.put_object()
.bucket(bucket)
.key("c-to-a")
.body(ByteStream::from_static(b"c to a survives"))
.send()
.await?;
assert_eq!(wait_for_object_on_target(&ca, bucket, "c-to-a").await?, b"c to a survives");
c.restart_server_preserving_data(vec![], &env).await?;
assert!(site_replication_info(&c).await?.pending_operation.is_none());
assert_eq!(decommission_site_v2(&a, &request).await?.status, "success");
Ok(())
}
async fn site_replication_state_edit(
env: &RustFSTestEnvironment,
body: &rustfs_madmin::SRStateEditReq,
@@ -8543,7 +8222,7 @@ async fn test_site_replication_tagging_during_initial_pending_window_converges()
_site_b_replication_enabled,
_site_b_held_tagging,
mut site_b_response_hold,
) = start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
) = start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks).await?;
let add_status = site_replication_add(
&site_a_env,
@@ -8800,9 +8479,9 @@ async fn test_site_replication_tagging_lww_converges_active_active_real_dual_nod
let mut proxy_tasks = JoinSet::new();
let (site_a_proxy, site_a_replication_requests, _site_a_replication_enabled, site_a_held_tagging, _site_a_response_hold) =
start_replication_counting_proxy_with_tag_hold(&site_a_env.url, &mut proxy_tasks, None).await?;
start_replication_counting_proxy_with_tag_hold(&site_a_env.url, &mut proxy_tasks).await?;
let (site_b_proxy, site_b_replication_requests, _site_b_replication_enabled, site_b_held_tagging, _site_b_response_hold) =
start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks).await?;
let site_a_client = site_a_env.create_s3_client();
let site_b_client = site_b_env.create_s3_client();
@@ -1,208 +0,0 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use std::collections::BTreeMap;
use std::path::Path;
use std::time::{Duration, SystemTime};
use aws_sdk_s3::{Client, primitives::ByteStream};
use futures::{StreamExt, TryStreamExt, stream};
use rustfs_data_usage::{BucketUsageValueState, DataUsageInfo};
use serde::{Deserialize, de::DeserializeOwned};
use tokio::time::{Instant, sleep, timeout};
use crate::common::{RustFSTestEnvironment, signed_request};
use crate::storage_api::scanner_peer_bucket::{BUCKET_META_PREFIX, RUSTFS_META_BUCKET};
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
const BUCKET: &str = "wide-directory-usage";
const WIDTH: usize = 512;
// The per-disk token bucket allows an initial burst of one second. Even the
// first pass can read at most (1 + 3) * 96 = 384 of these 512 root entries.
const SCAN_ENV: &[(&str, &str)] = &[
("RUST_LOG", "warn,rustfs::scanner::io=debug,rustfs::scanner::data_usage=debug"),
("RUSTFS_SCANNER_ENABLED", "true"),
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
("RUSTFS_SCANNER_CYCLE", "1"),
("RUSTFS_SCANNER_CYCLE_MAX_DURATION_SECS", "3"),
("RUSTFS_SCANNER_SPEED", "fastest"),
("RUSTFS_SCANNER_DISK_IO_BUDGET_IOPS", "96"),
("RUSTFS_SCANNER_DISK_IO_BUDGET_BYTES_PER_SEC", "off"),
];
#[derive(Debug, Deserialize)]
struct Status {
metrics: Metrics,
disk_io_budget: Vec<DiskBudget>,
}
#[derive(Debug, Deserialize)]
struct Metrics {
current_cycle_active: bool,
active_paths: Vec<String>,
cycle_max_duration_seconds: f64,
partial_cycles_runtime: u64,
}
#[derive(Debug, Deserialize)]
struct DiskBudget {
iops: Option<u64>,
}
async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str) -> TestResult<T> {
let url = format!("{}/rustfs/admin/v3/{resource}", env.url);
let response = signed_request(http::Method::GET, &url, &env.access_key, &env.secret_key, None, None).await?;
Ok(response.error_for_status()?.json().await?)
}
async fn inventory(client: &Client) -> TestResult<BTreeMap<String, u64>> {
let mut pages = client.list_objects_v2().bucket(BUCKET).max_keys(37).into_paginator().send();
let mut sizes = BTreeMap::new();
while let Some(page) = pages.next().await {
for object in page?.contents() {
let key = object.key().ok_or("S3 inventory omitted object key")?;
let size = u64::try_from(object.size().ok_or("S3 inventory omitted object size")?)?;
assert!(sizes.insert(key.to_owned(), size).is_none(), "duplicate inventory key {key}");
}
}
Ok(sizes)
}
async fn scan_status(env: &RustFSTestEnvironment) -> TestResult<Status> {
let status: Status = admin(env, "scanner/status").await?;
assert_eq!(status.metrics.cycle_max_duration_seconds, 3.0, "effective cycle budget");
assert!(status.disk_io_budget.iter().all(|disk| disk.iops == Some(96)), "effective disk budget");
Ok(status)
}
#[tokio::test(flavor = "multi_thread")]
async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult {
let mut env = RustFSTestEnvironment::new().await?;
let temporary_log = tempfile::NamedTempFile::new()?;
let server_log = env
.capture_log_path
.get_or_insert_with(|| temporary_log.path().display().to_string())
.clone();
let bucket_metadata = Path::new(&env.temp_dir)
.join(RUSTFS_META_BUCKET)
.join(BUCKET_META_PREFIX)
.join(BUCKET);
// Seed a cold bucket without allowing any earlier, larger-budget sweep to count it.
env.start_rustfs_server_without_cleanup_with_env(&[("RUSTFS_SCANNER_ENABLED", "false")])
.await?;
let client = env.create_s3_client();
client.create_bucket().bucket(BUCKET).send().await?;
stream::iter(0..WIDTH)
.map(Ok)
.try_for_each_concurrent(12, |i| {
let client = &client;
async move {
client
.put_object()
.bucket(BUCKET)
.key(format!("object-{i:064x}"))
.body(ByteStream::from(vec![42; 1 + i % 67]))
.send()
.await
.map(|_| ())
}
})
.await?;
let expected = inventory(&client).await?;
assert_eq!(expected.len(), WIDTH);
env.restart_server_preserving_data(vec![], SCAN_ENV).await?;
let first_pid = env.process.as_ref().ok_or("missing scanner process")?.id();
timeout(Duration::from_secs(60), async {
loop {
let status = scan_status(&env).await?;
if status.metrics.partial_cycles_runtime >= 1
&& bucket_metadata.join(".usage-cache.bin").join("xl.meta").is_file()
&& bucket_metadata.join(".usage-cache.bin.pages").is_dir()
&& status.metrics.current_cycle_active
&& status
.metrics
.active_paths
.iter()
.any(|path| path.split('/').any(|part| part == BUCKET))
{
let log = tokio::fs::read_to_string(&server_log).await?;
if !log
.lines()
.any(|line| line.contains("partial_saved_not_published") && line.contains(BUCKET))
{
sleep(Duration::from_millis(200)).await;
continue;
}
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
}
sleep(Duration::from_millis(200)).await;
}
})
.await
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
assert!(
partial
.buckets_usage
.get(BUCKET)
.is_none_or(|value| value.usage_certification.is_none()),
"the first process certified the bucket before the injected crash"
);
env.stop_server();
// The terminal save has returned and the old process can no longer write.
assert!(
bucket_metadata.join(".usage-cache.bin").join("xl.meta").is_file()
&& bucket_metadata.join(".usage-cache.bin.pages").is_dir(),
"the interrupted process must have committed a paged checkpoint"
);
let restart_log_offset = usize::try_from(tokio::fs::metadata(&server_log).await?.len())?;
let restarted_at = SystemTime::now();
env.start_rustfs_server_without_cleanup_with_env(SCAN_ENV).await?;
let second_pid = env.process.as_ref().ok_or("missing restarted scanner process")?.id();
assert_ne!(first_pid, second_pid);
let deadline = Instant::now() + Duration::from_secs(180);
loop {
let usage: DataUsageInfo = admin(&env, "datausageinfo").await?;
let status = scan_status(&env).await?;
if let Some(bucket) = usage.buckets_usage.get(BUCKET)
&& bucket.usage_value_state == Some(BucketUsageValueState::Certified)
{
let log = tokio::fs::read_to_string(&server_log).await?;
let first_admission = log
.get(restart_log_offset..)
.ok_or("server log truncated across restart")?
.lines()
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
.find(|record| record["state"] == "bucket_checkpoint_prepared" && record["bucket"] == BUCKET)
.ok_or("no checkpoint admission in the restarted process")?;
assert_eq!(first_admission["resume_position"], true, "restarted scanner discarded the checkpoint");
assert!(usage.is_complete_bucket_usage_snapshot());
let certificate = bucket
.usage_certification
.ok_or("missing certificate for the measured bucket")?;
assert!(certificate.certified_at >= restarted_at, "stale pre-restart certificate");
assert!(status.metrics.partial_cycles_runtime > 0, "new process must cross a cycle deadline");
assert!(!status.disk_io_budget.is_empty(), "restarted scanner never admitted disk I/O");
assert_eq!(inventory(&client).await?, expected, "durable S3 inventory changed across restart");
let count = u64::try_from(expected.len())?;
let bytes = expected.values().sum::<u64>();
assert_eq!((bucket.objects_count, bucket.size), (count, bytes));
assert_eq!((usage.objects_total_count, usage.objects_total_size), (count, bytes));
eprintln!(
"PIDs {first_pid}/{second_pid}, runtime-limited cycles since restart {}, certificate epoch {} cycle {}, S3 and admin {} objects/{} bytes",
status.metrics.partial_cycles_runtime, certificate.epoch, certificate.cycle, count, bytes
);
return Ok(());
}
assert!(
Instant::now() < deadline,
"no certified bucket after restart: {status:?}, value={:?}",
usage.buckets_usage.get(BUCKET)
);
sleep(Duration::from_millis(500)).await;
}
}
@@ -1758,129 +1758,6 @@ mod upgrade_write_readiness_tests {
}
}
async fn stop_scanner_handoff_server(env: &mut RustFSTestEnvironment) -> TestResult {
let process = env.process.as_mut().ok_or("handoff server is not running")?;
signal_process(process.id(), "TERM")?;
tokio::time::timeout(Duration::from_secs(90), async {
loop {
if let Some(status) = process.try_wait()? {
assert!(status.success(), "handoff shutdown failed: {status}");
return Ok::<(), BoxError>(());
}
sleep(Duration::from_millis(50)).await;
}
})
.await??;
env.process.take();
Ok(())
}
fn scanner_handoff_identity(env: &RustFSTestEnvironment) -> Result<String, BoxError> {
let receipt: Value = serde_json::from_slice(&std::fs::read(Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown"))?)?;
assert_eq!(receipt["schema"], 1);
assert_eq!(receipt["owner"], env.address);
Ok(receipt["checkpoint_instance_id"]
.as_str()
.ok_or("handoff receipt omitted checkpoint identity")?
.to_owned())
}
async fn assert_scanner_handoff_consumed(marker: &Path) -> TestResult {
let marker = tokio::fs::read_to_string(marker).await?;
// Heal may replace the startup marker with its ordinary timestamp before
// readiness. Neither form carries the prior checkpoint identity.
assert!(
marker == "running" || marker.parse::<u64>().is_ok(),
"readiness must expose an ordinary unclean marker, never a handoff receipt"
);
Ok(())
}
#[tokio::test]
async fn scanner_read_only_handoff_requires_explicit_opt_in() -> TestResult {
const HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
assert!(std::env::var_os(HANDOFF).is_none(), "this scenario tests the unset default");
let mut env = RustFSTestEnvironment::new().await?;
let marker = Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown");
env.start_rustfs_server_without_cleanup(vec![]).await?;
stop_scanner_handoff_server(&mut env).await?;
assert!(!marker.exists(), "the default must not create a receipt");
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
stop_scanner_handoff_server(&mut env).await?;
let previous = scanner_handoff_identity(&env)?;
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
assert_scanner_handoff_consumed(&marker).await?;
stop_scanner_handoff_server(&mut env).await?;
assert_eq!(scanner_handoff_identity(&env)?, previous, "opted-in read-only boots retain identity");
for disabled in ["invalid", "false"] {
let before_disabled = scanner_handoff_identity(&env)?;
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, disabled)])
.await?;
assert_scanner_handoff_consumed(&marker).await?;
stop_scanner_handoff_server(&mut env).await?;
assert!(!marker.exists(), "disabled shutdown must not recreate the receipt");
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
stop_scanner_handoff_server(&mut env).await?;
assert_ne!(scanner_handoff_identity(&env)?, before_disabled, "opt-out breaks the prior lineage");
}
Ok(())
}
// Exercise the receipt protocol in the existing pinned-release rollback lane.
async fn assert_scanner_handoff_prepares_legacy_rollback(previous_binary: &Path) -> TestResult {
const HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
let mut env = RustFSTestEnvironment::new().await?;
let marker = Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown");
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
stop_scanner_handoff_server(&mut env).await?;
let previous = scanner_handoff_identity(&env)?;
// Complete the current reader's rollback preparation before any old writer
// opens storage, including an old writer with all background services off.
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "false")])
.await?;
assert_scanner_handoff_consumed(&marker).await?;
stop_scanner_handoff_server(&mut env).await?;
assert!(!marker.exists());
env.start_rustfs_server_from_binary_without_cleanup(
previous_binary,
vec![],
&[
("RUSTFS_SCANNER_ENABLED", "false"),
("RUSTFS_HEAL_ENABLED", "false"),
("RUSTFS_HEAL_AUTO_HEAL_ENABLE", "false"),
("RUSTFS_HEAL_MRF_ENABLE", "false"),
],
)
.await?;
let client = env.create_s3_client();
env.create_test_bucket("handoff-rollback").await?;
client
.put_object()
.bucket("handoff-rollback")
.key("legacy-write")
.body(ByteStream::from_static(b"legacy writer survived rollback preparation"))
.send()
.await?;
env.stop_server();
assert!(!marker.exists(), "the legacy crash cannot resurrect a consumed receipt");
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
assert_eq!(
read_object(&client, "handoff-rollback", "legacy-write", None).await?.1,
b"legacy writer survived rollback preparation"
);
stop_scanner_handoff_server(&mut env).await?;
assert_ne!(
scanner_handoff_identity(&env)?,
previous,
"a legacy write must not retain the old lineage"
);
Ok(())
}
/// Pins the published old writer's limitation and the supported recovery
/// procedure. This is not a promise that mixed-version ODM is supported.
/// Replace the loss assertion when ODM gains independent persistence;
@@ -3585,7 +3462,6 @@ async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestRes
init_logging();
let previous_binary = source_binary()?;
let evidence_context = g09_evidence_context(&previous_binary).await?;
assert_scanner_handoff_prepares_legacy_rollback(&previous_binary).await?;
let replication_target = FakeS3Target::start().await?;
replication_target.create_bucket(ROLLBACK_REPLICA_BUCKET);
+1
View File
@@ -183,6 +183,7 @@ rmp.workspace = true
rmp-serde.workspace = true
tokio-util = { workspace = true, features = ["io", "compat", "rt"] }
tokio-stream = { workspace = true, features = ["sync"] }
hmac = { workspace = true }
sha2 = { workspace = true }
hex-simd = { workspace = true }
tempfile.workspace = true
+12 -14
View File
@@ -28,7 +28,7 @@ pub mod diagnostic {
}
pub mod admin {
pub use crate::diagnostics::admin_server_info::{get_local_server_property, get_server_info, get_server_info_with_inventory};
pub use crate::diagnostics::admin_server_info::{get_local_server_property, get_server_info};
}
pub mod bitrot {
@@ -72,11 +72,10 @@ pub mod bucket {
ExpiryState, LifecycleOps, ManualTransitionCancelCheck, ManualTransitionProgressSink,
ManualTransitionQueueSnapshot, ManualTransitionRunExecution, ManualTransitionRunOptions,
ManualTransitionRunReport, RestoreRequestOps, TransitionState, TransitionedObject, apply_expiry_rule,
apply_transition_rule, apply_transition_rule_with_incarnation, enqueue_expiry_for_existing_objects,
enqueue_transition_for_existing_objects, enqueue_transition_for_existing_objects_scoped,
enqueue_transition_for_existing_objects_scoped_with_cancel, enqueue_transition_immediate,
expire_transitioned_object, get_global_expiry_state, get_global_transition_state, init_background_expiry,
lifecycle_version_delete_target, manual_transition_queue_snapshot, post_restore_opts,
apply_transition_rule, enqueue_expiry_for_existing_objects, enqueue_transition_for_existing_objects,
enqueue_transition_for_existing_objects_scoped, enqueue_transition_for_existing_objects_scoped_with_cancel,
enqueue_transition_immediate, expire_transitioned_object, get_global_expiry_state, get_global_transition_state,
init_background_expiry, lifecycle_version_delete_target, manual_transition_queue_snapshot, post_restore_opts,
run_stale_multipart_upload_cleanup_once, validate_transition_tier,
};
}
@@ -349,7 +348,7 @@ pub mod bucket {
pub mod utils {
pub use crate::bucket::utils::{
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args, check_object_args,
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args,
check_object_name_for_length_and_slash, check_valid_bucket_name_strict, deserialize, has_bad_path_component,
has_xml_invalid_control_characters, is_meta_bucketname, is_valid_object_prefix, serialize,
};
@@ -455,13 +454,13 @@ pub mod data_usage {
DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage,
init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache,
invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached,
load_admin_data_usage_with_memory_overlay, load_bucket_usage_from_backend_cached, load_compression_total_from_memory,
load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
load_bucket_usage_from_backend_cached, load_compression_total_from_memory, load_data_usage_from_backend,
load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
store_data_usage_in_backend, verified_account_bucket_usage,
store_data_usage_in_backend,
};
pub use crate::data_usage::{get_bucket_usage_memory, lookup_degraded_bucket_usage_baseline};
}
@@ -470,7 +469,6 @@ pub mod disk {
pub use crate::cluster::rpc::background_pipe::{BackgroundPipeReader, BackgroundPipeWriter, background_pipe};
pub use crate::cluster::rpc::background_reader_stream::BackgroundReaderStream;
pub use crate::disk::BOUNDED_DELETE_PREPARE_PROTOCOL_VERSION;
pub use crate::disk::ReplacementMount;
pub use crate::disk::background_memory::BackgroundEncodeBuffer;
pub use crate::disk::disk_store::get_object_disk_read_timeout;
#[cfg(feature = "test-util")]
@@ -505,7 +503,7 @@ pub mod disk {
PoolMetaNativeInspection, PoolMetaNativeObject, PoolMetaNativeRecoveryRequest, PoolMetaNativeRecoveryResponse,
QUOTA_MUTATION_FENCE_METADATA_SUFFIX, RUSTFS_META_BUCKET, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET,
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp, STORAGE_FORMAT_FILE, SnapshotLeaseToken,
UNCLEAN_SHUTDOWN_MARKER_PATH, UpdateMetadataOpts, VolumeInfo, WalkDirOptions, is_quota_mutation_fence_path, new_disk,
UpdateMetadataOpts, VolumeInfo, WalkDirOptions, is_quota_mutation_fence_path, new_disk,
validate_batch_read_version_item_count, validate_format_control_path,
};
pub use crate::disk::{
@@ -771,8 +769,8 @@ pub mod storage {
pub use crate::store::external_rpc_disk;
pub use crate::store::{
BootstrapLocalTarget, ECStore, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, all_local_disk,
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc,
init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, init_local_disks,
init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
prewarm_local_disk_id_map_with_instance_ctx,
};
pub use crate::store::{HealObjectAbsenceProof, HealObjectStorageResult};
@@ -5082,14 +5082,7 @@ mod tests {
let cert = generate_simple_self_signed(vec!["localhost".to_string()]).expect("certificate should generate");
let (port, server) = spawn_https_server(&cert, 2);
let endpoint = format!("https://localhost:{port}");
let strict_client = s3_client_for_test(port, None);
// A failed trust check must consume just one of the two fixture connections.
let strict_config = strict_client
.config()
.to_builder()
.retry_config(aws_sdk_s3::config::retry::RetryConfig::disabled())
.build();
let strict = target_client_for_test("arn:strict", endpoint.clone(), S3Client::from_conf(strict_config));
let strict = target_client_for_test("arn:strict", endpoint.clone(), s3_client_for_test(port, None));
let insecure = target_client_for_test(
"arn:insecure",
endpoint,
@@ -51,20 +51,15 @@ impl LcAuditEvent {
}
}
pub(crate) fn emit_transition_failed_event(object: ObjectInfo, incarnation_id: Option<uuid::Uuid>) {
emit_lifecycle_event(EventName::ObjectTransitionFailed, object, LIFECYCLE_TRANSITION_USER_AGENT, incarnation_id);
pub(crate) fn emit_transition_failed_event(object: ObjectInfo) {
emit_lifecycle_event(EventName::ObjectTransitionFailed, object, LIFECYCLE_TRANSITION_USER_AGENT);
}
pub(crate) fn emit_transition_complete_event(object: ObjectInfo, incarnation_id: Option<uuid::Uuid>) {
emit_lifecycle_event(
EventName::ObjectTransitionComplete,
object,
LIFECYCLE_TRANSITION_USER_AGENT,
incarnation_id,
);
pub(crate) fn emit_transition_complete_event(object: ObjectInfo) {
emit_lifecycle_event(EventName::ObjectTransitionComplete, object, LIFECYCLE_TRANSITION_USER_AGENT);
}
pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo, incarnation_id: uuid::Uuid) {
pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo) {
let event_name = transitioned_expiration_event_name(source.delete_marker, deleted.delete_marker);
let object = ObjectInfo {
bucket: source.bucket.clone(),
@@ -74,17 +69,12 @@ pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &
delete_marker: source.delete_marker,
..Default::default()
};
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT);
}
pub(crate) fn emit_non_transitioned_expiration_event(
action: IlmAction,
source: &ObjectInfo,
deleted: ObjectInfo,
incarnation_id: uuid::Uuid,
) {
pub(crate) fn emit_non_transitioned_expiration_event(action: IlmAction, source: &ObjectInfo, deleted: ObjectInfo) {
let event_name = non_transitioned_expiration_event_name(action, source.delete_marker, deleted.delete_marker);
emit_lifecycle_event(event_name, deleted, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
emit_lifecycle_event(event_name, deleted, LIFECYCLE_EXPIRY_USER_AGENT);
}
/// Emit the lifecycle expiration event for one version removed by the batch
@@ -93,15 +83,9 @@ pub(crate) fn emit_non_transitioned_expiration_event(
/// That path never sent events, so a successful noncurrent-version expiry was
/// invisible to notification subscribers even though the equivalent
/// current-version path emits one (backlog#2202).
pub(crate) fn emit_noncurrent_expiration_event(
bucket: &str,
target: &ObjectToDelete,
deleted: &DeletedObject,
failed: bool,
incarnation_id: uuid::Uuid,
) {
pub(crate) fn emit_noncurrent_expiration_event(bucket: &str, target: &ObjectToDelete, deleted: &DeletedObject, failed: bool) {
if let Some((event_name, object)) = noncurrent_expiration_event(bucket, target, deleted, failed) {
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT);
}
}
@@ -147,10 +131,9 @@ fn noncurrent_expiration_event(
Some((event_name, object))
}
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str, incarnation_id: Option<uuid::Uuid>) {
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str) {
send_event(EventArgs {
event_name: event_name.to_string(),
bucket_incarnation_id: incarnation_id,
bucket_name: object.bucket.clone(),
object,
user_agent: user_agent.to_string(),
@@ -117,9 +117,9 @@ use tracing::{debug, error, warn};
use uuid::Uuid;
use xxhash_rust::xxh64;
pub(super) const LOG_COMPONENT_ECSTORE: &str = "ecstore";
pub(super) const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
pub(super) const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
const EVENT_LIFECYCLE_TRANSITION_COMPENSATION: &str = "lifecycle_transition_compensation";
const EVENT_LIFECYCLE_STALE_MULTIPART_CLEANUP: &str = "lifecycle_stale_multipart_cleanup";
const METRIC_STALE_MULTIPART_CLEANUP_BLOCKED_TOTAL: &str = "rustfs_stale_multipart_cleanup_blocked_total";
@@ -1566,12 +1566,7 @@ pub(super) async fn enqueue_recovered_free_version_with_cancel(
queued
}
type TransitionKey = (Option<Uuid>, String, String, String);
struct TransitionTask {
// Captured with the source object; recovery without this provenance must
// never bind notification authority from the bucket name at execution.
notification_bucket_incarnation: Option<Uuid>,
obj_info: ObjectInfo,
src: LcEventSrc,
event: lifecycle::Event,
@@ -1611,12 +1606,12 @@ pub struct TransitionState {
compensation_scheduled_tasks: AtomicI64,
compensation_running_tasks: AtomicI64,
compensation_buckets: Arc<Mutex<HashSet<String>>>,
// (incarnation, bucket, object, version) currently queued or being transitioned. A single
// (bucket, object, version) currently queued or being transitioned. A single
// PUT can enqueue the same object twice (immediate transition + startup
// compensation backfill); without this guard the duplicates run concurrently,
// and the loser races the winner's source cleanup — reading data the winner
// already removed and logging a spurious NotFound failure (rustfs/backlog#1268).
in_flight_transitions: Arc<Mutex<HashSet<TransitionKey>>>,
in_flight_transitions: Arc<Mutex<HashSet<(String, String, String)>>>,
last_day_stats: Arc<Mutex<HashMap<String, LastDayTierStats>>>,
}
@@ -1682,29 +1677,28 @@ impl TransitionState {
})
}
fn transition_key(oi: &ObjectInfo, incarnation: Option<Uuid>) -> TransitionKey {
fn transition_key(oi: &ObjectInfo) -> (String, String, String) {
(
incarnation,
oi.bucket.clone(),
oi.name.clone(),
oi.version_id.map(|v| v.to_string()).unwrap_or_default(),
)
}
/// Try to claim a transition for this exact (incarnation, bucket, object, version). Returns
/// Try to claim a transition for this exact (bucket, object, version). Returns
/// `false` when one is already queued or running, so the caller can skip the
/// duplicate enqueue (rustfs/backlog#1268). The claim is released in the
/// worker once the transition finishes, or here if the enqueue fails.
fn reserve_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) -> bool {
let key = Self::transition_key(oi, incarnation);
fn reserve_transition(&self, oi: &ObjectInfo) -> bool {
let key = Self::transition_key(oi);
match self.in_flight_transitions.lock() {
Ok(mut set) => set.insert(key),
Err(poisoned) => poisoned.into_inner().insert(key),
}
}
fn release_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) {
let key = Self::transition_key(oi, incarnation);
fn release_transition(&self, oi: &ObjectInfo) {
let key = Self::transition_key(oi);
match self.in_flight_transitions.lock() {
Ok(mut set) => set.remove(&key),
Err(poisoned) => poisoned.into_inner().remove(&key),
@@ -1908,7 +1902,6 @@ impl TransitionState {
event: &lifecycle::Event,
src: &LcEventSrc,
manual_job_id: Option<Uuid>,
notification_bucket_incarnation: Option<Uuid>,
) -> TransitionEnqueueOutcome {
if is_immediate_transition_source(src) && should_force_immediate_transition_enqueue_timeout() {
self.handle_immediate_enqueue_failure(oi, src, ImmediateEnqueueFailure::ForcedTimeout);
@@ -1921,7 +1914,7 @@ impl TransitionState {
// released by the worker after the transition finishes (rustfs/backlog#1268).
// This is a no-op, not a new enqueue, so it must not touch the enqueue
// counters (the first enqueue already counted this object).
if !self.reserve_transition(oi, notification_bucket_incarnation) {
if !self.reserve_transition(oi) {
self.record_scanner_transition_state();
return TransitionEnqueueOutcome::AlreadyInFlight;
}
@@ -1930,7 +1923,7 @@ impl TransitionState {
manual_job_id.map(|_| manual_transition_worker_result_task_key(&oi.bucket, &oi.name, oi.version_id));
if let (Some(job_id), Some(result_key)) = (manual_job_id, manual_result_key.as_deref()) {
let Some(api) = api else {
self.release_transition(oi, notification_bucket_incarnation);
self.release_transition(oi);
warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
@@ -1955,7 +1948,7 @@ impl TransitionState {
)
.with_object_metadata(oi.etag.clone(), oi.mod_time, oi.size, oi.is_latest);
if let Err(err) = save_manual_transition_task_if_absent(api, &task_record).await {
self.release_transition(oi, notification_bucket_incarnation);
self.release_transition(oi);
warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
@@ -1974,7 +1967,6 @@ impl TransitionState {
}
let task = TransitionTask {
notification_bucket_incarnation,
obj_info: oi.clone(),
src: src.clone(),
event: event.clone(),
@@ -2018,7 +2010,7 @@ impl TransitionState {
};
let queued = outcome == TransitionEnqueueOutcome::Queued;
if !queued {
self.release_transition(oi, notification_bucket_incarnation);
self.release_transition(oi);
}
record_scanner_transition_enqueue_result(src, 1, queued);
self.record_scanner_transition_state();
@@ -2071,7 +2063,7 @@ impl TransitionState {
};
let queued = outcome == TransitionEnqueueOutcome::Queued;
if !queued {
self.release_transition(oi, notification_bucket_incarnation);
self.release_transition(oi);
}
record_scanner_transition_enqueue_result(src, 1, queued);
self.record_scanner_transition_state();
@@ -2079,7 +2071,7 @@ impl TransitionState {
}
pub async fn queue_transition_task(self: &Arc<Self>, oi: &ObjectInfo, event: &lifecycle::Event, src: &LcEventSrc) -> bool {
self.queue_transition_task_outcome(None, oi, event, src, None, None)
self.queue_transition_task_outcome(None, oi, event, src, None)
.await
.is_handled()
}
@@ -2174,10 +2166,9 @@ impl TransitionState {
..Default::default()
};
let (incarnation_id, transition_result) =
transition_object(api.clone(), &task.obj_info, LcAuditEvent::new(task.event.clone(), task.src.clone()), task.notification_bucket_incarnation)
.await;
if let Err(err) = transition_result
if let Err(err) =
transition_object(api.clone(), &task.obj_info, LcAuditEvent::new(task.event.clone(), task.src.clone()))
.await
{
if let (Some(job_id), Some(result_key)) = (task.manual_job_id, task.manual_result_key.as_deref()) {
record_manual_transition_worker_result_for_task_with_reason(
@@ -2204,7 +2195,7 @@ impl TransitionState {
"Lifecycle tier operation failed"
);
}
emit_transition_failed_event(obj_info_for_event, incarnation_id);
emit_transition_failed_event(obj_info_for_event);
} else {
if let (Some(job_id), Some(result_key)) = (task.manual_job_id, task.manual_result_key.as_deref()) {
record_manual_transition_worker_result_for_task(
@@ -2226,11 +2217,11 @@ impl TransitionState {
}
transition_state.add_lastday_stats(&task.event.storage_class, ts);
emit_transition_complete_event(obj_info_for_event, incarnation_id);
emit_transition_complete_event(obj_info_for_event);
}
// Release the dedup claim so a later lifecycle pass can
// re-transition this object if needed (rustfs/backlog#1268).
transition_state.release_transition(&task.obj_info, task.notification_bucket_incarnation);
transition_state.release_transition(&task.obj_info);
TransitionState::add_counter(&transition_state.active_tasks, -1);
transition_state.record_scanner_transition_state();
}
@@ -2835,7 +2826,7 @@ async fn replay_manual_transition_pending_tasks(
};
match transition_state
.queue_transition_task_outcome(Some(api.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
.queue_transition_task_outcome(Some(api.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id))
.await
{
TransitionEnqueueOutcome::Queued | TransitionEnqueueOutcome::AlreadyInFlight => {
@@ -3093,7 +3084,6 @@ async fn recover_configured_tier_free_versions(
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
});
}
@@ -3233,7 +3223,6 @@ async fn run_tier_free_version_recovery_loop<F, Fut>(
scanned = stats.scanned,
scanned_entries = stats.scanned_entries,
buckets_scanned = stats.buckets_scanned,
unreadable_objects = stats.unreadable_objects,
enqueued = stats.enqueued,
failed = stats.failed,
truncated = stats.truncated,
@@ -4070,11 +4059,9 @@ fn transitioned_cleanup_tuple(oi: &ObjectInfo) -> Result<(&str, &str, &str), std
Ok((&transitioned.name, &transitioned.version_id, &transitioned.tier))
}
/// Queue a committed object with its storage-validated bucket identity.
/// `None` permits the transition but withholds external notifications.
pub async fn enqueue_transition_immediate(oi: &ObjectInfo, src: LcEventSrc, notification_bucket_incarnation: Option<Uuid>) {
pub async fn enqueue_transition_immediate(oi: &ObjectInfo, src: LcEventSrc) {
if let Some(lc) = runtime_sources::bucket_lifecycle_config(&oi.bucket).await {
enqueue_transition_with_lifecycle(oi, &lc, &src, notification_bucket_incarnation).await;
enqueue_transition_with_lifecycle(oi, &lc, &src).await;
}
}
@@ -4547,20 +4534,10 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
let deadline = options.max_duration.map(|duration| tokio::time::Instant::now() + duration);
loop {
let (page, bucket_incarnation_id) = {
// Lock order: lifecycle read -> metadata transaction -> listing locks.
// Release the lifecycle fence before enqueue or progress persistence.
let guard = api.acquire_bucket_lifecycle_read_lock(bucket).await?;
let incarnation = api.bucket_incarnation_id_from_disk(bucket).await?;
let page = api
.clone()
.list_object_versions(bucket, &options.prefix, marker.clone(), version_marker.clone(), None, LIST_PAGE_SIZE)
.await?;
if guard.is_lock_lost() {
return Err(Error::other("bucket lifecycle lock was lost while listing transition candidates"));
}
(page, incarnation)
};
let page = api
.clone()
.list_object_versions(bucket, &options.prefix, marker.clone(), version_marker.clone(), None, LIST_PAGE_SIZE)
.await?;
for (index, object) in page.objects.iter().enumerate() {
if manual_transition_cancel_requested(&options).await {
@@ -4582,16 +4559,7 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
return Ok(report);
}
report.scanned = report.scanned.saturating_add(1);
enqueue_transition_with_lifecycle_report(
Some(api.clone()),
object,
&lc,
&src,
&options,
&mut report,
Some(bucket_incarnation_id),
)
.await;
enqueue_transition_with_lifecycle_report(Some(api.clone()), object, &lc, &src, &options, &mut report).await;
if report.has_enqueue_backpressure() {
report.next_marker.clone_from(&previous_marker);
report.next_version_idmarker.clone_from(&previous_version_marker);
@@ -4897,7 +4865,6 @@ async fn enqueue_transition_with_lifecycle_report(
src: &LcEventSrc,
options: &ManualTransitionRunOptions,
report: &mut ManualTransitionRunReport,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
if oi.transitioned_object.status == TRANSITION_COMPLETE {
if options
@@ -4950,7 +4917,7 @@ async fn enqueue_transition_with_lifecycle_report(
return true;
}
let outcome = runtime_sources::transition_state_handle()
.queue_transition_task_outcome(api.clone(), oi, &event, src, options.job_id, notification_bucket_incarnation)
.queue_transition_task_outcome(api.clone(), oi, &event, src, options.job_id)
.await;
report.record_enqueue_outcome(outcome);
return outcome.is_handled();
@@ -4960,12 +4927,7 @@ async fn enqueue_transition_with_lifecycle_report(
false
}
async fn enqueue_transition_with_lifecycle(
oi: &ObjectInfo,
lc: &PersistedLifecycleConfiguration,
src: &LcEventSrc,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
async fn enqueue_transition_with_lifecycle(oi: &ObjectInfo, lc: &PersistedLifecycleConfiguration, src: &LcEventSrc) -> bool {
let event = lc.eval(&oi.to_lifecycle_opts()).await;
match event.action {
IlmAction::TransitionAction | IlmAction::TransitionVersionAction => {
@@ -4976,9 +4938,8 @@ async fn enqueue_transition_with_lifecycle(
return false;
}
runtime_sources::transition_state_handle()
.queue_transition_task_outcome(None, oi, &event, src, None, notification_bucket_incarnation)
.queue_transition_task(oi, &event, src)
.await
.is_handled()
}
_ => false,
}
@@ -5160,7 +5121,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
}
};
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).await;
schedule_lifecycle_replication_delete_if_needed(oi, &dobj).await;
// The transitioned version is gone; evict any cached body for this object
// so it does not linger until TTL (ODC-26).
@@ -5173,7 +5134,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
//audit_log_lifecycle(oi, ILMExpiry, tags);
emit_transitioned_expiration_event(oi, &dobj, bucket_incarnation_id);
emit_transitioned_expiration_event(oi, &dobj);
Ok(dobj)
}
@@ -5191,22 +5152,12 @@ pub fn gen_transition_objname(bucket: &str) -> Result<String, Error> {
Ok(obj)
}
async fn transition_object(
api: Arc<ECStore>,
oi: &ObjectInfo,
lae: LcAuditEvent,
notification_bucket_incarnation: Option<Uuid>,
) -> (Option<Uuid>, Result<(), Error>) {
pub async fn transition_object(api: Arc<ECStore>, oi: &ObjectInfo, lae: LcAuditEvent) -> Result<(), Error> {
let time_ilm = Metrics::time_ilm(lae.event.action);
let Some((publication_guard, bucket_incarnation_id)) =
lifecycle_transition_publication_guard(&api, oi, notification_bucket_incarnation).await
else {
return (
notification_bucket_incarnation,
Err(Error::other("lifecycle transition is not allowed for this bucket")),
);
};
let (publication_guard, bucket_incarnation_id) = lifecycle_transition_publication_guard(&api, oi)
.await
.ok_or_else(|| Error::other("lifecycle transition is not allowed for this bucket"))?;
let etag = if let Some(etag) = &oi.etag { etag } else { "" };
let etag = etag.to_string();
@@ -5224,13 +5175,12 @@ async fn transition_object(
version_suspended: BucketVersioningSys::prefix_suspended(&oi.bucket, &oi.name).await,
mod_time: oi.mod_time,
expected_bucket_incarnation_id: Some(bucket_incarnation_id),
notification_bucket_incarnation_id: notification_bucket_incarnation,
..Default::default()
};
opts.add_namespace_lock_guard(&publication_guard);
let result = api.transition_object(&oi.bucket, &oi.name, &opts).await;
time_ilm(1)();
(notification_bucket_incarnation, result)
result
}
#[allow(
@@ -5841,22 +5791,12 @@ fn lifecycle_replication_blocks_action(oi: &ObjectInfo) -> bool {
}
pub async fn apply_transition_rule(event: &lifecycle::Event, src: &LcEventSrc, oi: &ObjectInfo) -> bool {
apply_transition_rule_with_incarnation(event, src, oi, None).await
}
pub async fn apply_transition_rule_with_incarnation(
event: &lifecycle::Event,
src: &LcEventSrc,
oi: &ObjectInfo,
notification_bucket_incarnation: Option<Uuid>,
) -> bool {
if oi.delete_marker || oi.is_dir {
return false;
}
runtime_sources::transition_state_handle()
.queue_transition_task_outcome(None, oi, event, src, None, notification_bucket_incarnation)
.queue_transition_task(oi, event, src)
.await
.is_handled()
}
async fn acquire_lifecycle_publication_guard(api: &ECStore, bucket: &str) -> Result<rustfs_lock::NamespaceLockGuard, Error> {
@@ -5905,14 +5845,10 @@ pub(crate) async fn lifecycle_expiry_publication_guard(
async fn lifecycle_transition_publication_guard(
api: &ECStore,
oi: &ObjectInfo,
expected_incarnation: Option<Uuid>,
) -> Option<(rustfs_lock::NamespaceLockGuard, Uuid)> {
let result: std::result::Result<(rustfs_lock::NamespaceLockGuard, Uuid), Error> = async {
let guard = acquire_lifecycle_publication_guard(api, &oi.bucket).await?;
let configs = metadata_boundary::get_expiry_configs(api, &oi.bucket).await?;
if expected_incarnation.is_some_and(|expected| expected != configs.bucket_incarnation_id) {
return Err(Error::PreconditionFailed);
}
Ok((guard, configs.bucket_incarnation_id))
}
.await;
@@ -6098,7 +6034,7 @@ async fn apply_expiry_on_non_transitioned_objects_with_lock_lost_signal(
{
accounting.commit(size).await;
}
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).await;
schedule_lifecycle_replication_delete_if_needed(oi, &dobj).await;
// The object (or all its versions, for delete_all) was expired; evict any
// cached body so dead bytes do not sit resident until TTL (ODC-26). The
@@ -6114,7 +6050,7 @@ async fn apply_expiry_on_non_transitioned_objects_with_lock_lost_signal(
//let tags = LcAuditEvent::new(lc_event.clone(), src.clone()).tags();
//tags["version-id"] = dobj.version_id;
emit_non_transitioned_expiration_event(lc_event.action, oi, dobj, bucket_incarnation_id);
emit_non_transitioned_expiration_event(lc_event.action, oi, dobj);
if lc_event.action != IlmAction::NoneAction {
let mut num_versions = 1_u64;
@@ -6266,12 +6202,12 @@ fn lifecycle_deleted_object(oi: &ObjectInfo, dobj: &ObjectInfo) -> DeletedObject
}
}
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo, bucket_incarnation_id: Uuid) {
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo) {
let delete_object = lifecycle_deleted_object(oi, dobj);
if delete_object.replication_state.is_none() {
return;
}
replication_sink::schedule_delete(oi.bucket.clone(), delete_object, Some(bucket_incarnation_id)).await;
replication_sink::schedule_delete(oi.bucket.clone(), delete_object).await;
}
async fn lifecycle_delete_config_snapshot(api: &ECStore, oi: &ObjectInfo) -> Result<DeleteReplicationConfigSnapshot, Error> {
@@ -6661,7 +6597,6 @@ mod tests {
next_object_marker: truncated.then(|| "object".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated,
}
}
@@ -9179,160 +9114,6 @@ mod tests {
assert!(recovery_notify.notified().now_or_never().is_some());
}
#[tokio::test]
async fn transition_dedup_keeps_recreated_bucket_admissions_independent() {
let state = TransitionState::new_with_capacity(2);
let object = ObjectInfo {
bucket: "bucket".to_string(),
name: "same-key".to_string(),
..Default::default()
};
let first = Uuid::new_v4();
let second = Uuid::new_v4();
let event = lifecycle::Event {
action: IlmAction::TransitionAction,
..Default::default()
};
for identity in [first, second] {
assert_eq!(
state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, Some(identity))
.await,
TransitionEnqueueOutcome::Queued
);
}
state.release_transition(&object, Some(first));
assert!(
!state.reserve_transition(&object, Some(second)),
"finishing the old incarnation must retain the new claim"
);
assert!(state.reserve_transition(&object, Some(first)), "only the old claim was released");
}
#[tokio::test]
#[serial]
async fn queued_transition_notifications_keep_the_admitted_bucket_incarnation() {
use super::metadata_boundary::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::services::event_notification::test_recorder;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "queued-transition-notification-origin";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create original bucket");
let original = store.bucket_incarnation_id(bucket).await.expect("original identity");
let state = TransitionState::new_with_capacity(2);
let event = lifecycle::Event {
action: IlmAction::TransitionVersionAction,
storage_class: "missing-tier".to_string(),
..Default::default()
};
for (name, identity) in [("known-old", Some(original)), ("unknown-replay", None)] {
let object = ObjectInfo {
bucket: bucket.to_string(),
name: name.to_string(),
version_id: Some(Uuid::new_v4()),
..Default::default()
};
assert_eq!(
state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, identity)
.await,
TransitionEnqueueOutcome::Queued
);
}
store
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete original bucket");
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("recreate bucket");
let replacement = store.bucket_incarnation_id(bucket).await.expect("replacement identity");
assert_ne!(original, replacement);
test_recorder::install();
for expected in [Some(original), None] {
let task = state
.transition_rx
.recv()
.await
.expect("receive queued transition")
.expect("transition task");
assert_eq!(task.notification_bucket_incarnation, expected);
let (identity, result) = super::transition_object(
store.clone(),
&task.obj_info,
super::LcAuditEvent::new(task.event, task.src),
task.notification_bucket_incarnation,
)
.await;
assert!(result.is_err(), "the old version cannot transition in the replacement");
assert_eq!(identity, expected);
super::emit_transition_failed_event(task.obj_info, identity);
}
let events = test_recorder::recorded_for_bucket(bucket);
assert_eq!(events.len(), 2);
assert_eq!(events[0].bucket_incarnation_id, Some(original));
assert_eq!(events[1].bucket_incarnation_id, None);
assert!(events.iter().all(|event| event.bucket_incarnation_id != Some(replacement)));
}
#[tokio::test]
#[serial]
async fn successful_recovered_transition_keeps_unknown_notification_origin_unbound() {
use super::metadata_boundary::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::services::event_notification::test_recorder;
use crate::services::tier::test_util::register_mock_tier;
use rustfs_s3_types::EventName;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("recovered-notify-{}", &Uuid::new_v4().simple().to_string()[..12]);
let object = "object";
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create transition bucket");
let mut reader = PutObjReader::from_vec(b"transition payload".to_vec());
store
.put_object(&bucket, object, &mut reader, &ObjectOptions::default())
.await
.expect("seed transition object");
let object_info = store
.get_object_info(&bucket, object, &ObjectOptions::default())
.await
.expect("read transition object");
let tier = format!("COLDTIER{}", &Uuid::new_v4().simple().to_string()[..8]).to_uppercase();
register_mock_tier(&store.tier_config_mgr(), &tier).await;
test_recorder::install();
let (origin, result) = super::transition_object(
store,
&object_info,
super::LcAuditEvent::new(
lifecycle::Event {
action: IlmAction::TransitionAction,
storage_class: tier,
..Default::default()
},
LcEventSrc::Scanner,
),
None,
)
.await;
assert!(result.is_ok(), "recovered transition should complete: {result:?}");
assert_eq!(origin, None);
let events = test_recorder::recorded_for_bucket(&bucket);
let transition = events
.iter()
.find(|event| event.event_name == EventName::LifecycleTransition.as_str())
.expect("successful transition should emit its native lifecycle event");
assert_eq!(transition.bucket_incarnation_id, None);
}
#[tokio::test]
#[serial]
async fn scanner_transition_enqueue_reports_full_queue() {
@@ -9400,7 +9181,7 @@ mod tests {
.await
.expect("queue should remain open")
.expect("first queued transition task should be present");
state.release_transition(&first_task.obj_info, first_task.notification_bucket_incarnation);
state.release_transition(&first_task.obj_info);
assert!(
deferred.await,
@@ -10159,8 +9940,8 @@ mod tests {
..Default::default()
};
assert!(state.reserve_transition(&oi, None), "first claim must succeed");
assert!(!state.reserve_transition(&oi, None), "duplicate claim must be rejected");
assert!(state.reserve_transition(&oi), "first claim must succeed");
assert!(!state.reserve_transition(&oi), "duplicate claim must be rejected");
// A different object is independent.
let other = ObjectInfo {
@@ -10169,11 +9950,11 @@ mod tests {
version_id: None,
..Default::default()
};
assert!(state.reserve_transition(&other, None), "distinct object must claim independently");
assert!(state.reserve_transition(&other), "distinct object must claim independently");
// After release, the same object can be re-claimed (later lifecycle pass).
state.release_transition(&oi, None);
assert!(state.reserve_transition(&oi, None), "re-claim after release must succeed");
state.release_transition(&oi);
assert!(state.reserve_transition(&oi), "re-claim after release must succeed");
}
#[tokio::test]
@@ -10215,10 +9996,10 @@ mod tests {
};
let first = state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
.await;
let second = state
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
.await;
assert_eq!(first, TransitionEnqueueOutcome::Queued);
@@ -10246,10 +10027,10 @@ mod tests {
};
let first = state
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None, None)
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None)
.await;
let second = state
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None, None)
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None)
.await;
assert_eq!(first, TransitionEnqueueOutcome::Queued);
@@ -10282,7 +10063,7 @@ mod tests {
let task_key = manual_transition_worker_result_task_key(&object.bucket, &object.name, object.version_id);
let outcome = state
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id))
.await;
assert_eq!(outcome, TransitionEnqueueOutcome::Queued);
@@ -10319,14 +10100,14 @@ mod tests {
};
let failed = state
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()), None)
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()))
.await;
assert_eq!(failed, TransitionEnqueueOutcome::TaskJournalFailed);
assert_eq!(state.transition_rx.len(), 0);
let retried = state
.queue_transition_task_outcome(Some(ecstore), &object, &event, &LcEventSrc::Scanner, Some(Uuid::new_v4()), None)
.queue_transition_task_outcome(Some(ecstore), &object, &event, &LcEventSrc::Scanner, Some(Uuid::new_v4()))
.await;
assert_eq!(retried, TransitionEnqueueOutcome::Queued);
assert_eq!(state.transition_rx.len(), 1);
@@ -10827,7 +10608,7 @@ mod tests {
let lc = latest_transition_lifecycle();
let object = current_object(ReplicationStatusType::Pending);
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner, None).await;
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner).await;
assert!(!queued);
}
@@ -10843,7 +10624,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(handled);
assert_eq!(report.eligible, 1);
@@ -10865,7 +10646,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10884,7 +10665,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -10899,7 +10680,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -11012,7 +10793,7 @@ mod tests {
let mut report = ManualTransitionRunReport::new(&object.bucket, &options);
let handled =
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report).await;
assert!(!handled);
assert_eq!(report.eligible, 0);
@@ -14357,7 +14138,7 @@ mod tests {
let admission_store = ecstore.clone();
let admission_object = object_info.clone();
let mut admission =
tokio::spawn(async move { lifecycle_transition_publication_guard(&admission_store, &admission_object, None).await });
tokio::spawn(async move { lifecycle_transition_publication_guard(&admission_store, &admission_object).await });
assert!(
tokio::time::timeout(StdDuration::from_millis(100), &mut admission)
.await
@@ -15176,37 +14957,6 @@ mod tests {
}
}
async fn seed_corrupt_free_version(disk_paths: &[PathBuf], bucket: &str, object: &str) -> Vec<u8> {
use rustfs_utils::http::metadata_compat::{SUFFIX_TRANSITIONED_VERSION_STATE, insert_bytes};
seed_recoverable_free_version(disk_paths, bucket, object, None, None).await;
let path = PathBuf::from(bucket).join(object).join(STORAGE_FORMAT_FILE);
let original = fs::read(disk_paths[0].join(&path))
.await
.expect("read the seeded free version");
let mut metadata = FileMeta::load(&original).expect("load the seeded metadata");
let mut version = metadata.versions[0].parse_version_meta().expect("decode the seeded version");
let marker = version.delete_marker.as_mut().expect("the free version is a delete marker");
insert_bytes(&mut marker.meta_sys, SUFFIX_TRANSITIONED_VERSION_STATE, b"invalid".to_vec());
metadata.versions[0] = version
.try_into()
.expect("encode the malformed marker with a consistent header");
let encoded = metadata.marshal_msg().expect("encode the metadata with a valid checksum");
let reloaded = FileMeta::load(&encoded).expect("the metadata envelope must remain readable");
assert_eq!(
reloaded
.get_file_info_versions(bucket, object, false)
.expect_err("decoding the marker must fail"),
rustfs_filemeta::Error::FileCorrupt
);
for disk in disk_paths {
fs::write(disk.join(&path), &encoded)
.await
.expect("persist the same malformed marker on every disk");
}
encoded
}
async fn remove_seeded_free_version(disk_paths: &[PathBuf], bucket: &str, object: &str) {
for disk_path in disk_paths {
fs::remove_dir_all(disk_path.join(bucket).join(object))
@@ -15279,7 +15029,6 @@ mod tests {
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
}
);
@@ -15476,14 +15225,12 @@ mod tests {
);
assert_eq!(check.reasons.len(), 1);
assert_eq!(check.reasons[0].kind, crate::services::tier::tier::TierDeletionReasonKind::CleanupPending);
seed_corrupt_free_version(&disks, &bucket, "corrupt").await;
let report = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("retry should enqueue durable cleanup");
assert_eq!(report.status, TierCleanupRetryStatus::Accepted);
assert_eq!(report.enqueued, 1);
assert_eq!(report.failed, 0);
assert_eq!(report.unreadable_objects, 1);
let rx = Arc::clone(&state.read().await.tasks_rx[0]);
let task = rx.lock().await.try_recv().expect("cleanup was queued").expect("queue item");
let task = task
@@ -15503,27 +15250,21 @@ mod tests {
let other = retry_tier_free_version_cleanup(api.clone(), "OTHER")
.await
.expect("other tier retry should be bounded");
assert_eq!(other.status, TierCleanupRetryStatus::Accepted);
assert_eq!(other.enqueued, 0, "retry must not enqueue a different tier's marker");
assert_eq!(other.failed, 0);
let json = serde_json::to_value(&other).expect("serialize the public retry report");
assert_eq!(json["unreadableObjects"], 1, "unreadable keys cannot be attributed to a tier");
assert!(rx.lock().await.try_recv().is_err());
reset_runtime_expiry_state(&api).await;
let failed = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("queue failure remains retryable");
assert_eq!(failed.failed, 1);
assert_eq!(failed.enqueued, 0);
assert_eq!(failed.unreadable_objects, 1);
assert_eq!(crate::services::tier::test_util::free_version_count(&disks[0], &bucket, "owned").await, 1);
remove_seeded_free_version(&disks, &bucket, "corrupt").await;
api.tier_config_mgr()
.write()
.await
.remove("OTHER", true)
.await
.expect("remove other mock tier");
reset_runtime_expiry_state(&api).await;
let failed = retry_tier_free_version_cleanup(api.clone(), "WARM")
.await
.expect("queue failure remains retryable");
assert_eq!(failed.failed, 1);
assert_eq!(failed.enqueued, 0);
assert_eq!(crate::services::tier::test_util::free_version_count(&disks[0], &bucket, "owned").await, 1);
remove_seeded_free_version(&disks, &bucket, "owned").await;
api.tier_config_mgr()
.write()
@@ -15743,121 +15484,6 @@ mod tests {
reset_runtime_expiry_state(&ecstore).await;
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_enqueues_past_a_corrupt_free_version() {
let (disk_paths, ecstore) = setup_test_env().await;
let prefix = format!("zzzz-recovery-corrupt-{}", Uuid::new_v4().simple());
let first_bucket = format!("{prefix}-a");
let second_bucket = format!("{prefix}-b");
for bucket in [&first_bucket, &second_bucket] {
create_test_bucket(&ecstore, bucket).await;
}
let healthy = [
(first_bucket.as_str(), "a"),
(first_bucket.as_str(), "c"),
(second_bucket.as_str(), "d"),
];
for (bucket, object) in healthy {
seed_recoverable_free_version(&disk_paths, bucket, object, None, None).await;
}
let corrupt = seed_corrupt_free_version(&disk_paths, &first_bucket, "b").await;
let state = install_unconsumed_runtime_expiry_worker(&ecstore, healthy.len()).await;
let stats = recover_tier_free_versions_with_cancel(
Arc::clone(&ecstore),
healthy.len() + 1,
Some(first_bucket.clone()),
None,
CancellationToken::new(),
)
.await
.expect("a corrupt free version must not discard other recovery candidates");
assert!(!stats.truncated);
assert_eq!(stats.enqueued, healthy.len());
let receiver = Arc::clone(&state.read().await.tasks_rx[0]);
let mut receiver = receiver.lock().await;
for (bucket, object) in healthy {
let task = receiver
.try_recv()
.expect("receive a healthy cleanup task")
.expect("the queue carries a task");
let task = task
.as_any()
.downcast_ref::<FreeVersionTask>()
.expect("a free-version cleanup task");
assert_eq!((task.0.bucket.as_str(), task.0.name.as_str()), (bucket, object));
}
drop(receiver);
reset_runtime_expiry_state(&ecstore).await;
for disk in &disk_paths {
let stored = fs::read(disk.join(&first_bucket).join("b").join(STORAGE_FORMAT_FILE))
.await
.expect("discovery must preserve the unreadable marker");
assert_eq!(stored, corrupt);
}
for (bucket, object) in healthy.into_iter().chain([(first_bucket.as_str(), "b")]) {
remove_seeded_free_version(&disk_paths, bucket, object).await;
}
for bucket in [&first_bucket, &second_bucket] {
ecstore
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete the empty test bucket");
}
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_counts_a_corrupt_boundary_once_per_sweep() {
let (disk_paths, ecstore) = setup_test_env().await;
let bucket = format!("zzzz-recovery-boundary-{}", Uuid::new_v4().simple());
create_test_bucket(&ecstore, &bucket).await;
seed_corrupt_free_version(&disk_paths, &bucket, "b").await;
seed_recoverable_free_version(&disk_paths, &bucket, "c", None, None).await;
let page_from = |marker| {
list_tier_free_versions_with_budget(
Arc::clone(&ecstore),
2,
Some(bucket.clone()),
marker,
CancellationToken::new(),
RecoveryWorkBudget {
max_objects: 1,
max_buckets: 1,
},
)
};
let first = page_from(None)
.await
.expect("the unreadable key should consume the first page");
assert!(first.items.is_empty());
assert_eq!(first.unreadable_objects, 1);
assert!(first.truncated);
assert_eq!(first.next_bucket_marker.as_deref(), Some(bucket.as_str()));
assert_eq!(first.next_object_marker.as_deref(), Some("b"));
let second = page_from(first.next_object_marker)
.await
.expect("resume past the unreadable boundary");
assert_eq!(second.unreadable_objects, 0);
assert_eq!(second.items.len(), 1);
assert_eq!(second.items[0].name, "c");
let next_sweep = page_from(None).await.expect("a later sweep must revisit the unreadable key");
assert_eq!(next_sweep.unreadable_objects, 1);
assert_eq!(next_sweep.next_object_marker.as_deref(), Some("b"));
for object in ["b", "c"] {
remove_seeded_free_version(&disk_paths, &bucket, object).await;
}
ecstore
.delete_bucket(&bucket, &DeleteBucketOptions::default())
.await
.expect("delete the empty test bucket");
}
#[tokio::test]
#[serial]
async fn tier_free_version_recovery_real_enqueue_failure_retries_same_object() {
@@ -124,9 +124,6 @@ pub(crate) async fn get_lifecycle_config(bucket: &str) -> Result<(PersistedLifec
metadata_sys::get_lifecycle_config(bucket).await
}
#[cfg(test)]
pub(crate) use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support};
#[cfg(test)]
mod tests {
use super::*;
@@ -128,7 +128,7 @@ pub async fn delete_object_versions(
// order and admission; the event is derived from the committed
// result, and a send failure never rolls back a delete that
// already happened (backlog#2202).
emit_noncurrent_expiration_event(bucket, target, deleted_obj, false, bucket_incarnation_id);
emit_noncurrent_expiration_event(bucket, target, deleted_obj, false);
}
if !deleted_obj
.replication_state
@@ -137,7 +137,7 @@ pub async fn delete_object_versions(
{
continue;
}
replication_sink::schedule_delete(bucket.to_string(), deleted_obj.clone(), Some(bucket_incarnation_id)).await;
replication_sink::schedule_delete(bucket.to_string(), deleted_obj.clone()).await;
}
for (i, err) in errors.iter().enumerate() {
@@ -66,12 +66,8 @@ pub(crate) fn lifecycle_action_waits_for_replication(action: IlmAction) -> bool
)
}
pub(crate) async fn schedule_delete(
bucket: String,
delete_object: DeletedObject,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
ReplicationLifecycleBridge::schedule_delete(bucket, delete_object, notification_bucket_incarnation).await;
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
ReplicationLifecycleBridge::schedule_delete(bucket, delete_object).await;
}
#[cfg(test)]
@@ -20,9 +20,7 @@ use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::bucket::lifecycle::bucket_lifecycle_ops::{
EVENT_LIFECYCLE_WORKER_STATE, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_LIFECYCLE, enqueue_recovered_free_version_with_cancel,
};
use crate::bucket::lifecycle::bucket_lifecycle_ops::enqueue_recovered_free_version_with_cancel;
use crate::disk::RUSTFS_META_BUCKET;
use crate::error::Result;
use crate::object_api::ObjectInfo;
@@ -30,10 +28,9 @@ use crate::services::tier::tier::{ERR_TIER_INVALID_CONFIG, TierConfigMgr};
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
use crate::storage_api_contracts::{
bucket::{BucketOperations, BucketOptions},
list::StorageWalkOptions,
list::{ListOperations as _, StorageObjectInfoOrErr, StorageWalkOptions},
};
use crate::store::ECStore;
use crate::store::list_objects::TierRecoveryEntry;
use rustfs_filemeta::FileInfo;
use rustfs_lock::error::LockError;
use rustfs_s3_client::admin_handler_utils::AdminError;
@@ -48,6 +45,7 @@ const BACKGROUND_WALK_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(test)]
const BACKGROUND_WALK_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
type ObjectInfoOrErr = StorageObjectInfoOrErr<ObjectInfo, crate::error::Error>;
type WalkOptions = StorageWalkOptions<fn(&FileInfo) -> bool>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -145,8 +143,6 @@ pub struct TierCleanupRetryReport {
pub scanned: usize,
pub enqueued: usize,
pub failed: usize,
/// Unreadable logical objects encountered in this pass, whose tier is unknown.
pub unreadable_objects: usize,
pub scan_truncated: bool,
}
@@ -165,7 +161,6 @@ impl TierCleanupRetryReport {
scanned: 0,
enqueued: 0,
failed: 0,
unreadable_objects: 0,
scan_truncated: false,
}
}
@@ -272,7 +267,6 @@ async fn retry_tier_free_version_cleanup_page(
.map_err(|_| tier_cleanup_retry_error())?;
let mut report = TierCleanupRetryReport::new(tier_name, TierCleanupRetryStatus::Accepted);
report.scanned = page.scanned_entries;
report.unreadable_objects = page.unreadable_objects;
report.scan_truncated = page.truncated;
for object in page.items {
if cancel.is_cancelled() {
@@ -296,7 +290,6 @@ pub struct FreeVersionRecoveryStats {
pub next_object_marker: Option<String>,
pub scanned_entries: usize,
pub buckets_scanned: usize,
pub unreadable_objects: usize,
pub truncated: bool,
}
@@ -307,7 +300,6 @@ pub struct FreeVersionRecoveryPage {
pub next_object_marker: Option<String>,
pub scanned_entries: usize,
pub buckets_scanned: usize,
pub unreadable_objects: usize,
pub truncated: bool,
}
@@ -351,7 +343,6 @@ pub(super) async fn recover_tier_free_versions_with_cancel(
next_object_marker: page.next_object_marker,
scanned_entries: page.scanned_entries,
buckets_scanned: page.buckets_scanned,
unreadable_objects: page.unreadable_objects,
truncated: page.truncated,
};
@@ -481,7 +472,6 @@ async fn list_tier_free_versions_for_tier(
next_object_marker: None,
scanned_entries: 0,
buckets_scanned: 0,
unreadable_objects: 0,
truncated: false,
};
@@ -515,7 +505,6 @@ async fn list_tier_free_versions_for_tier(
let mut bucket_seen = bucket_marker.is_none();
let mut truncated_after: Option<RecoveryCursor> = None;
let mut remaining_scan_objects = work_budget.max_objects;
let mut first_unreadable = None;
for bucket in buckets {
if cancel_token.is_cancelled() {
@@ -546,7 +535,7 @@ async fn list_tier_free_versions_for_tier(
};
let bucket_walk_limit = remaining_scan_objects;
let (tx, mut rx) = mpsc::channel::<Result<TierRecoveryEntry>>(100);
let (tx, mut rx) = mpsc::channel::<ObjectInfoOrErr>(100);
let cancel = cancel_token.child_token();
let mut draining_after_truncation = false;
let mut drain_deadline = None;
@@ -570,7 +559,14 @@ async fn list_tier_free_versions_for_tier(
match action {
RecoveryWalkTestAction::SendItems(items) => {
for item in items {
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
return Ok(());
}
}
@@ -578,16 +574,35 @@ async fn list_tier_free_versions_for_tier(
}
RecoveryWalkTestAction::SendItemsThenError(items, err) => {
for item in items {
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
return Ok(());
}
}
let _ = tx.send(Err(err)).await;
let _ = tx
.send(ObjectInfoOrErr {
item: None,
err: Some(err),
})
.await;
return Ok(());
}
RecoveryWalkTestAction::SendItemsThenHang(items, started) => {
for item in items {
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
if tx
.send(ObjectInfoOrErr {
item: Some(item),
err: None,
})
.await
.is_err()
{
return Ok(());
}
}
@@ -599,11 +614,14 @@ async fn list_tier_free_versions_for_tier(
let mut index = 0usize;
loop {
if tx
.send(Ok(TierRecoveryEntry::Version(Box::new(ObjectInfo {
bucket: bucket_name.clone(),
name: format!("nonrecoverable-{index:08}"),
..Default::default()
}))))
.send(ObjectInfoOrErr {
item: Some(ObjectInfo {
bucket: bucket_name.clone(),
name: format!("nonrecoverable-{index:08}"),
..Default::default()
}),
err: None,
})
.await
.is_err()
{
@@ -621,7 +639,7 @@ async fn list_tier_free_versions_for_tier(
}
}
api.walk_for_tier_recovery(cancel, &bucket_name, tx, recovery_walk_options(bucket_walk_limit, object_marker))
api.walk(cancel, &bucket_name, "", tx, recovery_walk_options(bucket_walk_limit, object_marker))
.await
}
});
@@ -651,25 +669,21 @@ async fn list_tier_free_versions_for_tier(
},
};
page.scanned_entries += 1;
let entry = match item {
Ok(entry) => entry,
Err(err) => {
cancel.cancel();
receive_error = Some(err);
break;
}
};
if let Some(err) = item.err {
cancel.cancel();
receive_error = Some(err);
break;
}
if draining_after_truncation {
continue;
}
let name = match &entry {
TierRecoveryEntry::Version(oi) => oi.name.as_str(),
TierRecoveryEntry::Unreadable { object } => object.as_str(),
let Some(oi) = item.item else {
continue;
};
if last_seen_object.as_deref() != Some(name) && scanned_objects >= bucket_walk_limit {
if last_seen_object.as_deref() != Some(oi.name.as_str()) && scanned_objects >= bucket_walk_limit {
// The disk listing limit follows S3-visible counting rules and
// does not charge metadata containing only hidden/free versions.
// Charge the recovery budget by key, including unreadable metadata.
// Enforce the repair budget again at the decoded-object boundary.
page.truncated = true;
page.next_bucket_marker = Some(bucket.name.clone());
page.next_object_marker = last_seen_object.clone();
@@ -678,9 +692,9 @@ async fn list_tier_free_versions_for_tier(
drain_deadline = Some(tokio::time::Instant::now() + BACKGROUND_WALK_SHUTDOWN_TIMEOUT);
continue;
}
record_scanned_object(&mut last_seen_object, &mut scanned_objects, name);
record_scanned_object(&mut last_seen_object, &mut scanned_objects, &oi.name);
if let Some(cursor) = &truncated_after
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != name)
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != oi.name.as_str())
{
page.truncated = true;
cancel.cancel();
@@ -688,14 +702,6 @@ async fn list_tier_free_versions_for_tier(
drain_deadline = Some(tokio::time::Instant::now() + BACKGROUND_WALK_SHUTDOWN_TIMEOUT);
continue;
}
let oi = match entry {
TierRecoveryEntry::Version(oi) => *oi,
TierRecoveryEntry::Unreadable { object } => {
page.unreadable_objects += 1;
first_unreadable.get_or_insert_with(|| (bucket.name.clone(), object));
continue;
}
};
if is_recoverable_tier_free_version_for_tier(&oi, tier_name) {
let current_cursor = RecoveryCursor {
bucket: bucket.name.clone(),
@@ -750,18 +756,6 @@ async fn list_tier_free_versions_for_tier(
page.next_object_marker = None;
}
if let Some((bucket, object)) = first_unreadable {
tracing::warn!(
event = EVENT_LIFECYCLE_WORKER_STATE,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_LIFECYCLE,
state = "free_version_recovery_unreadable_metadata",
unreadable_objects = page.unreadable_objects,
sample_bucket = ?bucket,
sample_object = ?object,
"Retained unreadable objects during tier free-version recovery"
);
}
Ok(page)
}
@@ -829,7 +823,6 @@ mod tests {
next_object_marker: None,
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
@@ -850,7 +843,6 @@ mod tests {
next_object_marker: Some("object".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
@@ -871,7 +863,6 @@ mod tests {
next_object_marker: Some("object-a".to_string()),
scanned_entries: 1,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
let mut cursor = RetryCursor::new(stats.next_bucket_marker.clone(), stats.next_object_marker.clone());
@@ -982,7 +973,6 @@ mod tests {
next_object_marker: None,
scanned_entries: DEFAULT_FREE_VERSION_RECOVERY_SCAN_LIMIT,
buckets_scanned: 1,
unreadable_objects: 0,
truncated: false,
};
+18 -320
View File
@@ -2090,74 +2090,6 @@ pub(crate) fn bump_local_meta_mutation_gen() {
LOCAL_META_MUTATION_GEN.fetch_add(1, std::sync::atomic::Ordering::Release);
}
/// Bumps `LOCAL_META_MUTATION_GEN` for mutations in `RUSTFS_META_BUCKET` except
/// known non-authority scanner, data-usage, and shutdown-marker paths.
///
/// The classifier is fail-closed: only exact 1-, 2-, or 3-segment paths naming
/// `unclean-shutdown`, root scanner summary/usage files under `buckets/`, or
/// per-bucket `.usage-cache.bin[.bkp]` files (with at most one optional trailing
/// `/<uuid>` data-dir/transaction cleanup segment) skip the generation bump.
/// All bucket authority files (`.metadata.bin`, `.bucket-incarnation`), bucket
/// metadata directories (including names ending in `.usage-cache.bin`), and any
/// other `.rustfs.sys` paths bump `LOCAL_META_MUTATION_GEN`.
pub(crate) fn maybe_bump_local_meta_mutation_gen_for_path(volume: &str, path: &str) {
if volume != crate::disk::RUSTFS_META_BUCKET {
return;
}
if !is_non_authority_meta_bucket_path(path) {
bump_local_meta_mutation_gen();
}
}
fn is_non_authority_meta_bucket_path(path: &str) -> bool {
let trimmed = path.trim_matches('/');
if trimmed.is_empty() {
return false;
}
let normalized = match trimmed.rsplit_once('/') {
Some((prefix, tail)) if !prefix.is_empty() && Uuid::parse_str(tail).is_ok() => prefix,
_ => trimmed,
};
if normalized == crate::disk::UNCLEAN_SHUTDOWN_MARKER_PATH {
return true;
}
let Some(rest) = normalized
.strip_prefix(crate::disk::BUCKET_META_PREFIX)
.and_then(|rest| rest.strip_prefix('/'))
else {
return false;
};
if rest.is_empty() {
return false;
}
match rest.split_once('/') {
None => {
let base = rest.strip_suffix(".bkp").unwrap_or(rest);
base == crate::data_usage::DATA_USAGE_CACHE_NAME
|| matches!(
rest,
".usage.v2.json"
| ".usage.v2.json.bkp"
| ".usage.v2.json.recovery-pending.json"
| ".usage.observed.json"
| ".usage.json"
| ".usage.json.bkp"
| ".bloomcycle.bin"
| ".compression.json"
| ".background-heal.json"
)
}
Some((bucket, name)) => {
!bucket.is_empty()
&& !bucket.contains('/')
&& bucket != "."
&& bucket != ".."
&& !name.contains('/')
&& name.strip_suffix(".bkp").unwrap_or(name) == crate::data_usage::DATA_USAGE_CACHE_NAME
}
}
}
pub(crate) fn current_local_meta_mutation_gen() -> u64 {
LOCAL_META_MUTATION_GEN.load(std::sync::atomic::Ordering::Acquire)
}
@@ -2203,20 +2135,6 @@ pub struct BucketMetadataSys {
/// then the metadata map. It is only ever taken as the first of those, so
/// it cannot invert against a path that already holds one of the others.
lazy_load_locks: Arc<MetadataPublishLockRegistry>,
/// Deduplicates concurrent cold-cache loads in
/// [`Self::read_authoritative_metadata_from_disk_under_guard`] when
/// `can_use_local_authority_cache` is true.
///
/// Lock order: caller's bucket lifecycle / metadata-transaction guard ->
/// `authority_load_locks` -> disk reads. Separate from `lazy_load_locks`
/// (which is acquired before the bucket namespace lock); holders of
/// `authority_load_locks` never acquire `lazy_load_locks`,
/// `metadata_publish_locks`, or `metadata_map`. If the leader errors or the
/// generation moves during the load, queued followers serialize and retry
/// under their own held guard.
authority_load_locks: Arc<MetadataPublishLockRegistry>,
#[cfg(test)]
authority_disk_loads: Arc<std::sync::atomic::AtomicUsize>,
#[cfg(test)]
lazy_load_lock_probe: Arc<std::sync::atomic::AtomicBool>,
/// Counts disk loads taken by the lazy `get_config` path, so a test can
@@ -2251,11 +2169,6 @@ impl BucketMetadataSys {
lazy_load_locks: Arc::new(MetadataPublishLockRegistry {
locks: StdMutex::new(HashMap::new()),
}),
authority_load_locks: Arc::new(MetadataPublishLockRegistry {
locks: StdMutex::new(HashMap::new()),
}),
#[cfg(test)]
authority_disk_loads: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
#[cfg(test)]
lazy_load_lock_probe: Arc::new(std::sync::atomic::AtomicBool::new(false)),
#[cfg(test)]
@@ -2340,7 +2253,6 @@ impl BucketMetadataSys {
.await?;
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, persisted, &guard)
.await
.map(|_| ())
}
#[cfg(test)]
@@ -2379,12 +2291,6 @@ impl BucketMetadataSys {
Self::bucket_lock_in(&self.lazy_load_locks, bucket)
}
/// Per-bucket gate for cold `local_authority_cache` loads. See
/// [`Self::authority_load_locks`].
fn authority_load_lock(&self, bucket: &str) -> Arc<Mutex<MetadataPublishLockState>> {
Self::bucket_lock_in(&self.authority_load_locks, bucket)
}
fn bucket_lock_in(registry: &Arc<MetadataPublishLockRegistry>, bucket: &str) -> Arc<Mutex<MetadataPublishLockState>> {
let mut locks = registry.locks.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
locks.get(bucket).and_then(Weak::upgrade).unwrap_or_else(|| {
@@ -2644,7 +2550,7 @@ impl BucketMetadataSys {
metadata: BucketMetadata,
persisted: bool,
namespace_guard: &rustfs_lock::NamespaceLockGuard,
) -> Result<bool> {
) -> Result<()> {
self.revoke_pending_bucket_creation(bucket).await;
if !persisted {
let _publish_guard = self
@@ -2657,7 +2563,7 @@ impl BucketMetadataSys {
_ => false,
};
if !unchanged {
return Ok(false);
return Ok(());
}
let removed = map.remove(bucket).is_some();
drop(map);
@@ -2668,7 +2574,7 @@ impl BucketMetadataSys {
clear_bucket_overrides(bucket);
clear_on_demand_migration(bucket);
}
return Ok(true);
return Ok(());
}
let _publish_guard = self
.lock_metadata_publish(bucket, namespace_guard, "refreshed bucket metadata publish")
@@ -2681,7 +2587,7 @@ impl BucketMetadataSys {
_ => false,
};
if !unchanged {
return Ok(false);
return Ok(());
}
map.insert(bucket.to_string(), Arc::clone(&metadata));
drop(map);
@@ -2690,7 +2596,7 @@ impl BucketMetadataSys {
sync_bucket_target_sys(bucket, &metadata).await;
sync_bucket_overrides(bucket, &metadata);
sync_on_demand_migration(bucket, &metadata);
Ok(true)
Ok(())
}
pub async fn get(&self, bucket: &str) -> Result<Arc<BucketMetadata>> {
@@ -2974,35 +2880,25 @@ impl BucketMetadataSys {
namespace_guard: &rustfs_lock::NamespaceLockGuard,
) -> Result<()> {
self.revoke_pending_bucket_creation(bucket).await;
let expected = self.metadata_map.read().await.get(bucket).cloned();
if !self
.bucket_exists(bucket, namespace_guard, "peer bucket metadata existence check")
.await?
{
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
}
// A concurrent publication can reject the snapshot we read. Re-read
// from storage so a newer committed config does not lose its reload to
// an older one that happened to publish first.
for _ in 0..3 {
let expected = self.metadata_map.read().await.get(bucket).cloned();
let (metadata, persisted) = await_bucket_namespace_operation(
Some(namespace_guard),
bucket,
"peer bucket metadata load",
load_bucket_metadata_parse_with_presence(self.object_store(), bucket, true),
)
.await?;
if !persisted {
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
}
if self
.publish_if_unchanged(bucket, expected.as_ref(), metadata, true, namespace_guard)
.await?
{
return Ok(());
}
let (metadata, persisted) = await_bucket_namespace_operation(
Some(namespace_guard),
bucket,
"peer bucket metadata load",
load_bucket_metadata_parse_with_presence(self.object_store(), bucket, true),
)
.await?;
if !persisted {
return Err(Error::other(PEER_METADATA_NOT_PERSISTED));
}
Err(Error::other("bucket metadata changed repeatedly during peer reload"))
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, true, namespace_guard)
.await
}
pub async fn get_config(&self, bucket: &str) -> Result<(Arc<BucketMetadata>, bool)> {
@@ -3579,7 +3475,7 @@ impl BucketMetadataSys {
let store = self.object_store();
let can_use_local_authority_cache = !store.ctx.lock_manager().is_disabled() && store.all_disks_local_and_online();
let mut gen_before = current_local_meta_mutation_gen();
let gen_before = current_local_meta_mutation_gen();
let cached_authority = can_use_local_authority_cache
.then(|| {
self.local_authority_cache
@@ -3603,43 +3499,6 @@ impl BucketMetadataSys {
}
}
let _load_guard = if can_use_local_authority_cache {
let load_lock = self.authority_load_lock(bucket);
let acquired = Box::pin(await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata authoritative snapshot",
async { Ok(load_lock.lock_owned().await) },
))
.await?;
gen_before = current_local_meta_mutation_gen();
let cached_after_lock = self
.local_authority_cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(bucket)
.filter(|(cached_gen, _)| *cached_gen == gen_before)
.map(|(_, bm)| Arc::clone(bm));
if let Some(cached) = cached_after_lock {
await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata authoritative snapshot",
std::future::ready(Ok::<_, Error>(())),
)
.await?;
if current_local_meta_mutation_gen() == gen_before && store.all_disks_local_and_online() {
return Ok(BucketMetadataAuthority::Authoritative(cached));
}
}
Some(acquired)
} else {
None
};
#[cfg(test)]
self.authority_disk_loads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (bucket_info_res, metadata_res) = tokio::join!(
Box::pin(await_bucket_namespace_operation(
Some(guard),
@@ -7122,165 +6981,4 @@ mod tests {
assert!(!should_refresh);
}
#[tokio::test]
#[serial]
async fn concurrent_authoritative_metadata_loads_singleflight_and_survive_usage_cache_writes() {
use std::sync::atomic::Ordering;
const CHILD: &str = "RUSTFS_TEST_AUTHORITY_SINGLEFLIGHT_CHILD";
const TEST: &str =
"bucket::metadata_sys::tests::concurrent_authoritative_metadata_loads_singleflight_and_survive_usage_cache_writes";
if std::env::var_os(CHILD).is_none() {
let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
.args(["--exact", TEST, "--nocapture", "--test-threads=1"])
.env(CHILD, "1")
.output()
.expect("authority singleflight subprocess");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "authority singleflight child failed: {stdout}{stderr}");
assert!(
stdout.contains("AUTHORITY_SINGLEFLIGHT_OK"),
"authority singleflight child must execute all assertions: {stdout}"
);
return;
}
let (dirs, ecstore) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(ecstore.clone(), Vec::new()).await;
let sys_lock = bucket_metadata_sys_of(&ecstore.ctx).expect("initialized bucket_metadata_sys");
let sys = Arc::new(sys_lock.read().await.clone());
let bucket = "authority-singleflight-bucket";
for dir in &dirs {
std::fs::create_dir_all(dir.path().join(bucket)).expect("bucket volume should exist");
}
sys.persist_new_and_set(BucketMetadata::new(bucket))
.await
.expect("persist committed bucket metadata and incarnation sidecar");
sys.local_authority_cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
sys.authority_disk_loads.store(0, Ordering::Relaxed);
// Hold one leader lock so all 16 waiters queue behind authority_load_lock after missing the cold cache.
let held_load_lock = sys.authority_load_lock(bucket);
let held_load_guard = held_load_lock.lock_owned().await;
let gen_before_burst = current_local_meta_mutation_gen();
let waiters = 16;
let mut handles = Vec::with_capacity(waiters);
for _ in 0..waiters {
let sys = Arc::clone(&sys);
let store = Arc::clone(&ecstore);
handles.push(tokio::spawn(async move {
let guard = acquire_bucket_metadata_transaction_read_lock_in(&store.ctx, bucket)
.await
.expect("transaction read lock");
match sys
.read_authoritative_metadata_from_disk_under_guard(bucket, &guard)
.await
.expect("authoritative read")
{
BucketMetadataAuthority::Authoritative(bm) => bm,
_ => panic!("expected Authoritative metadata"),
}
}));
}
tokio::time::sleep(Duration::from_millis(30)).await;
drop(held_load_guard);
let mut results = Vec::with_capacity(waiters);
for h in handles {
results.push(h.await.expect("waiter task joins"));
}
assert_eq!(
current_local_meta_mutation_gen(),
gen_before_burst,
"generation must stay stable across cold singleflight burst"
);
assert_eq!(
sys.authority_disk_loads.load(Ordering::Relaxed),
1,
"16 concurrent cold authority reads must collapse into 1 disk load"
);
for bm in &results[1..] {
assert!(Arc::ptr_eq(&results[0], bm), "followers must share the leader's Arc<BucketMetadata>");
}
// Verify real store config writes to non-authority .rustfs.sys paths do NOT bump LOCAL_META_MUTATION_GEN.
let gen_before = current_local_meta_mutation_gen();
crate::config::com::save_config(ecstore.clone(), "buckets/.usage-cache.bin", b"usage-snapshot".to_vec())
.await
.expect("save root usage cache");
crate::config::com::save_config(ecstore.clone(), "buckets/.usage-cache.bin.bkp", b"usage-snapshot-bkp".to_vec())
.await
.expect("save root usage cache bkp");
assert_eq!(
current_local_meta_mutation_gen(),
gen_before,
"real usage-cache writes must not bump LOCAL_META_MUTATION_GEN"
);
let tx_uuid = Uuid::new_v4();
for inert_path in [
"unclean-shutdown".to_string(),
"buckets/.usage-cache.bin".to_string(),
"buckets/.usage-cache.bin.bkp".to_string(),
format!("buckets/.usage-cache.bin/{tx_uuid}"),
format!("buckets/{bucket}/.usage-cache.bin"),
format!("buckets/{bucket}/.usage-cache.bin.bkp"),
format!("buckets/{bucket}/.usage-cache.bin.bkp/{tx_uuid}"),
"buckets/.usage.v2.json".to_string(),
"buckets/.usage.v2.json.bkp".to_string(),
"buckets/.usage.v2.json.recovery-pending.json".to_string(),
"buckets/.usage.observed.json".to_string(),
"buckets/.usage.json".to_string(),
"buckets/.usage.json.bkp".to_string(),
"buckets/.bloomcycle.bin".to_string(),
"buckets/.compression.json".to_string(),
"buckets/.background-heal.json".to_string(),
] {
maybe_bump_local_meta_mutation_gen_for_path(crate::disk::RUSTFS_META_BUCKET, &inert_path);
assert_eq!(
current_local_meta_mutation_gen(),
gen_before,
"inert path {inert_path} must not invalidate local_authority_cache"
);
}
// Warm hit after inert writes still performs 0 additional disk loads.
let guard = acquire_bucket_metadata_transaction_read_lock_in(&ecstore.ctx, bucket)
.await
.expect("transaction read lock");
let _ = sys
.read_authoritative_metadata_from_disk_under_guard(bucket, &guard)
.await
.expect("warm cached read");
assert_eq!(sys.authority_disk_loads.load(Ordering::Relaxed), 1);
// Negative controls: authority paths and suffix-bearing bucket names MUST bump LOCAL_META_MUTATION_GEN.
for authority_path in [
format!("buckets/{bucket}/.metadata.bin"),
format!("buckets/{bucket}/.bucket-incarnation"),
format!("buckets/{bucket}/.metadata.bin/{tx_uuid}"),
"buckets/tenant.usage-cache.bin".to_string(),
format!("buckets/tenant.usage-cache.bin/{tx_uuid}"),
format!("buckets/{bucket}"),
"buckets".to_string(),
"format.json".to_string(),
] {
let before = current_local_meta_mutation_gen();
maybe_bump_local_meta_mutation_gen_for_path(crate::disk::RUSTFS_META_BUCKET, &authority_path);
assert_eq!(
current_local_meta_mutation_gen(),
before + 1,
"authority path {authority_path} must bump LOCAL_META_MUTATION_GEN"
);
}
println!("AUTHORITY_SINGLEFLIGHT_OK");
}
}
@@ -13,8 +13,6 @@
// limitations under the License.
pub(crate) use crate::services::event_notification::EventArgs;
#[cfg(test)]
pub(crate) use crate::services::event_notification::test_recorder;
use super::runtime_boundary;
@@ -89,11 +89,7 @@ impl ReplicationLifecycleBridge {
}
}
pub(crate) async fn schedule_delete(
bucket: String,
delete_object: DeletedObject,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
#[cfg(test)]
{
SCHEDULED_DELETE_OBJECTS
@@ -102,7 +98,6 @@ impl ReplicationLifecycleBridge {
.push(delete_object.clone());
}
super::replication_pool::schedule_replication_delete(DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket,
event_type: REPLICATE_INCOMING_DELETE.to_string(),
@@ -22,10 +22,6 @@ use rustfs_utils::path::path_join_buf;
use time::OffsetDateTime;
use super::replication_error_boundary::{Error, Result};
#[cfg(test)]
pub(crate) use crate::bucket::metadata_sys::{
bucket_metadata_sys_of, init_bucket_metadata_sys, set_bucket_metadata_in, test_support,
};
pub(crate) type ReplicationInstanceContext = InstanceContext;
@@ -110,16 +110,13 @@ impl ReplicationObjectBridge {
check_replicate_delete_with_snapshot(object, source, opts, source_error, snapshot)
}
/// Admits replication with the bucket identity verified by the originating mutation.
/// An absent identity suppresses external notifications; workers never infer one by name.
pub async fn schedule_object<S: ReplicationStorage>(
object: ObjectInfo,
storage: Arc<S>,
decision: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
schedule_replication(object, storage, decision, op_type, notification_bucket_incarnation).await;
schedule_replication(object, storage, decision, op_type).await;
}
pub async fn schedule_delete(delete_object: DeletedObjectReplicationInfo) {
@@ -151,16 +148,8 @@ impl ReplicationObjectBridge {
}
}
/// Schedules a committed delete with its originating bucket identity for notifications.
/// An absent identity leaves external notifications unbound.
pub async fn schedule_storage_delete(
delete_object: DeletedObject,
bucket: String,
event_type: String,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
pub async fn schedule_storage_delete(delete_object: DeletedObject, bucket: String, event_type: String) {
Self::schedule_delete(DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket,
event_type,
@@ -169,18 +158,10 @@ impl ReplicationObjectBridge {
.await;
}
/// Schedules committed deletes from one bucket instance, retaining that notification identity.
/// An absent identity leaves external notifications unbound.
pub async fn schedule_storage_deletes(
delete_objects: Vec<DeletedObject>,
bucket: String,
event_type: String,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
pub async fn schedule_storage_deletes(delete_objects: Vec<DeletedObject>, bucket: String, event_type: String) {
let delete_objects = delete_objects
.into_iter()
.map(|delete_object| DeletedObjectReplicationInfo {
notification_bucket_incarnation,
delete_object: deleted_object_for_replication(delete_object),
bucket: bucket.clone(),
event_type: event_type.clone(),
@@ -1016,9 +1016,7 @@ async fn replay_mrf_metadata_entry<S: ReplicationStorage>(
/// admitted targets, carrying over the entry's retry count.
fn admitted_mrf_replicate_object(oi: ObjectInfo, entry: &MrfReplicateEntry, op_type: ReplicationType) -> ReplicateObjectInfo {
let dsc = replicate_decision_for_admitted_targets(&entry.target_arns);
// The journal does not bind this task to a bucket instance. Keep external
// notifications unbound instead of attaching an old task to a reused name.
let mut roi = replicate_object_info_from_object_info(oi, dsc, op_type, None);
let mut roi = replicate_object_info_from_object_info(oi, dsc, op_type);
roi.retry_count = entry.retry_count.max(0) as u32;
roi
}
@@ -3173,13 +3171,12 @@ pub(crate) async fn schedule_replication<S: ReplicationStorage>(
o: Arc<S>,
dsc: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) {
let (synchronous, asynchronous) = dsc.partition_by_sync();
let mut async_oi = oi;
if synchronous.replicate_any() {
let ri = replicate_object_info_from_object_info(async_oi.clone(), synchronous, op_type, notification_bucket_incarnation);
let ri = replicate_object_info_from_object_info(async_oi.clone(), synchronous, op_type);
let state = replicate_object(ri, o.clone()).await;
async_oi.replication_status_internal = state.replication_status_internal;
async_oi.version_purge_status_internal = state.version_purge_status_internal;
@@ -3188,7 +3185,7 @@ pub(crate) async fn schedule_replication<S: ReplicationStorage>(
if asynchronous.replicate_any()
&& let Some(pool) = runtime_sources::replication_pool()
{
let ri = replicate_object_info_from_object_info(async_oi, asynchronous, op_type, notification_bucket_incarnation);
let ri = replicate_object_info_from_object_info(async_oi, asynchronous, op_type);
let _ = pool.queue_replica_task(ri).await;
}
}
@@ -3197,7 +3194,6 @@ fn replicate_object_info_from_object_info(
oi: ObjectInfo,
dsc: ReplicateDecision,
op_type: ReplicationType,
notification_bucket_incarnation: Option<uuid::Uuid>,
) -> ReplicateObjectInfo {
let tgt_statuses = replication_statuses_map(&oi.replication_status_internal.clone().unwrap_or_default());
let purge_statuses = version_purge_statuses_map(&oi.version_purge_status_internal.clone().unwrap_or_default());
@@ -3213,7 +3209,6 @@ fn replicate_object_info_from_object_info(
let checksum = if ssec { oi.checksum.clone() } else { None };
ReplicateObjectInfo {
notification_bucket_incarnation,
name: oi.name,
size: oi.size,
actual_size: asz,
@@ -3355,7 +3350,7 @@ pub async fn queue_replication_metadata(bucket: &str, oi: ObjectInfo, retry_coun
return ReplicationQueueAdmission::Skipped;
}
let mut roi = replicate_object_info_from_object_info(oi, dsc, ReplicationType::Metadata, None);
let mut roi = replicate_object_info_from_object_info(oi, dsc, ReplicationType::Metadata);
roi.retry_count = retry_count;
if let Some(pool) = runtime_sources::replication_pool() {
pool.queue_replica_task(roi).await
@@ -5210,117 +5205,6 @@ mod tests {
}
}
#[test]
fn replication_admission_keeps_original_incarnation_and_mrf_replay_does_not_guess() {
let incarnation = Uuid::new_v4();
let target = "arn:rustfs:replication:target-a";
for op_type in [ReplicationType::Object, ReplicationType::Metadata] {
let object = ObjectInfo {
bucket: "source".to_string(),
name: "object".to_string(),
version_id: Some(Uuid::new_v4()),
..Default::default()
};
let admitted = replicate_object_info_from_object_info(
object.clone(),
test_replicate_decision(&[target]),
op_type,
Some(incarnation),
);
assert_eq!(admitted.notification_bucket_incarnation, Some(incarnation));
let encoded = encode_mrf_file(&[admitted.to_mrf_entry()]).expect("encode queued replication");
let entries = decode_mrf_file(&encoded).expect("decode queued replication");
let replayed = admitted_mrf_replicate_object(object, &entries[0], op_type);
assert_eq!(
replayed.notification_bucket_incarnation, None,
"MRF replay must not infer a bucket instance from a reused name"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial_test::serial]
async fn queued_delete_notifications_keep_origin_across_bucket_recreation() {
use super::super::replication_event_sink::test_recorder;
use super::super::replication_metadata_boundary::{
bucket_metadata_sys_of, init_bucket_metadata_sys, set_bucket_metadata_in,
test_support::isolated_store_over_temp_disks,
};
use super::super::replication_storage_boundary::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
runtime_sources::set_test_object_layer(store.clone()).await;
test_recorder::install();
let bucket = "queued-delete-notification-origin";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create original bucket");
let original = store.bucket_incarnation_id(bucket).await.expect("original incarnation");
let queued = DeletedObjectReplicationInfo {
notification_bucket_incarnation: Some(original),
bucket: bucket.to_string(),
target_arn: "arn:rustfs:replication:target-a".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "original-object".to_string(),
version_id: Some(Uuid::new_v4()),
replication_state: Some(ReplicationState {
replicate_decision_str: "malformed-decision".to_string(),
..Default::default()
}),
..Default::default()
},
..Default::default()
};
let encoded = encode_mrf_file(&[queued.to_mrf_entry()]).expect("persist old delete task");
let entries = decode_mrf_file(&encoded).expect("recover old delete task");
let mut replayed = reconstructed_heal_delete_info(
&entries[0],
&ObjectInfo::default(),
&replicate_decision_for_admitted_targets(&entries[0].target_arns),
);
replayed
.delete_object
.replication_state
.as_mut()
.expect("reconstructed replication state")
.replicate_decision_str = "malformed-decision".to_string();
store
.delete_bucket(bucket, &DeleteBucketOptions::default())
.await
.expect("delete original bucket");
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create replacement bucket");
let replacement = store.bucket_incarnation_id(bucket).await.expect("replacement incarnation");
assert_ne!(original, replacement);
let sys = bucket_metadata_sys_of(&store.ctx).expect("metadata owner");
let mut metadata = (*sys.read().await.get(bucket).await.expect("replacement metadata")).clone();
metadata.notification_config_xml = br#"<NotificationConfiguration><QueueConfiguration><Id>replacement</Id><Queue>arn:rustfs:sqs:us-east-1:replacement:webhook</Queue><Event>s3:Replication:*</Event></QueueConfiguration></NotificationConfiguration>"#.to_vec();
set_bucket_metadata_in(&store.ctx, metadata)
.await
.expect("install replacement notification configuration");
assert!(!replicate_delete_with_outcome(queued, store.clone()).await);
assert!(!replicate_delete_with_outcome(replayed, store).await);
let events = test_recorder::recorded_for_bucket(bucket);
assert_eq!(events.len(), 2, "both worker failures must emit an observable local event");
assert!(
events
.iter()
.all(|event| event.object == "original-object" && event.event_name == "s3:Replication:OperationNotTracked")
);
assert_eq!(events[0].bucket_incarnation_id, Some(original));
assert_eq!(
events[1].bucket_incarnation_id, None,
"a replay without provenance must not acquire the replacement bucket's identity"
);
assert!(events.iter().all(|event| event.bucket_incarnation_id != Some(replacement)));
}
#[test]
fn replicate_object_info_from_object_info_preserves_ssec_checksum() {
let checksum = bytes::Bytes::from_static(b"ssec-checksum");
@@ -5335,7 +5219,7 @@ mod tests {
..Default::default()
};
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object, None);
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object);
assert!(ri.ssec);
assert_eq!(ri.checksum, Some(checksum));
@@ -5351,12 +5235,8 @@ mod tests {
user_tags: Arc::new("owner=a3".to_string()),
..Default::default()
};
let live = replicate_object_info_from_object_info(
object.clone(),
test_replicate_decision(&[target]),
ReplicationType::Metadata,
None,
);
let live =
replicate_object_info_from_object_info(object.clone(), test_replicate_decision(&[target]), ReplicationType::Metadata);
let persisted = live.to_mrf_entry();
let encoded = encode_mrf_file(std::slice::from_ref(&persisted)).expect("metadata MRF entry should encode");
let decoded = decode_mrf_file(&encoded).expect("metadata MRF entry should decode");
@@ -2274,7 +2274,6 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
let replication_generation = oi.replication_generation_snapshot();
Ok(ReplicateObjectInfo {
notification_bucket_incarnation: None,
name: oi.name.clone(),
size: oi.size,
actual_size,
@@ -2449,7 +2448,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Failed to parse replicate decision"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2531,7 +2529,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Failed to verify source delete-marker state before replication"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2566,7 +2563,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Skipping replication delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2597,7 +2593,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Skipping replication delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2697,7 +2692,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
"Replication resync task failed"
);
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -2806,7 +2800,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
{
Ok(object) => {
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object,
@@ -2832,7 +2825,6 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
);
}
send_event(EventArgs {
bucket_incarnation_id: dobj.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3164,7 +3156,6 @@ async fn purge_stale_delete_marker_targets(bucket: &str, dobj: &DeletedObjectRep
}
async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &DeletedObjectReplicationInfo, storage: Arc<S>) -> bool {
let incarnation_id = dobj.notification_bucket_incarnation;
let bucket = &dobj.bucket;
let object_name = &dobj.delete_object.object_name;
let admitted_target_arns = dobj.admitted_target_arns();
@@ -3185,7 +3176,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because replication config is missing"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3209,7 +3199,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because replication config lookup failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3244,7 +3233,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3273,7 +3261,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3321,7 +3308,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete because target client is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3352,7 +3338,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Skipping replication force-delete"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationFailed.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -3389,7 +3374,6 @@ async fn replicate_force_delete_to_targets<S: ReplicationStorage>(dobj: &Deleted
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationFailed.to_string(),
bucket_name: bucket.clone(),
object: ObjectInfo {
@@ -4253,7 +4237,6 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Skipping replication object"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4277,7 +4260,6 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Skipping replication object"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4344,7 +4326,6 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
"Replication resync task failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: roi.to_object_info(),
@@ -4489,7 +4470,6 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
if publication.emit_event {
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name,
bucket_name: bucket.clone(),
object: object_info,
@@ -4632,7 +4612,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4648,7 +4627,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo)
else {
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4692,7 +4670,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -4724,7 +4701,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4750,7 +4726,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Skipping replication object target"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4882,7 +4857,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -4911,7 +4885,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: object_info,
@@ -5009,7 +4982,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo)
else {
send_local_event(EventArgs {
bucket_incarnation_id: self.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.clone(),
object: self.to_object_info(),
@@ -5043,7 +5015,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let size = match object_info.get_actual_size() {
Ok(size) => size,
Err(e) => {
note_replicate_all_size_unavailable(&bucket, &tgt_client, object_info, &e, self.notification_bucket_incarnation);
note_replicate_all_size_unavailable(&bucket, &tgt_client, object_info, &e);
return rinfo;
}
};
@@ -5052,7 +5024,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let transfer_size = if self.ssec { object_info.size } else { size };
if tgt_client.bucket.is_empty() {
note_replicate_all_target_bucket_empty(&bucket, &tgt_client, object_info, self.notification_bucket_incarnation);
note_replicate_all_target_bucket_empty(&bucket, &tgt_client, object_info);
return rinfo;
}
@@ -5098,15 +5070,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
let (put_opts, is_multipart) = match replication_put_object_options_for_target(&tgt_client, &object_info) {
Ok((put_opts, is_mp)) => (put_opts, is_mp),
Err(e) => {
fail_replicate_all_put_options(
&mut rinfo,
&tgt_client,
&bucket,
object_info,
&e,
start_time,
self.notification_bucket_incarnation,
);
fail_replicate_all_put_options(&mut rinfo, &tgt_client, &bucket, object_info, &e, start_time);
return rinfo;
}
};
@@ -5210,7 +5174,6 @@ fn note_replicate_all_target_offline(roi: &ReplicateObjectInfo, bucket: &str, tg
"Skipped replication because target is offline"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: roi.to_object_info(),
@@ -5249,7 +5212,6 @@ fn note_replicate_all_reader_unavailable(roi: &ReplicateObjectInfo, bucket: &str
"Skipped replication because object reader is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: roi.to_object_info(),
@@ -5261,13 +5223,7 @@ fn note_replicate_all_reader_unavailable(roi: &ReplicateObjectInfo, bucket: &str
/// Log and notify that replication was skipped because the actual object size
/// is unavailable.
fn note_replicate_all_size_unavailable(
bucket: &str,
tgt_client: &TargetClient,
object_info: ObjectInfo,
e: &std::io::Error,
incarnation_id: Option<uuid::Uuid>,
) {
fn note_replicate_all_size_unavailable(bucket: &str, tgt_client: &TargetClient, object_info: ObjectInfo, e: &std::io::Error) {
debug!(
event = EVENT_RESYNC_RUNTIME_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
@@ -5280,7 +5236,6 @@ fn note_replicate_all_size_unavailable(
"Skipped replication because actual object size is unavailable"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5291,12 +5246,7 @@ fn note_replicate_all_size_unavailable(
/// Log and notify that replication was skipped because the target bucket is
/// empty.
fn note_replicate_all_target_bucket_empty(
bucket: &str,
tgt_client: &TargetClient,
object_info: ObjectInfo,
incarnation_id: Option<uuid::Uuid>,
) {
fn note_replicate_all_target_bucket_empty(bucket: &str, tgt_client: &TargetClient, object_info: ObjectInfo) {
debug!(
event = EVENT_RESYNC_RUNTIME_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
@@ -5308,7 +5258,6 @@ fn note_replicate_all_target_bucket_empty(
"Skipped replication because target bucket is empty"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5422,7 +5371,6 @@ async fn resolve_replicate_all_action(
"Skipping replication because newer target version exists"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info.clone(),
@@ -5546,7 +5494,6 @@ async fn resolve_replicate_all_action(
"Failed replication head-object fallback"
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5579,7 +5526,6 @@ async fn resolve_replicate_all_action(
);
send_local_event(EventArgs {
bucket_incarnation_id: roi.notification_bucket_incarnation,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -5608,7 +5554,6 @@ fn fail_replicate_all_put_options(
object_info: ObjectInfo,
e: &Error,
start_time: OffsetDateTime,
incarnation_id: Option<uuid::Uuid>,
) {
rinfo.replication_status = ReplicationStatusType::Failed;
rinfo.error = Some(e.to_string());
@@ -5624,7 +5569,6 @@ fn fail_replicate_all_put_options(
"Replication target operation failed"
);
send_local_event(EventArgs {
bucket_incarnation_id: incarnation_id,
event_name: EventName::ObjectReplicationNotTracked.to_string(),
bucket_name: bucket.to_string(),
object: object_info,
@@ -24,8 +24,6 @@ pub(crate) use crate::object_api::{
};
#[cfg(test)]
pub(crate) use crate::object_api::{NamespaceLockFence, NamespaceLockSignalTestFence};
#[cfg(test)]
pub(crate) use crate::storage_api_contracts::bucket::{BucketOperations, DeleteBucketOptions, MakeBucketOptions};
pub(crate) use crate::storage_api_contracts::list::{
ListOperations, StorageListObjectVersionsInfo, StorageListObjectsV2Info, StorageObjectInfoOrErr, StorageWalkOptions,
};
@@ -18,8 +18,6 @@ use super::replication_bandwidth_boundary::ReplicationBucketMonitor;
use super::replication_pool::DynReplicationPool;
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::ReplicationObjectStore;
#[cfg(test)]
pub(crate) use crate::runtime::global::set_object_layer as set_test_object_layer;
use crate::runtime::sources;
pub use crate::runtime::sources::{
ScannerDirtyUsageMutationObserver, ScannerDirtyUsageMutationSource, set_scanner_dirty_usage_mutation_observer,
+2 -18
View File
@@ -145,22 +145,6 @@ pub async fn node_service_time_out_client_for_class(
) -> Result<NodeServiceClient<InterceptedService<AuthenticatedChannel, TonicInterceptor>>, Box<dyn Error>> {
let interceptor = interceptor.with_rpc_audience(addr)?;
let channel = get_internode_channel_for_class(addr, class).await?;
Ok(node_client_on_channel(channel, interceptor))
}
pub(crate) async fn staged_shard_verification_client(
addr: &str,
interceptor: TonicInterceptor,
) -> Result<NodeServiceClient<InterceptedService<AuthenticatedChannel, TonicInterceptor>>, Box<dyn Error>> {
let interceptor = interceptor.with_rpc_audience(addr)?;
let channel = rustfs_protos::staged_shard_verification_channel(addr).await?;
Ok(node_client_on_channel(channel, interceptor))
}
fn node_client_on_channel(
channel: rustfs_protos::InternodeChannel,
interceptor: TonicInterceptor,
) -> NodeServiceClient<InterceptedService<AuthenticatedChannel, TonicInterceptor>> {
let connection_state = channel.connection_state();
let interceptor = interceptor.with_connection_state(connection_state.clone());
@@ -170,9 +154,9 @@ fn node_client_on_channel(
interceptor.replay_scope_audience(),
connection_state,
);
NodeServiceClient::with_interceptor(channel, interceptor)
Ok(NodeServiceClient::with_interceptor(channel, interceptor)
.max_decoding_message_size(max_message_size)
.max_encoding_message_size(max_message_size)
.max_encoding_message_size(max_message_size))
}
/// Build an eligible request client and capture its peer capability exactly once for this RPC.
@@ -294,11 +294,6 @@ pub struct NsScannerCapabilityRequest {
/// in `crates/ecstore/docs/internode-transport/`.
#[async_trait]
pub trait InternodeDataTransport: Send + Sync + std::fmt::Debug {
/// Whether shard reads must declare a nonzero byte limit.
fn requires_bounded_reads(&self) -> bool {
false
}
async fn open_read(&self, request: ReadStreamRequest) -> Result<FileReader>;
async fn open_read_fresh(&self, request: ReadStreamRequest) -> Result<FileReader> {
self.open_read(request).await
@@ -2749,6 +2744,8 @@ mod tests {
for configured in KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS {
let transport = build_internode_data_transport(Some(configured)).unwrap();
// NIXL builds everywhere and serves reads over TCP/HTTP until a node
// installs its receive pool; every other known name is the TCP transport.
let expected = if *configured == INTERNODE_DATA_TRANSPORT_NIXL {
INTERNODE_DATA_TRANSPORT_NIXL
} else {
+60 -103
View File
@@ -24,8 +24,8 @@
//! run per stream so request latency overlaps the transfers.
//!
//! UCX addresses ports by LID or GID, so this works on InfiniBand rails that
//! have no IP addresses. Shard reads and writes require NIXL. Directory walks
//! and scanner requests use the control transport.
//! have no IP addresses. Writes, walks and any stream whose first chunk cannot
//! be served this way use the TCP/HTTP transport.
//!
//! Buffer safety: the serving node may still write into a buffer whose request
//! was abandoned (a dropped reader, chunks past the end of the file). Such
@@ -83,6 +83,7 @@ pub const NIXL_BYTES_HEADER: &str = "x-rustfs-nixl-bytes";
pub const ABANDONED_BUFFER_HOLD: Duration = Duration::from_secs(120);
/// Request timeout when the caller sets no stall timeout.
const DEFAULT_CHUNK_TIMEOUT: Duration = Duration::from_secs(60);
const EVENT_NIXL_INTERNODE_FALLBACK: &str = "nixl_internode_fallback";
const LOG_COMPONENT_INTERNODE: &str = "internode";
const LOG_SUBSYSTEM_NIXL: &str = "nixl";
@@ -124,7 +125,8 @@ fn recv_pool() -> Option<Arc<dyn NixlRecvPool>> {
RECV_POOL.get().cloned()
}
/// Internode transport for NIXL shard data and TCP/HTTP control requests.
/// Internode transport that reads shard streams over NIXL and delegates
/// everything else to TCP/HTTP.
#[derive(Debug)]
pub struct NixlInternodeDataTransport {
tcp: TcpHttpInternodeDataTransport,
@@ -139,36 +141,72 @@ impl NixlInternodeDataTransport {
}
}
async fn open_nixl(&self, request: ReadStreamRequest) -> Result<NixlChunkReader> {
/// A NIXL chunk reader for `request` with its first chunk already landed,
/// or `None` when this read should use TCP/HTTP.
async fn open_nixl(&self, request: &ReadStreamRequest) -> Option<NixlChunkReader> {
let pool = recv_pool()?;
if request.length == 0 {
return Err(io::Error::new(io::ErrorKind::Unsupported, "NIXL shard reads require a bounded range").into());
// Unbounded reads need the file size; TCP/HTTP streams them.
return None;
}
let pool = recv_pool().ok_or_else(|| io::Error::other("NIXL receive pool unavailable"))?;
let mut reader = NixlChunkReader::new(pool, request, self.depth);
if let Some(first) = futures::future::poll_fn(|cx| reader.state_mut().poll_chunk(cx, usize::MAX)).await? {
reader.state_mut().current = first;
let mut reader = NixlChunkReader::new(pool, request.clone(), self.depth);
match futures::future::poll_fn(|cx| reader.state_mut().poll_chunk(cx, usize::MAX)).await {
Ok(Some(first)) => {
reader.state_mut().current = first;
Some(reader)
}
Ok(None) => Some(reader),
Err(error) => {
debug!(
event = EVENT_NIXL_INTERNODE_FALLBACK,
component = LOG_COMPONENT_INTERNODE,
subsystem = LOG_SUBSYSTEM_NIXL,
result = "fallback",
endpoint = %request.endpoint,
error = %error,
"nixl internode read fell back to tcp"
);
None
}
}
Ok(reader)
}
}
#[async_trait]
impl InternodeDataTransport for NixlInternodeDataTransport {
fn requires_bounded_reads(&self) -> bool {
true
async fn open_read(&self, request: ReadStreamRequest) -> Result<FileReader> {
match self.open_nixl(&request).await {
Some(reader) => Ok(Box::new(reader)),
None => self.tcp.open_read(request).await,
}
}
async fn open_read(&self, request: ReadStreamRequest) -> Result<FileReader> {
Ok(Box::new(self.open_nixl(request).await?))
async fn open_read_fresh(&self, request: ReadStreamRequest) -> Result<FileReader> {
match self.open_nixl(&request).await {
Some(reader) => Ok(Box::new(reader)),
None => self.tcp.open_read_fresh(request).await,
}
}
async fn open_read_chunks(&self, request: ReadStreamRequest) -> Result<Option<ChunkReaderBox>> {
Ok(Some(Box::new(self.open_nixl(request).await?)))
match self.open_nixl(&request).await {
Some(reader) => Ok(Some(Box::new(reader))),
None => self.tcp.open_read_chunks(request).await,
}
}
async fn open_read_chunks_fresh(&self, request: ReadStreamRequest) -> Result<Option<ChunkReaderBox>> {
match self.open_nixl(&request).await {
Some(reader) => Ok(Some(Box::new(reader))),
None => self.tcp.open_read_chunks_fresh(request).await,
}
}
async fn open_write(&self, request: WriteStreamRequest) -> Result<FileWriter> {
let pool = recv_pool().ok_or_else(|| io::Error::other("NIXL receive pool unavailable"))?;
Ok(Box::new(NixlFileWriter::new(pool, request)))
match recv_pool() {
Some(pool) => Ok(Box::new(NixlFileWriter::new(pool, request))),
None => self.tcp.open_write(request).await,
}
}
async fn open_walk_dir(&self, request: WalkDirStreamRequest) -> Result<FileReader> {
@@ -192,10 +230,7 @@ impl InternodeDataTransport for NixlInternodeDataTransport {
}
fn capabilities(&self) -> InternodeDataTransportCapabilities {
InternodeDataTransportCapabilities {
fallback_supported: false,
..InternodeDataTransportCapabilities::tcp_http()
}
InternodeDataTransportCapabilities::tcp_http()
}
}
@@ -255,17 +290,7 @@ async fn fetch_chunk(pool: Arc<dyn NixlRecvPool>, request: ReadStreamRequest, ti
.map_err(|_| io::Error::other("nixl agent metadata is not a header value"))?,
);
build_auth_headers(&url, &Method::GET, &mut headers)?;
let (status, response_headers, body) = rustfs_rio::internode_http_request(&url, Method::GET, headers, Some(timeout)).await?;
finish_read_chunk(buffer, request.length, status, &response_headers, &body)
}
fn finish_read_chunk(
buffer: LentBuffer,
requested: usize,
status: http::StatusCode,
response_headers: &http::HeaderMap,
body: &[u8],
) -> io::Result<(usize, Bytes)> {
let (status, response_headers, _) = rustfs_rio::internode_http_request(&url, Method::GET, headers, Some(timeout)).await?;
if !status.is_success() {
debug!(
component = LOG_COMPONENT_INTERNODE,
@@ -274,18 +299,6 @@ fn finish_read_chunk(
status = status.as_u16(),
"nixl internode read refused by peer"
);
if status == http::StatusCode::NOT_FOUND {
// A missing route also returns 404. Only the disk marker or the legacy file response identifies a missing shard.
// RUSTFS_COMPAT_TODO(9526): Older peers report a missing file in the body. Remove after all supported peers send the disk error header.
let missing = match response_headers.get(rustfs_rio::INTERNODE_DISK_ERROR_HEADER) {
Some(marker) => marker == rustfs_rio::INTERNODE_FILE_NOT_FOUND,
None => body == b"file not found",
};
if missing {
buffer.release();
return Err(crate::disk::error::DiskError::FileNotFound.into());
}
}
return Err(io::Error::other("nixl internode read refused by peer"));
}
let landed = response_headers
@@ -293,10 +306,10 @@ fn finish_read_chunk(
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<usize>().ok())
.ok_or_else(|| io::Error::other("nixl internode read reply lacks the byte count"))?;
if landed > requested {
if landed > request.length {
return Err(io::Error::other("nixl internode read reports more bytes than requested"));
}
Ok((requested, buffer.complete(landed)?))
Ok((request.length, buffer.complete(landed)?))
}
type ChunkFuture = BoxFuture<'static, io::Result<(usize, Bytes)>>;
@@ -649,35 +662,11 @@ impl tokio::io::AsyncWrite for NixlFileWriter {
}
}
#[cfg(test)]
pub(crate) mod read_test_support;
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
#[tokio::test]
async fn strict_nixl_rejects_unbounded_reads() {
let request = ReadStreamRequest {
endpoint: String::new(),
disk: String::new(),
volume: String::new(),
path: String::new(),
offset: 0,
length: 0,
stall_timeout: None,
};
let transport = NixlInternodeDataTransport::from_env();
let error = transport
.open_read_chunks_fresh(request)
.await
.err()
.expect("unbounded shard read must fail");
assert!(error.to_string().contains("NIXL shard reads require a bounded range"));
assert!(!transport.capabilities().fallback_supported);
}
struct CountingBuffer {
released: Arc<AtomicUsize>,
}
@@ -727,7 +716,7 @@ mod tests {
}
}
pub(super) struct VecPool;
struct VecPool;
impl NixlRecvPool for VecPool {
fn agent_name(&self) -> &str {
@@ -908,38 +897,6 @@ mod tests {
}
}
#[tokio::test(start_paused = true)]
async fn only_confirmed_missing_shards_release_the_buffer_on_refusal() {
for (marker, body, confirmed) in [
(Some("file-not-found"), &b""[..], true),
(None, &b"file not found"[..], true),
(Some("other"), &b"file not found"[..], false),
(None, &b"no such route"[..], false),
] {
let released = Arc::new(AtomicUsize::new(0));
let buffer = LentBuffer {
buffer: Some(Box::new(CountingBuffer {
released: released.clone(),
})),
};
let mut headers = http::HeaderMap::new();
if let Some(marker) = marker {
headers.insert(rustfs_rio::INTERNODE_DISK_ERROR_HEADER, HeaderValue::from_static(marker));
}
let error = finish_read_chunk(buffer, 8, http::StatusCode::NOT_FOUND, &headers, body).expect_err("refused read");
assert_eq!(
matches!(
error
.get_ref()
.and_then(|err| err.downcast_ref::<crate::disk::error::DiskError>()),
Some(crate::disk::error::DiskError::FileNotFound)
),
confirmed
);
assert_eq!(released.load(Ordering::SeqCst), usize::from(confirmed));
}
}
#[tokio::test(start_paused = true)]
async fn abandoned_buffers_return_only_after_the_hold() {
let released = Arc::new(AtomicUsize::new(0));
@@ -1,84 +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.
use super::{NixlChunkReader, ReadStreamRequest, tests::VecPool};
use crate::cluster::rpc::{internode_data_transport::InternodeDataTransport, remote_disk::RemoteDisk};
use crate::disk::{Disk, DiskOption, DiskStore, endpoint::Endpoint};
use rustfs_rio::ChunkReaderBox;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use url::Url;
/// Serve a single response over HTTP/1.1 and return the request URI for assertions.
pub(crate) async fn read_peer(response: Vec<u8>) -> (Endpoint, JoinHandle<Url>) {
crate::runtime::sources::ensure_test_rpc_secret();
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind loopback peer");
let address = listener.local_addr().expect("peer address");
let url = Url::parse(&format!("http://{address}/disk")).expect("disk URL");
let endpoint = Endpoint {
url: url.clone(),
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx: 0,
};
let peer = tokio::spawn(async move {
let (mut socket, _) = tokio::time::timeout(std::time::Duration::from_secs(10), listener.accept())
.await
.expect("peer received a request")
.expect("accept read");
let mut lines = BufReader::new(&mut socket).lines();
let request = lines.next_line().await.expect("request line").expect("request");
let target = request.split_whitespace().nth(1).expect("request target");
while !lines
.next_line()
.await
.expect("read headers")
.expect("header terminator")
.is_empty()
{}
socket.write_all(&response).await.expect("send response");
url.join(target).expect("request URI")
});
(endpoint, peer)
}
pub(crate) async fn remote_disk(endpoint: &Endpoint, transport: Arc<dyn InternodeDataTransport>) -> DiskStore {
let disk = RemoteDisk::new(
endpoint,
&DiskOption {
cleanup: false,
health_check: false,
},
transport,
)
.await
.expect("create remote disk");
Arc::new(Disk::Remote(Box::new(disk)))
}
pub(crate) fn nixl_reader(endpoint: &Endpoint, length: usize) -> ChunkReaderBox {
let request = ReadStreamRequest {
endpoint: endpoint.grid_host(),
disk: "disk".to_owned(),
volume: "bucket".to_owned(),
path: "part.1".to_owned(),
offset: 0,
length,
stall_timeout: None,
};
Box::new(NixlChunkReader::new(Arc::new(VecPool), request, 1))
}
@@ -21,7 +21,7 @@ use crate::cluster::rpc::{set_tonic_canonical_body_digest, set_tonic_mutation_bo
use crate::error::{Error, Result};
use crate::storage_api_contracts::internode::{
SCANNER_ACTIVITY_LEGACY_PROTOCOL_VERSION, SCANNER_ACTIVITY_PREVIOUS_PROTOCOL_VERSION, SCANNER_ACTIVITY_PROTOCOL_VERSION,
SCANNER_ACTIVITY_V6_PROTOCOL_VERSION, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES,
SCANNER_ACTIVITY_V6_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES,
SCANNER_DIRTY_USAGE_SNAPSHOT_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_RPC_MAX_MESSAGE_SIZE,
};
use crate::{
@@ -192,7 +192,6 @@ fn validate_signal_service_protocol(sig: u64, sub_sys: &str, protocol_version: u
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScannerPeerActivity {
pub instance_id: String,
pub checkpoint_instance_id: Option<String>,
pub namespace_generation: u64,
pub maintenance_generation: u64,
pub protocol_version: u32,
@@ -355,9 +354,6 @@ fn decode_scanner_activity_with_verifier(
challenge: &[u8; 16],
verify_proof: impl FnOnce(&[u8], &[u8]) -> Result<()>,
) -> Result<ScannerPeerActivity> {
if response.protocol_version != SCANNER_ACTIVITY_PROTOCOL_VERSION && response.checkpoint_instance_id.is_some() {
return Err(Error::other("legacy scanner activity peer returned unauthenticated checkpoint identity"));
}
let instance_id = &response.instance_id;
if !scanner_instance_id_is_valid(instance_id) {
return Err(Error::other("peer returned an invalid scanner activity instance ID"));
@@ -427,7 +423,7 @@ fn decode_scanner_activity_with_verifier(
None,
)
}
SCANNER_ACTIVITY_V7_PROTOCOL_VERSION | SCANNER_ACTIVITY_PROTOCOL_VERSION => {
SCANNER_ACTIVITY_PROTOCOL_VERSION => {
if response.dirty_usage_pending && response.dirty_usage_generation == 0 {
return Err(Error::other("scanner activity peer returned pending dirty usage without a generation"));
}
@@ -440,20 +436,8 @@ fn decode_scanner_activity_with_verifier(
if movement_generation == u64::MAX {
return Err(Error::other("scanner activity peer exhausted its movement generation"));
}
let canonical = if response.protocol_version == SCANNER_ACTIVITY_PROTOCOL_VERSION {
let instance = response
.checkpoint_instance_id
.as_deref()
.filter(|instance| scanner_instance_id_is_valid(instance))
.ok_or_else(|| Error::other("scanner activity peer omitted its checkpoint identity"))?;
if instance.bytes().all(|byte| byte == b'0') {
return Err(Error::other("scanner activity peer returned an empty checkpoint identity"));
}
rustfs_protos::canonical_scanner_activity_v8_response_body(challenge, &response)
} else {
rustfs_protos::canonical_scanner_activity_v7_response_body(challenge, &response)
}
.map_err(|_| Error::other("scanner activity peer response is too large to authenticate"))?;
let canonical = rustfs_protos::canonical_scanner_activity_v7_response_body(challenge, &response)
.map_err(|_| Error::other("scanner activity peer response is too large to authenticate"))?;
verify_proof(&canonical, &response.response_proof)?;
(
Some(
@@ -474,7 +458,6 @@ fn decode_scanner_activity_with_verifier(
};
Ok(ScannerPeerActivity {
instance_id: response.instance_id,
checkpoint_instance_id: response.checkpoint_instance_id,
namespace_generation: response.namespace_generation,
maintenance_generation: response.maintenance_generation,
protocol_version: response.protocol_version,
@@ -2469,15 +2452,11 @@ impl PeerRestClient {
.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_PROTOCOL_VERSION)
.await;
if result.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
let previous = self
.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION)
.await;
if previous.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
self.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
.await
} else {
previous
}
// A v6 peer cannot parse the v7 marker. Its authenticated
// response is still decoded as untrusted terminal state, so the
// scanner will defer publication until every peer is v7.
self.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
.await
} else {
result
}
@@ -2744,15 +2723,8 @@ impl PeerRestClient {
.scanner_activity_request_with_protocol(instance_id.clone(), generation, SCANNER_ACTIVITY_PROTOCOL_VERSION)
.await;
if result.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
let previous = self
.scanner_activity_request_with_protocol(instance_id.clone(), generation, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION)
.await;
if previous.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
self.scanner_activity_request_with_protocol(instance_id, generation, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
.await
} else {
previous
}
self.scanner_activity_request_with_protocol(instance_id, generation, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
.await
} else {
result
}
@@ -3708,7 +3680,6 @@ mod tests {
#[test]
fn scanner_scoped_dirty_usage_ack_reconciliation_requires_same_clean_instance() {
let activity = |instance_id: &str, generation, pending| ScannerPeerActivity {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: instance_id.to_string(),
namespace_generation: 1,
maintenance_generation: 1,
@@ -3990,44 +3961,9 @@ mod tests {
.await;
}
#[test]
fn scanner_checkpoint_identity_requires_v8_proof_and_preserves_rpc_epoch() {
let response = ScannerActivityResponse {
protocol_version: SCANNER_ACTIVITY_PROTOCOL_VERSION,
instance_id: "1".repeat(32),
checkpoint_instance_id: Some("2".repeat(32)),
topology_digest: vec![7; 32].into(),
movement_generation: Some(0),
publication_blocked: Some(false),
response_proof: b"proof".to_vec().into(),
..Default::default()
};
let decoded = decode_test_scanner_activity(response.clone()).expect("authenticated v8");
assert_eq!(decoded.instance_id, "1".repeat(32));
assert_eq!(decoded.checkpoint_instance_id, Some("2".repeat(32)));
for checkpoint_instance_id in [None, Some(String::new()), Some("0".repeat(32)), Some("A".repeat(32))] {
let malformed = ScannerActivityResponse {
checkpoint_instance_id,
..response.clone()
};
assert!(decode_test_scanner_activity(malformed).is_err(), "invalid continuity must fail closed");
}
let v7 = ScannerActivityResponse {
protocol_version: SCANNER_ACTIVITY_V7_PROTOCOL_VERSION,
..response
};
assert!(decode_test_scanner_activity(v7.clone()).is_err(), "legacy proof does not bind continuity");
let v7 = ScannerActivityResponse {
checkpoint_instance_id: None,
..v7
};
assert!(decode_test_scanner_activity(v7).is_ok(), "v7 without continuity remains supported");
}
#[test]
fn scanner_activity_requires_restart_safe_peer_identity() {
let legacy = decode_test_scanner_activity(ScannerActivityResponse {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4044,7 +3980,6 @@ mod tests {
assert_eq!(
legacy,
ScannerPeerActivity {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4059,7 +3994,6 @@ mod tests {
);
let previous = decode_test_scanner_activity(ScannerActivityResponse {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4076,7 +4010,6 @@ mod tests {
assert_eq!(
previous,
ScannerPeerActivity {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4091,7 +4024,6 @@ mod tests {
);
let v6 = decode_test_scanner_activity(ScannerActivityResponse {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4110,7 +4042,6 @@ mod tests {
assert_eq!(v6.dirty_usage_generation, Some(11));
let malformed_topology = ScannerActivityResponse {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4131,7 +4062,6 @@ mod tests {
);
let missing_instance = ScannerActivityResponse {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: String::new(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4152,7 +4082,6 @@ mod tests {
);
let malformed_instance = ScannerActivityResponse {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: "ABCDEF0123456789ABCDEF0123456789".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4173,7 +4102,6 @@ mod tests {
);
let activity = decode_test_scanner_activity(ScannerActivityResponse {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4190,7 +4118,6 @@ mod tests {
assert_eq!(
activity,
ScannerPeerActivity {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4205,7 +4132,6 @@ mod tests {
);
let missing_movement_generation = ScannerActivityResponse {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4226,7 +4152,6 @@ mod tests {
);
let pending_without_generation = ScannerActivityResponse {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4247,7 +4172,6 @@ mod tests {
);
let previous_with_dirty_usage = ScannerActivityResponse {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4268,7 +4192,6 @@ mod tests {
);
let legacy_with_topology = ScannerActivityResponse {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4289,7 +4212,6 @@ mod tests {
);
let unsupported_protocol = ScannerActivityResponse {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
@@ -4310,7 +4232,6 @@ mod tests {
);
let missing_proof = ScannerActivityResponse {
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 7,
maintenance_generation: 3,
+64 -259
View File
@@ -1932,50 +1932,6 @@ impl RemoteDisk {
}
}
pub(crate) async fn read_format_control(&self, volume: &str, path: &str) -> Result<FileReader> {
if self.data_transport.requires_bounded_reads() {
let control = Arc::new(super::internode_data_transport::TcpHttpInternodeDataTransport);
return self.open_file_range(control, volume, path, 0, 0).await;
}
self.read_file(volume, path).await
}
async fn open_file_range(
&self,
transport: Arc<dyn InternodeDataTransport>,
volume: &str,
path: &str,
offset: usize,
length: usize,
) -> Result<FileReader> {
if self.health.is_faulty() {
return Err(DiskError::FaultyDisk);
}
let disk = self.disk_ref().await;
let timeouts = remote_read_timeouts(get_object_disk_read_timeout());
let request = ReadStreamRequest {
endpoint: self.endpoint.grid_host(),
disk,
volume: volume.to_string(),
path: path.to_string(),
offset,
length,
stall_timeout: timeouts.body_stall,
};
#[cfg(feature = "internode-transport")]
if self.external_streams {
return transport.open_read(request).await;
}
let reader = Self::open_read_with_retry(transport.as_ref(), request.clone()).await?;
Ok(Box::new(RetryingRemoteReader::new_with_timeouts(
reader,
transport,
request,
timeouts.initial_read,
timeouts.recovery,
)))
}
/// Open a remote read stream with a bounded retry on transient transport failures, mirroring
/// [`Self::open_write_with_retry`]. A freshly-committed object exists on only `write_quorum`
/// disks until background heal reconstructs the rest, so a single transient network error
@@ -1983,16 +1939,16 @@ impl RemoteDisk {
/// window can drop the readable-shard count below `data_shards` and surface as a spurious
/// `InsufficientReadQuorum`. Opening the stream is idempotent, so re-dialing once absorbs the
/// transient failure instead of eroding quorum. See issue #2761.
async fn open_read_with_retry(transport: &dyn InternodeDataTransport, request: ReadStreamRequest) -> Result<FileReader> {
async fn open_read_with_retry(&self, request: ReadStreamRequest) -> Result<FileReader> {
let mut attempt = 1;
let mut last_retry_classification = None;
loop {
// The second attempt bypasses the pool. The first failure is often a
// stale kept-alive connection to a peer that just restarted.
let opened = if attempt == 1 {
transport.open_read(request.clone()).await
self.data_transport.open_read(request.clone()).await
} else {
transport.open_read_fresh(request.clone()).await
self.data_transport.open_read_fresh(request.clone()).await
};
match opened {
Ok(reader) => {
@@ -2823,75 +2779,6 @@ impl RemoteDisk {
.map_err(|err| Error::RemoteClientUnavailable(err.to_string()))
}
pub(crate) async fn verify_staged_part(&self, directory: &str, fi: &FileInfo, encoded_size: usize) -> Result<CheckPartsResp> {
// The reply arrives after the complete disk scan. A fixed control-RPC
// deadline would reject healthy large shards even while reads progress.
let scan_seconds = u64::try_from(encoded_size)
.map_err(Error::other)?
.div_ceil(rustfs_config::DEFAULT_OBJECT_BYTES_PER_SECOND);
let base = get_max_timeout_duration();
// gRPC encodes deadlines with at most eight digits and hours as its largest unit.
let timeout = if base.is_zero() {
Duration::ZERO
} else {
base.saturating_add(Duration::from_secs(scan_seconds))
.min(Duration::from_secs(99_999_999 * 3600))
};
self.verify_file_rpc(crate::disk::RUSTFS_META_TMP_BUCKET, directory, fi, Some(timeout))
.await
}
async fn verify_file_rpc(
&self,
volume: &str,
path: &str,
fi: &FileInfo,
scan_timeout: Option<Duration>,
) -> Result<CheckPartsResp> {
self.execute_with_timeout_for_op(
"verify_file",
|| async {
let file_info = serde_json::to_string(fi)?;
let mut client = if scan_timeout.is_some() {
if let Some(err) = self.offline_bypass_error() {
return Err(err);
}
super::client::staged_shard_verification_client(
&self.addr,
TonicInterceptor::Signature(gen_tonic_signature_interceptor()),
)
.await
.map_err(|err| Error::RemoteClientUnavailable(err.to_string()))?
} else {
self.get_client().await?
};
let mut request = Request::new(VerifyFileRequest {
disk: self.endpoint.to_string(),
volume: volume.to_string(),
path: path.to_string(),
file_info,
});
if let Some(timeout) = scan_timeout.filter(|duration| !duration.is_zero()) {
request.set_timeout(timeout);
}
let response = client.verify_file(request).await?.into_inner();
if let Some(error) = response.error {
return Err(error.into());
}
if !response.success {
return Err(Error::other("peer failed file verification without an error"));
}
let check_parts_resp = serde_json::from_str::<CheckPartsResp>(&response.check_parts_resp)?;
Ok(check_parts_resp)
},
scan_timeout.unwrap_or_else(get_max_timeout_duration),
)
.await
}
async fn get_client_with_msgpack_policy(&self) -> Result<(NodeRpcClient, MsgpackSendPolicy)> {
if let Some(err) = self.offline_bypass_error() {
return Err(err);
@@ -5074,8 +4961,41 @@ impl DiskAPI for RemoteDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn read_file_stream(&self, volume: &str, path: &str, offset: usize, length: usize) -> Result<FileReader> {
self.open_file_range(self.data_transport.clone(), volume, path, offset, length)
.await
// warn!(
// "disk remote read_file_stream {}/{}/{} offset={} length={}",
// self.endpoint.to_string(),
// volume,
// path,
// offset,
// length
// );
if self.health.is_faulty() {
return Err(DiskError::FaultyDisk);
}
let disk = self.disk_ref().await;
let timeouts = remote_read_timeouts(get_object_disk_read_timeout());
let request = ReadStreamRequest {
endpoint: self.endpoint.grid_host(),
disk,
volume: volume.to_string(),
path: path.to_string(),
offset,
length,
stall_timeout: timeouts.body_stall,
};
#[cfg(feature = "internode-transport")]
if self.external_streams {
return self.data_transport.open_read(request).await;
}
let reader = self.open_read_with_retry(request.clone()).await?;
Ok(Box::new(RetryingRemoteReader::new_with_timeouts(
reader,
Arc::clone(&self.data_transport),
request,
timeouts.initial_read,
timeouts.recovery,
)))
}
async fn read_file_stream_chunks(
@@ -5569,7 +5489,30 @@ impl DiskAPI for RemoteDisk {
"Remote disk RPC started"
);
self.verify_file_rpc(volume, path, fi, None).await
self.execute_with_timeout(
|| async {
let file_info = serde_json::to_string(&fi)?;
let mut client = self.get_client().await?;
let request = Request::new(VerifyFileRequest {
disk: self.endpoint.to_string(),
volume: volume.to_string(),
path: path.to_string(),
file_info,
});
let response = client.verify_file(request).await?.into_inner();
if !response.success {
return Err(response.error.unwrap_or_default().into());
}
let check_parts_resp = serde_json::from_str::<CheckPartsResp>(&response.check_parts_resp)?;
Ok(check_parts_resp)
},
get_max_timeout_duration(),
)
.await
}
#[tracing::instrument(level = "trace", skip_all)]
@@ -5924,9 +5867,6 @@ impl DiskAPI for RemoteDisk {
}
}
#[cfg(test)]
pub(crate) use tests::{with_lost_staged_shard_peer, with_staged_part_peer};
#[cfg(test)]
mod tests {
#[test]
@@ -6691,9 +6631,7 @@ mod tests {
);
assert_eq!(
remote
.pool_meta_native_recovery(PoolMetaNativeRecoveryRequest::Inspect {
object: crate::disk::PoolMetaNativeObject::PoolBin,
})
.pool_meta_native_recovery(PoolMetaNativeRecoveryRequest::Probe {})
.await,
Err(DiskError::UnsupportedDisk),
);
@@ -6704,7 +6642,7 @@ mod tests {
"/node_service.NodeService/UndoPoolMetaWrite",
"/node_service.NodeService/PoolMetaNativeRecovery"
],
"protected mutations and native inspection must never fall back to legacy RPCs",
"protected mutations and capability probes must never fall back to legacy RPCs",
);
peer.stop().await;
}
@@ -7320,7 +7258,6 @@ mod tests {
fail_format_reads: Arc<AtomicBool>,
next_format_read_gate: Arc<StdMutex<Option<Arc<TestFormatReadGate>>>>,
bounded_discovery: Arc<StdMutex<Option<Arc<TestBoundedDiscovery>>>>,
verify_disk: Arc<StdMutex<Option<crate::disk::DiskStore>>>,
unsupported_methods: Arc<StdMutex<Vec<String>>>,
}
@@ -7348,7 +7285,6 @@ mod tests {
fail_format_reads: Arc::default(),
next_format_read_gate: Arc::default(),
bounded_discovery: Arc::default(),
verify_disk: Arc::default(),
unsupported_methods: Arc::default(),
}
}
@@ -7448,77 +7384,6 @@ mod tests {
Ok(grpc.unary(method, request).await)
})
}
"/node_service.NodeService/ReadVersion"
if self.peer.verify_disk.lock().expect("verification fixture").is_some() =>
{
struct ReadVersionSvc(AuthenticatedReadPeer);
impl tonic::server::UnaryService<ReadVersionRequest> for ReadVersionSvc {
type Response = rustfs_protos::proto_gen::node_service::ReadVersionResponse;
type Future = Pin<Box<dyn Future<Output = std::result::Result<Response<Self::Response>, Status>> + Send>>;
fn call(&mut self, request: Request<ReadVersionRequest>) -> Self::Future {
let peer = self.0.clone();
Box::pin(async move {
peer.verify_auth(&request, "/node_service.NodeService/ReadVersion")?;
let req = request.into_inner();
let disk = peer.verify_disk.lock().expect("verification fixture").clone().expect("disk");
let opts = rmp_serde::from_slice(&req.opts_bin).expect("read options");
let mut response = Self::Response::default();
match disk.read_version("", &req.volume, &req.path, &req.version_id, &opts).await {
Ok(fi) => {
response.success = true;
response.file_info_bin = encode_file_info_msgpack(&fi).expect("encode file info").into();
}
Err(err) => response.error = Some(err.into()),
}
Ok(Response::new(response))
})
}
}
let method = ReadVersionSvc(self.peer.clone());
Box::pin(async move {
Ok(tonic::server::Grpc::new(tonic_prost::ProstCodec::default())
.unary(method, request)
.await)
})
}
"/node_service.NodeService/VerifyFile" => {
struct VerifySvc(AuthenticatedReadPeer);
impl tonic::server::UnaryService<VerifyFileRequest> for VerifySvc {
type Response = rustfs_protos::proto_gen::node_service::VerifyFileResponse;
type Future = Pin<Box<dyn Future<Output = std::result::Result<Response<Self::Response>, Status>> + Send>>;
fn call(&mut self, request: Request<VerifyFileRequest>) -> Self::Future {
let peer = self.0.clone();
Box::pin(async move {
peer.verify_auth(&request, "/node_service.NodeService/VerifyFile")?;
let request = request.into_inner();
let disk = peer
.verify_disk
.lock()
.expect("verification fixture")
.clone()
.expect("verification disk");
let fi: FileInfo = serde_json::from_str(&request.file_info).expect("verification layout");
assert!(fi.data.is_none());
let result = disk
.verify_file(&request.volume, &request.path, &fi)
.await
.expect("disk verification");
Ok(Response::new(Self::Response {
success: true,
check_parts_resp: serde_json::to_string(&result).expect("verification result"),
error: None,
}))
})
}
}
let method = VerifySvc(self.peer.clone());
Box::pin(async move {
Ok(tonic::server::Grpc::new(tonic_prost::ProstCodec::default())
.unary(method, request)
.await)
})
}
"/node_service.NodeService/RecoverDeleteTransaction"
if self.peer.bounded_discovery.lock().expect("bounded fixture").is_some() =>
{
@@ -7685,66 +7550,6 @@ mod tests {
}
}
pub(crate) async fn with_staged_part_peer<F, Fut>(disk: crate::disk::DiskStore, exercise: F)
where
F: FnOnce(RemoteDisk, RemoteDisk) -> Fut,
Fut: Future<Output = ()>,
{
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind verification peer");
*peer.peer.verify_disk.lock().expect("verification fixture") = Some(disk);
let tcp = remote_disk_for_addr(&peer.addr).await;
let mut nixl = remote_disk_for_addr(&peer.addr).await;
nixl.data_transport = Arc::new(crate::cluster::rpc::nixl_internode::NixlInternodeDataTransport::from_env());
// Ordinary control RPCs have a fixed deadline. Verification must use
// its own channel even when a short-lived control channel is cached.
let control = tonic::transport::Endpoint::from_shared(peer.addr.clone())
.expect("peer URI")
.timeout(Duration::from_nanos(1))
.connect()
.await
.expect("connect control channel");
rustfs_common::cache_connection(peer.addr.clone(), control).await;
exercise(tcp, nixl).await;
assert_eq!(peer.peer.read_all_calls(), 0);
assert!(peer.peer.unsupported_methods.lock().expect("unexpected requests").is_empty());
peer.stop().await;
}
/// The peer acknowledges the stream but loses the staged shard. Its signed VerifyFile
/// handler reads the actual backing disk, so the upload receives a missing-part status.
pub(crate) async fn with_lost_staged_shard_peer<F, Fut>(disk: crate::disk::DiskStore, exercise: F)
where
F: FnOnce(RemoteDisk) -> Fut,
Fut: Future<Output = ()>,
{
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind verification peer");
*peer.peer.verify_disk.lock().expect("verification fixture") = Some(disk);
let writes = Arc::new(RecordingInternodeDataTransport::default());
let mut remote = remote_disk_for_addr(&peer.addr).await;
remote.data_transport = writes.clone();
exercise(remote).await;
assert!(
writes
.calls()
.iter()
.any(|call| matches!(call, RecordedTransportCall::Write(_)))
);
let methods = peer.peer.unsupported_methods.lock().expect("peer requests").clone();
assert!(
!methods
.iter()
.any(|path| path.contains("Rename") || path.ends_with("/PreparePartTransaction")),
"{methods:?}"
);
peer.stop().await;
}
impl RecordingInternodeDataTransport {
fn with_ns_scanner_probe_status(status: u16) -> Self {
Self {
-1
View File
@@ -3507,7 +3507,6 @@ mod tests {
checksum: None,
multipart_completion_replayed: false,
backfilled_old_current_size: None,
ec_block_size: None,
}
}
}
@@ -207,10 +207,10 @@ async fn pool_meta_native_physical_split_without_ordinary_commit_performs_no_mut
let before = snapshots(&fixture.store).await;
let mut state = clean_state(&fixture);
let fence = PoolMetaPersistenceFence::Owned(owner(&fixture.store).await);
let error = repair(&fixture.store, &mut state, &fence)
.await
.expect_err("reconstruction alone must never authorize a COMMIT");
assert!(error.to_string().contains("(no_ordinary_v3_authority)"), "{error}");
assert!(
repair(&fixture.store, &mut state, &fence).await.is_err(),
"reconstruction alone must never authorize a COMMIT"
);
assert_eq!(
snapshots(&fixture.store).await,
before,
@@ -222,24 +222,6 @@ async fn pool_meta_native_physical_split_without_ordinary_commit_performs_no_mut
.expect("missing ordinary authority alone must not install a permanent corruption latch");
}
#[tokio::test]
#[serial_test::serial(pool_meta_version_env)]
async fn pool_meta_native_inspection_rejects_an_absent_slot_without_changing_evidence() {
let fixture = fixture(1).await;
let before = snapshots(&fixture.store).await;
let fence = PoolMetaPersistenceFence::Owned(owner(&fixture.store).await);
let last_pool = fixture.store.pools.last().expect("fixture has a last pool");
let set = last_pool.get_disks_by_key(POOL_META_NAME);
let missing = set.disks.write().await[0].take().expect("fixture has a disk in slot zero");
let result = inspect(&fixture.store.pools, &fence).await;
set.disks.write().await[0] = Some(missing);
let error = result.err().expect("an absent slot cannot provide native evidence");
assert!(error.to_string().contains("(missing_pool_metadata_slot)"), "{error}");
assert_eq!(snapshots(&fixture.store).await, before);
}
async fn interrupted_first_commit_fixture() -> (PhysicalFixture, PoolMetaCommittedCandidate) {
let fixture = fixture(3).await;
let PoolMetaReplica::Valid {
@@ -19,7 +19,6 @@ use crate::disk::{
PoolMetaNativeRecoveryResponse as Response,
};
use bytes::Bytes;
use futures::TryStreamExt as _;
#[cfg(test)]
#[derive(Default)]
@@ -39,16 +38,8 @@ struct InspectedPool {
snapshots: Vec<PoolMetaNativeInspection>,
}
#[derive(Debug, thiserror::Error)]
#[error("native pool metadata recovery requires one proven V3 transaction and complete matching disk evidence ({0})")]
struct MissingEvidence(&'static str);
fn missing_evidence(reason: &'static str) -> Error {
Error::other(MissingEvidence(reason))
}
fn invalid() -> Error {
missing_evidence("inconsistent_evidence")
Error::other("native pool metadata recovery requires one proven V3 transaction and complete matching disk evidence")
}
fn known_validation(source: Error, phase: &'static str) -> Error {
@@ -80,19 +71,13 @@ fn latch_validation(state: &mut PoolMetaWriteState, error: Error) -> Error {
fn current(pool: &InspectedPool) -> Result<Vec<Bytes>> {
pool.snapshots
.iter()
.map(|snapshot| {
snapshot
.current
.clone()
.ok_or_else(|| missing_evidence("missing_pool_metadata_head"))
})
.map(|snapshot| snapshot.current.clone().ok_or_else(invalid))
.collect()
}
async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> Result<Vec<InspectedPool>> {
let mut inspected = Vec::with_capacity(pools.len());
// Check every slot before starting I/O. The authenticated, read-only
// Inspect RPC proves both protocol support and the disk's evidence.
// Pool -> disk order is stable; all capability probes precede every mutation.
for pool in pools {
fence.ensure_held()?;
let set = pool.get_disks_by_key(POOL_META_NAME);
@@ -102,8 +87,20 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
.await
.iter()
.cloned()
.map(|disk| disk.ok_or_else(|| missing_evidence("missing_pool_metadata_slot")))
.map(|disk| disk.ok_or_else(invalid))
.collect::<Result<Vec<_>>>()?;
let probes = futures::stream::iter(disks.iter().cloned().map(|disk| async move {
match disk.pool_meta_native_recovery(Request::Probe {}).await? {
Response::Probed => Ok(()),
_ => Err(invalid()),
}
}))
.buffered(4)
.collect::<Vec<Result<()>>>()
.await;
for result in probes {
result?;
}
inspected.push(InspectedPool {
disks,
snapshots: Vec::new(),
@@ -111,7 +108,7 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
}
for pool in &mut inspected {
fence.ensure_held()?;
pool.snapshots = futures::stream::iter(pool.disks.iter().cloned().map(|disk| async move {
let results = futures::stream::iter(pool.disks.iter().cloned().map(|disk| async move {
match disk
.pool_meta_native_recovery(Request::Inspect {
object: PoolMetaNativeObject::PoolBin,
@@ -119,12 +116,15 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
.await?
{
Response::Inspected(snapshot) if !snapshot.disk_id.is_nil() => Ok(snapshot),
_ => Err(missing_evidence("invalid_disk_identity_evidence")),
_ => Err(invalid()),
}
}))
.buffered(4)
.try_collect()
.await?;
.collect::<Vec<Result<PoolMetaNativeInspection>>>()
.await;
for result in results {
pool.snapshots.push(result?);
}
}
fence.ensure_held()?;
Ok(inspected)
@@ -142,7 +142,7 @@ async fn validate_identities(pools: &[Arc<Sets>], canonical: &[u8], fence: &Pool
.await
.iter()
.cloned()
.map(|disk| disk.ok_or_else(|| missing_evidence("missing_pool_identity_slot")))
.map(|disk| disk.ok_or_else(invalid))
.collect::<Result<Vec<_>>>()?;
let results = futures::stream::iter(disks.into_iter().enumerate().map(|(index, disk)| async move {
match disk.pool_meta_native_recovery(Request::InspectIdentity {}).await? {
@@ -151,7 +151,7 @@ async fn validate_identities(pools: &[Arc<Sets>], canonical: &[u8], fence: &Pool
.await
.map_err(|error| codec_validation(error, "native_identity_validation"))
}
_ => Err(missing_evidence("invalid_disk_identity_evidence")),
_ => Err(invalid()),
}
}))
.buffered(4)
@@ -479,7 +479,7 @@ pub(super) async fn repair(
})
.collect::<Vec<_>>();
if ordinary_commits.is_empty() && ordinary_prepares.is_empty() {
return Err(missing_evidence("no_ordinary_v3_authority"));
return Err(invalid());
}
let selection = select_pool_meta_replica_reads(reads)
.map_err(|error| latch_validation(state, known_validation(error, "native_metadata_validation")))?;
@@ -535,7 +535,7 @@ pub(super) async fn repair(
.iter()
.any(|read| !matches!(read.replica, PoolMetaIdentityReplica::Valid(_)))
{
return Err(missing_evidence("pool_identity_unavailable"));
return Err(invalid());
}
let identity = select_pool_meta_identity(identities, cluster_id)
.map_err(|error| latch_validation(state, known_validation(error, "native_identity_validation")))?;
@@ -847,10 +847,7 @@ mod tests {
async fn pool_meta_native_plan_rejects_missing_or_corrupt_evidence() {
let mut f = fixture().await;
let before = f.pools[1].snapshots[2].current.take();
let error = plan(&f.pools, &f.commit, f.revision, &f.identity, None)
.await
.expect_err("missing current shard must block the repair plan");
assert!(error.to_string().contains("(missing_pool_metadata_head)"), "{error}");
assert!(plan(&f.pools, &f.commit, f.revision, &f.identity, None).await.is_err());
f.pools[1].snapshots[2].current = before;
f.pools[1].snapshots[2].backups[0].data = Bytes::from_static(b"invalid metadata");
assert!(plan(&f.pools, &f.commit, f.revision, &f.identity, None).await.is_err());
@@ -1,94 +0,0 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::{ADMIN_USAGE_INCARNATION_CONCURRENCY, ADMIN_USAGE_INCARNATION_TIMEOUT, BucketUsageInfo, ECStore};
use futures::StreamExt;
use std::{collections::HashMap, sync::Arc};
use tokio::time::{Instant, timeout_at};
/// Read only the caller-selected bucket identities. One deadline bounds the
/// entire batch, including concurrent reads waiting for metadata locks.
pub(crate) async fn current_admin_bucket_incarnations(
store: Arc<ECStore>,
buckets: Vec<String>,
deadline: Instant,
) -> HashMap<String, String> {
let mut current = HashMap::new();
let mut reads = futures::stream::iter(buckets)
.map(move |name| {
let store = store.clone();
async move {
let id = store.bucket_incarnation_id_from_disk(&name).await;
(name, id)
}
})
.buffer_unordered(ADMIN_USAGE_INCARNATION_CONCURRENCY);
while Instant::now() < deadline {
let Ok(Some((name, id))) = timeout_at(deadline, reads.next()).await else {
break;
};
if let Ok(id) = id
&& !id.is_nil()
{
current.insert(name, id.to_string());
}
}
current
}
/// Verify both persisted scanner and single-node overlay values at the time of
/// an account-info read. Only names already selected by the IAM policy enter
/// metadata I/O; missing legacy identities and metadata timeouts remain unknown.
pub async fn verified_account_bucket_usage(
store: Arc<ECStore>,
mut measured: HashMap<String, BucketUsageInfo>,
allowed_names: Vec<String>,
) -> HashMap<String, BucketUsageInfo> {
let names = allowed_names
.into_iter()
.filter(|name| measured.get(name).is_some_and(|value| value.bucket_incarnation.is_some()))
.collect();
let current = current_admin_bucket_incarnations(store, names, Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT).await;
measured.retain(|name, value| {
current
.get(name)
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
});
measured
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::storage_api_contracts::bucket::{BucketOperations as _, MakeBucketOptions};
#[tokio::test]
#[serial_test::serial]
async fn account_inventory_preserves_only_permitted_current_incarnations_including_measured_zero() {
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let mut usage = HashMap::new();
for (name, objects) in [("permitted", 0), ("private", 300), ("recreated", 900), ("legacy", 90)] {
store.make_bucket(name, &MakeBucketOptions::default()).await.unwrap();
let current = store.bucket_incarnation_id_from_disk(name).await.unwrap();
let incarnation = match name {
"recreated" => Some("11111111-1111-4111-8111-111111111111".to_string()),
"legacy" => None,
_ => Some(current.to_string()),
};
usage.insert(
name.to_owned(),
BucketUsageInfo {
objects_count: objects,
bucket_incarnation: incarnation,
..Default::default()
},
);
}
let allowed = ["permitted", "recreated", "legacy"].map(String::from).to_vec();
let values = verified_account_bucket_usage(store, usage, allowed).await;
assert_eq!(values.len(), 1);
assert_eq!(values["permitted"].objects_count, 0);
}
}
+46 -119
View File
@@ -14,9 +14,6 @@
// #730: scanner/data-usage state is partially migrated and still owns staged cache helpers.
mod admin_bucket_identity;
pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
pub use admin_bucket_identity::verified_account_bucket_usage;
pub mod local_snapshot;
use crate::storage_api_contracts::{
@@ -60,7 +57,7 @@ const DATA_COMPRESSION_TOTAL_NAME: &str = ".compression.json";
pub const DATA_USAGE_CACHE_NAME: &str = ".usage-cache.bin";
const DATA_USAGE_CACHE_TTL_SECS: u64 = 30;
const ADMIN_USAGE_INCARNATION_CONCURRENCY: usize = 4;
pub(crate) const ADMIN_USAGE_INCARNATION_TIMEOUT: Duration = Duration::from_secs(2);
const ADMIN_USAGE_INCARNATION_TIMEOUT: Duration = Duration::from_secs(2);
// A scanner save invalidates only the saving process's snapshot cache; every
// other node sees it only after reloading. A fail-closed usage lookup for a
// bucket the cached snapshot does not mention at all may reload a copy this
@@ -1466,43 +1463,45 @@ async fn load_admin_data_usage_from_backend(store: Arc<ECStore>) -> Result<DataU
let observed = load_observed_data_usage_snapshot(store.clone()).await.ok().flatten();
let (selected, selected_is_current_format) =
select_admin_data_usage_snapshot(authoritative, source.is_authoritative(), observed);
Ok(normalize_loaded_data_usage(selected, selected_is_current_format).await.0)
}
async fn project_admin_data_usage_for_current_buckets(
store: Arc<ECStore>,
mut response: DataUsageInfo,
with_memory_overlay: bool,
) -> DataUsageInfo {
if !(response.is_complete_bucket_usage_snapshot() || response.is_valid_partial_snapshot()) {
return DataUsageInfo::default();
}
let overlay_authoritative = with_memory_overlay && !runtime_sources::setup_is_dist_erasure().await;
let mut response = normalize_loaded_data_usage(selected, selected_is_current_format).await.0;
use futures::StreamExt as _;
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let mut buckets = response
.buckets_usage
.keys()
.chain(response.usage_snapshot_bucket_observations.keys())
.cloned()
.collect::<HashSet<_>>();
if overlay_authoritative {
// Copy names under the memory lock, then release it before storage I/O.
buckets.extend(memory_cache().read().await.keys().cloned());
let mut incarnations = HashMap::new();
{
// Display-only identity reads must not serialize every bucket behind a
// slow metadata lock while holding the shared admin refresh permit.
// The common deadline bounds their total added latency; dropping this
// stream cancels all unfinished reads without spawning detached work.
// Own the names and store across awaits so this future remains Send
// when composed into spawned metrics collectors.
let buckets = response
.usage_snapshot_bucket_observations
.keys()
.cloned()
.collect::<Vec<_>>();
let mut identities = futures::stream::iter(buckets)
.map(move |bucket| {
let store = store.clone();
async move {
let identity = store.bucket_incarnation_id_from_disk(&bucket).await;
(bucket, identity)
}
})
.buffer_unordered(ADMIN_USAGE_INCARNATION_CONCURRENCY);
while tokio::time::Instant::now() < deadline {
let Ok(Some((bucket, identity))) = tokio::time::timeout_at(deadline, identities.next()).await else {
break;
};
// Unavailable, timed-out or recreated buckets retain canonical values.
if let Ok(incarnation) = identity
&& !incarnation.is_nil()
{
incarnations.insert(bucket, incarnation.to_string());
}
}
}
let incarnations = current_admin_bucket_incarnations(store, buckets.into_iter().collect(), deadline).await;
response.project_bucket_observations_for_admin(&incarnations);
if apply_bucket_usage_memory_overlay_if_authoritative(&mut response, overlay_authoritative).await {
response.usage_snapshot_complete = false;
response.usage_snapshot_partial = true;
response.usage_snapshot_converged = Some(false);
response.usage_snapshot_admin_projection = true;
response.replication_info.clear();
response.tier_stats = None;
response.unknown_tier_stats = None;
}
response.retain_current_bucket_usage_for_admin(&incarnations);
response
Ok(response)
}
fn discard_incomplete_bucket_usage(data_usage_info: &mut DataUsageInfo) {
@@ -1691,7 +1690,11 @@ async fn project_data_usage_from_backend_cached<T>(
}
}
async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
/// Load the freshest structurally complete snapshot for authenticated admin
/// observability. A scan raced by namespace activity may be selected here, but
/// never by [`load_data_usage_from_backend_cached`], which remains the
/// converged source for quota admission.
pub async fn load_admin_data_usage_from_backend_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let ttl = Duration::from_secs(DATA_USAGE_CACHE_TTL_SECS);
loop {
@@ -1740,38 +1743,6 @@ async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<Da
}
}
/// Load cached scanner statistics for authenticated admin observability.
///
/// Each response verifies bucket identities against current storage metadata,
/// including cache hits. Missing, failed, or timed-out identity reads leave that
/// bucket's usage absent (unknown). Legacy values without an incarnation stay
/// unknown until a scanner snapshot certifies their identity. Per-bucket reads
/// linearize independently; this is not an atomic namespace snapshot.
/// Identity reads have a shared deadline and do not outlive cancellation. The
/// unchanged cached baseline remains independent of quota and persistence.
///
/// # Errors
/// Returns the cached snapshot loading error when no baseline can be loaded.
pub async fn load_admin_data_usage_from_backend_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let response = load_admin_data_usage_snapshot_cached(store.clone()).await?;
Ok(project_admin_data_usage_for_current_buckets(store, response, false).await)
}
/// Load the admin view with the existing authoritative single-process overlay.
///
/// Only a complete or valid partial scanner snapshot can receive memory values.
/// The final identity check excludes statistics from retired or unverified buckets.
/// Distributed nodes continue to use scanner statistics without local totals.
/// Cancellation, unknown values, and per-bucket read semantics are the same as
/// [`load_admin_data_usage_from_backend_cached`]. No overlay is persisted.
///
/// # Errors
/// Returns the cached snapshot loading error when no baseline can be loaded.
pub async fn load_admin_data_usage_with_memory_overlay(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
let response = load_admin_data_usage_snapshot_cached(store.clone()).await?;
Ok(project_admin_data_usage_for_current_buckets(store, response, true).await)
}
/// Invalidate the process-local persisted usage snapshot cache after a durable
/// scanner write.
pub async fn invalidate_data_usage_snapshot_cache() {
@@ -2834,17 +2805,16 @@ async fn replace_bucket_usage_memory_from_info_if_generation(data_usage_info: &D
*cache = next_cache;
}
async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mut DataUsageInfo, authoritative: bool) -> bool {
async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mut DataUsageInfo, authoritative: bool) {
if !authoritative {
return false;
return;
}
let cache = memory_cache().read().await;
if cache.is_empty() {
return false;
return;
}
let was_complete = data_usage_info.usage_snapshot_complete;
let persisted_update = data_usage_info.last_update;
let mut changed = false;
let mut added_bucket = false;
@@ -2881,7 +2851,6 @@ async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mu
data_usage_info.buckets_count = data_usage_info.buckets_usage.len() as u64;
data_usage_info.calculate_totals();
}
changed || was_complete != data_usage_info.usage_snapshot_complete
}
pub async fn apply_bucket_usage_memory_overlay(data_usage_info: &mut DataUsageInfo) {
@@ -3775,23 +3744,6 @@ mod tests {
*cache_updating().write().await = false;
}
async fn bind_admin_usage_test_identities(store: &Arc<ECStore>, snapshot: &mut DataUsageInfo) {
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
for (bucket, usage) in &mut snapshot.buckets_usage {
store
.make_bucket(bucket, &crate::storage_api_contracts::bucket::MakeBucketOptions::default())
.await
.expect("create a real bucket for current admin identity validation");
usage.bucket_incarnation = Some(
store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("read the storage-owned fixture identity")
.to_string(),
);
}
}
fn data_usage_info_for_test(bucket: &str, objects_count: u64, size: u64, last_update: SystemTime) -> DataUsageInfo {
let mut info = DataUsageInfo {
last_update: Some(last_update),
@@ -4327,11 +4279,7 @@ mod tests {
use crate::config::com::save_config;
let (_dirs, store) = isolated_store_over_temp_disks().await;
let (mut authoritative, mut observed) = usage_snapshots_with_missing_observed_set();
bind_admin_usage_test_identities(&store, &mut authoritative).await;
for (bucket, usage) in &mut observed.buckets_usage {
usage.bucket_incarnation = authoritative.buckets_usage[bucket].bucket_incarnation.clone();
}
let (authoritative, observed) = usage_snapshots_with_missing_observed_set();
let primary_bytes = serde_json::to_vec(&authoritative).expect("encode complete usage");
let observed_bytes = serde_json::to_vec(&observed).expect("encode partial observation");
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), primary_bytes.clone())
@@ -4380,11 +4328,6 @@ mod tests {
reconciled.scanner_epoch = Some(4);
reconciled.scanner_cycle = Some(12);
reconciled.usage_snapshot_converged = Some(true);
reconciled
.buckets_usage
.get_mut("large-bucket")
.expect("reconciled bucket")
.bucket_incarnation = authoritative.buckets_usage["large-bucket"].bucket_incarnation.clone();
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -4906,12 +4849,6 @@ mod tests {
backup.scanner_epoch = Some(4);
backup.scanner_cycle = Some(10);
backup.usage_snapshot_converged = Some(true);
bind_admin_usage_test_identities(&store, &mut current).await;
backup
.buckets_usage
.get_mut("existing")
.expect("backup bucket")
.bucket_incarnation = current.buckets_usage["existing"].bucket_incarnation.clone();
for (path, info) in [
(DATA_USAGE_OBJ_NAME_PATH.as_str(), &current),
(DATA_USAGE_OBJ_BACKUP_PATH.as_str(), &backup),
@@ -4934,11 +4871,6 @@ mod tests {
after_delete.scanner_epoch = current.scanner_epoch;
after_delete.scanner_cycle = current.scanner_cycle;
after_delete.usage_snapshot_converged = Some(true);
after_delete
.buckets_usage
.get_mut("existing")
.expect("post-delete bucket")
.bucket_incarnation = current.buckets_usage["existing"].bucket_incarnation.clone();
let mut stale_observation =
data_usage_info_for_test("retired-incarnation", 99, 999, SystemTime::UNIX_EPOCH + Duration::from_secs(4));
stale_observation.scanner_epoch = Some(4);
@@ -5000,7 +4932,6 @@ mod tests {
authoritative.scanner_epoch = Some(7);
authoritative.scanner_cycle = Some(10);
authoritative.usage_snapshot_converged = Some(true);
bind_admin_usage_test_identities(&store, &mut authoritative).await;
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
@@ -5015,10 +4946,6 @@ mod tests {
info.scanner_cycle = Some(cycle);
info.usage_snapshot_converged = Some(false);
info.usage_snapshot_authoritative_baseline = Some(authoritative.snapshot_identity());
info.buckets_usage
.get_mut("bucket")
.expect("observed bucket")
.bucket_incarnation = authoritative.buckets_usage["bucket"].bucket_incarnation.clone();
info
};
let first = observation(7, 11, 200, 11, 1_100);
@@ -221,7 +221,7 @@ async fn companion_admin_cache_isolated_from_quota_memory_and_persistence() {
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_buckets() {
async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buckets() {
use crate::bucket::metadata_sys::{
acquire_metadata_transaction_guard, init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks,
};
@@ -280,11 +280,8 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
.await
.expect("optional projection must return before the blocked metadata lock's long timeout")
.expect("canonical admin response stays available");
assert!(
!response.buckets_usage.contains_key(blocked),
"an unavailable current identity cannot bind the canonical value"
);
assert!(!response.bucket_sizes.contains_key(blocked));
assert_eq!(response.buckets_usage[blocked].size, 100);
assert_eq!(response.buckets_usage[blocked].usage_value_state, Some(BucketUsageValueState::Carried));
assert_eq!(response.buckets_usage[healthy].size, 250);
assert_eq!(response.buckets_usage[healthy].usage_value_state, Some(BucketUsageValueState::Observed));
assert!(response.usage_snapshot_admin_projection);
@@ -296,12 +293,13 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
.is_ok()
);
drop(blocked_guard);
invalidate_data_usage_snapshot_cache().await;
let recovered = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("refresh after lock recovery");
assert_eq!(
recovered.buckets_usage[blocked].size, 250,
"unavailable identity can recover on a cache hit"
"unavailable identity can recover on the next refresh"
);
assert_eq!(recovered.buckets_usage[healthy].size, 250);
let quota = load_data_usage_from_backend_cached(store)
@@ -310,331 +308,3 @@ async fn blocked_companion_identity_stays_unknown_without_delaying_healthy_bucke
assert_eq!(quota.buckets_usage[blocked].size, 100);
assert_eq!(quota.buckets_usage[healthy].size, 100);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_invalidation() {
use crate::bucket::metadata::{load_bucket_incarnation, save_bucket_incarnation};
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "usage-recreated-cache";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create identity fixture");
let old_identity = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("original identity");
let mut canonical = companion_snapshot(bucket, old_identity);
canonical.usage_snapshot_bucket_observations.clear();
canonical.usage_snapshot_converged = Some(true);
canonical.usage_snapshot_pending_buckets.clear();
canonical.usage_snapshot_pending_bucket_count = 0;
canonical
.buckets_usage
.get_mut(bucket)
.expect("canonical bucket")
.objects_count = 107;
canonical.calculate_totals();
let original_bytes = serde_json::to_vec(&canonical).expect("encode canonical old bucket");
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), original_bytes.clone())
.await
.expect("persist canonical root");
invalidate_data_usage_snapshot_cache().await;
let first = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("prime raw admin cache");
assert_eq!(first.buckets_usage[bucket].objects_count, 107);
assert!(first.is_complete_bucket_usage_snapshot());
let cache_generation = admin_data_usage_snapshot_generation();
let new_identity = uuid::Uuid::new_v4();
// Simulate the storage-owned identity changing on another node while this
// process has not received its invalidation notice. Do not clear the cache.
save_bucket_incarnation(store.clone(), bucket, new_identity)
.await
.expect("publish changed disk identity");
assert_eq!(
load_bucket_incarnation(store.clone(), bucket)
.await
.expect("read new sidecar"),
Some(new_identity)
);
let second = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("read raw cache with fresh identity");
assert_eq!(admin_data_usage_snapshot_generation(), cache_generation);
assert!(
!second.buckets_usage.contains_key(bucket),
"same name cannot retain the predecessor's 107"
);
assert!(!second.bucket_sizes.contains_key(bucket));
assert_eq!(second.usage_snapshot_converged, Some(false));
assert!(second.usage_snapshot_admin_projection);
assert!(reject_admin_usage_projection(&second).is_err());
assert!(certified_bucket_usage(&second, bucket, new_identity).is_none());
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
let quota = load_data_usage_from_backend_cached(store.clone())
.await
.expect("independent quota baseline");
assert_eq!(quota.buckets_usage[bucket].objects_count, 107);
assert_eq!(
read_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str())
.await
.expect("unchanged persisted root"),
original_bytes
);
// Rebinding a cached raw baseline is transient: recovery does not need to
// reload or permanently blank a healthy bucket's statistics.
save_bucket_incarnation(store.clone(), bucket, old_identity)
.await
.expect("restore fixture identity");
let recovered = load_admin_data_usage_from_backend_cached(store)
.await
.expect("recover on another cache hit");
assert_eq!(recovered.buckets_usage[bucket].objects_count, 107);
assert!(recovered.is_complete_bucket_usage_snapshot());
assert_eq!(admin_data_usage_snapshot_generation(), cache_generation);
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_memory_overlay_requires_a_measured_scanner_baseline() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
assert!(!runtime_sources::setup_is_dist_erasure().await);
let bucket = "usage-unmeasured-overlay";
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
let incarnation = store.bucket_incarnation_id_from_disk(bucket).await.unwrap();
let mut baseline = data_usage_info_for_test(bucket, 1, 100, SystemTime::UNIX_EPOCH);
let usage = baseline.buckets_usage.get_mut(bucket).unwrap();
usage.bucket_incarnation = Some(incarnation.to_string());
let memory_usage = BucketUsageInfo {
size: 150,
..usage.clone()
};
clear_usage_memory_cache_for_test().await;
replace_bucket_usage_memory_from_authoritative(bucket, memory_usage, SystemTime::now()).await;
// A missing snapshot and a mismatched bucket count both leave usage unknown.
for (buckets_count, expected_size) in [(None, None), (Some(2), None), (Some(1), Some(150))] {
if let Some(count) = buckets_count {
baseline.buckets_count = count;
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&baseline).unwrap())
.await
.unwrap();
}
invalidate_data_usage_snapshot_cache().await;
let response = load_admin_data_usage_with_memory_overlay(store.clone()).await.unwrap();
assert_eq!(
response.buckets_usage.get(bucket).map(|usage| usage.size),
expected_size,
"baseline count {buckets_count:?}"
);
assert_eq!(response.bucket_sizes.get(bucket).copied(), expected_size);
assert_eq!(response.objects_total_size, expected_size.unwrap_or_default());
assert_eq!(response.usage_snapshot_admin_projection, expected_size.is_some());
assert!(!response.is_complete_bucket_usage_snapshot());
assert!(!response.is_valid_partial_snapshot());
}
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_identity_filter_does_not_validate_an_unmeasured_partial_snapshot() {
use crate::bucket::metadata_sys::test_support::isolated_store_over_temp_disks;
use crate::config::com::save_config;
let (_dirs, store) = isolated_store_over_temp_disks().await;
let current = "usage-partial-current";
let stale = "usage-partial-stale";
let mut baseline = data_usage_info_for_test(current, 5, 100, SystemTime::UNIX_EPOCH);
baseline.buckets_usage.insert(
stale.to_owned(),
BucketUsageInfo {
size: 200,
objects_count: 10,
..Default::default()
},
);
baseline.bucket_sizes.insert(stale.to_owned(), 200);
baseline.buckets_count = 2;
baseline.calculate_totals();
baseline.usage_snapshot_complete = false;
baseline.usage_snapshot_partial = true;
baseline.usage_snapshot_converged = Some(false);
baseline.scanner_epoch = Some(2);
baseline.scanner_cycle = Some(9);
baseline.usage_snapshot_set_states = vec![DataUsageSnapshotSetState {
scanner_epoch: baseline.scanner_epoch,
scanner_cycle: baseline.scanner_cycle,
scan_plan_digest: Some([1; 32]),
..Default::default()
}];
bind_admin_usage_test_identities(&store, &mut baseline).await;
let current_incarnation = baseline.buckets_usage[current].bucket_incarnation.clone();
assert_ne!(current_incarnation, baseline.buckets_usage[stale].bucket_incarnation);
baseline
.buckets_usage
.get_mut(stale)
.expect("stale bucket fixture")
.bucket_incarnation = current_incarnation;
for (case, snapshot, expected_size) in [
(
"missing set provenance",
DataUsageInfo {
usage_snapshot_set_states: Vec::new(),
..baseline.clone()
},
None,
),
(
"mismatched bucket count",
DataUsageInfo {
buckets_count: 3,
..baseline.clone()
},
None,
),
("valid partial snapshot", baseline, Some(100)),
] {
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&snapshot).expect("encode partial snapshot"),
)
.await
.expect("persist partial snapshot");
invalidate_admin_data_usage_snapshot_cache().await;
let response = load_admin_data_usage_from_backend_cached(store.clone())
.await
.expect("load admin usage through the identity filter");
assert_eq!(response.buckets_usage.get(current).map(|usage| usage.size), expected_size, "{case}");
assert_eq!(response.bucket_sizes.get(current).copied(), expected_size, "{case}");
assert!(!response.buckets_usage.contains_key(stale), "{case}");
assert!(!response.bucket_sizes.contains_key(stale), "{case}");
assert_eq!(response.objects_total_size, expected_size.unwrap_or_default(), "{case}");
assert_eq!(response.usage_snapshot_admin_projection, expected_size.is_some(), "{case}");
}
invalidate_admin_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_memory_overlay_cannot_reintroduce_a_predecessor_identity() {
use crate::bucket::metadata::save_bucket_incarnation;
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = "usage-recreated-overlay";
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create overlay identity fixture");
let old_identity = store
.bucket_incarnation_id_from_disk(bucket)
.await
.expect("original identity");
let mut canonical = companion_snapshot(bucket, old_identity);
canonical.usage_snapshot_bucket_observations.clear();
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&canonical).expect("encode canonical root"),
)
.await
.expect("persist overlay fixture");
invalidate_data_usage_snapshot_cache().await;
let cached_usage = canonical.buckets_usage[bucket].clone();
replace_bucket_usage_memory_from_authoritative(bucket, cached_usage, SystemTime::now()).await;
let new_identity = uuid::Uuid::new_v4();
save_bucket_incarnation(store.clone(), bucket, new_identity)
.await
.expect("publish a replacement identity");
let response = load_admin_data_usage_with_memory_overlay(store.clone())
.await
.expect("project after memory overlay");
assert!(!response.buckets_usage.contains_key(bucket));
assert_eq!(response.usage_snapshot_converged, Some(false));
assert!(response.usage_snapshot_admin_projection);
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn admin_overlay_flags_only_change_keeps_identity_bound_cold_usage() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::storage_api_contracts::bucket::MakeBucketOptions;
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
assert!(
!runtime_sources::setup_is_dist_erasure().await,
"exercise the production single-process overlay"
);
let cold = "usage-overlay-cold";
let unverified = "usage-overlay-unverified";
for bucket in [cold, unverified] {
store
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("create overlay fixture bucket");
}
let identity = store
.bucket_incarnation_id_from_disk(cold)
.await
.expect("cold bucket identity");
let mut canonical = companion_snapshot(cold, identity);
canonical.usage_snapshot_bucket_observations.clear();
canonical.usage_snapshot_converged = Some(true);
save_config(
store.clone(),
DATA_USAGE_OBJ_NAME_PATH.as_str(),
serde_json::to_vec(&canonical).expect("encode cold canonical value"),
)
.await
.expect("persist cold baseline");
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
memory_cache().write().await.insert(
unverified.to_string(),
cached_bucket_usage_from_backend(BucketUsageInfo::default(), SystemTime::UNIX_EPOCH, false),
);
record_bucket_object_write_memory(unverified, None, 42).await;
{
let cache = memory_cache().read().await;
assert!(cache[unverified].dirty);
assert!(!cache[unverified].authoritative);
}
let response = load_admin_data_usage_with_memory_overlay(store)
.await
.expect("identity-filtered flags-only overlay");
assert_eq!(response.buckets_usage[cold].size, 100);
assert_eq!(response.objects_total_size, 100);
assert_eq!(response.bucket_sizes[cold], 100);
assert!(!response.buckets_usage.contains_key(unverified));
assert!(response.usage_snapshot_admin_projection);
assert_eq!(response.usage_snapshot_converged, Some(false));
assert!(!response.is_complete_bucket_usage_snapshot());
assert!(!response.is_valid_partial_snapshot());
clear_usage_memory_cache_for_test().await;
invalidate_data_usage_snapshot_cache().await;
}
@@ -50,8 +50,6 @@ const EVENT_SERVER_INFO: &str = "server_info";
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
const LOG_SUBSYSTEM_DIAGNOSTICS: &str = "diagnostics";
mod inventory;
use shadow_rs::shadow;
shadow!(build);
@@ -278,14 +276,6 @@ fn collect_runtime_server_stats() -> (MemStats, u64, u64) {
}
pub async fn get_server_info(get_pools: bool) -> InfoMessage {
get_server_info_with_inventory(get_pools, false).await.0
}
pub async fn get_server_info_with_inventory(
get_pools: bool,
include_inventory: bool,
) -> (InfoMessage, Option<rustfs_madmin::ClusterInventory>) {
let mut inventory = include_inventory.then(rustfs_madmin::ClusterInventory::default);
let started = tracing::enabled!(tracing::Level::TRACE).then(Instant::now);
let local = get_local_server_property().await;
@@ -311,24 +301,25 @@ pub async fn get_server_info_with_inventory(
if let Some(store) = runtime_sources::object_store_handle() {
mode = ITEM_ONLINE;
let namespace_options = BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
};
let load_snapshot = load_server_info_usage_snapshot(store.clone());
let (snapshot, namespace) = if include_inventory {
let (snapshot, namespace, measured) =
inventory::collect(&store, load_snapshot, store.list_bucket_for_scanner(&namespace_options)).await;
inventory = Some(measured);
(snapshot, Some(namespace))
} else {
(load_snapshot.await, None)
};
apply_data_usage_result(snapshot, &mut buckets, &mut objects, &mut versions, &mut delete_markers, &mut usage);
apply_data_usage_result(
load_server_info_usage_snapshot(store.clone()).await,
&mut buckets,
&mut objects,
&mut versions,
&mut delete_markers,
&mut usage,
);
if buckets.error.is_some() {
let listing = inventory::namespace_or_fallback(namespace, store.list_bucket_for_scanner(&namespace_options)).await;
apply_bucket_namespace_count(listing, &mut buckets);
apply_bucket_namespace_count(
store
.list_bucket_for_scanner(&BucketOptions {
cached: true,
no_metadata: true,
..Default::default()
})
.await,
&mut buckets,
);
}
let backend_info = StorageAdminApi::backend_info(store.as_ref()).await;
@@ -384,7 +375,7 @@ pub async fn get_server_info_with_inventory(
);
}
let info = InfoMessage {
InfoMessage {
mode: Some(mode.to_string()),
domain: None,
region: None,
@@ -399,8 +390,7 @@ pub async fn get_server_info_with_inventory(
services: Some(services),
servers: Some(servers),
pools: Some(pools),
};
(info, inventory)
}
}
fn is_online_drive_state(state: &str) -> bool {
@@ -1043,26 +1033,16 @@ mod tests {
#[tokio::test]
#[serial]
async fn server_info_reads_complete_observation_without_promoting_authority() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::bucket::metadata_sys::test_support::isolated_store_over_temp_disks;
use crate::config::com::{read_config, save_config};
use crate::data_usage::{
DATA_USAGE_OBJ_NAME_PATH, DATA_USAGE_OBSERVED_OBJ_NAME_PATH, invalidate_data_usage_snapshot_cache,
load_data_usage_from_backend_cached,
};
use crate::storage_api_contracts::bucket::{BucketOperations as _, MakeBucketOptions};
use rustfs_data_usage::{BucketUsageInfo, DataUsageInfo};
use std::time::{Duration, SystemTime};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
store
.make_bucket("bucket", &MakeBucketOptions::default())
.await
.expect("create a real observed bucket");
let incarnation = store
.bucket_incarnation_id_from_disk("bucket")
.await
.expect("read current storage-owned incarnation");
let primary = DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
scanner_epoch: Some(1),
@@ -1086,7 +1066,6 @@ mod tests {
versions_count: 4,
delete_markers_count: 1,
size: 6,
bucket_incarnation: Some(incarnation.to_string()),
..Default::default()
},
)]
@@ -1138,46 +1117,6 @@ mod tests {
invalidate_data_usage_snapshot_cache().await;
}
#[test]
fn identity_filtered_usage_remains_unknown_in_server_info() {
let mut info = rustfs_data_usage::DataUsageInfo {
last_update: Some(std::time::SystemTime::UNIX_EPOCH),
buckets_count: 1,
objects_total_count: 107,
objects_total_size: 1024,
buckets_usage: [(
"bucket".to_string(),
rustfs_data_usage::BucketUsageInfo {
objects_count: 107,
size: 1024,
bucket_incarnation: Some("11111111-1111-4111-8111-111111111111".to_string()),
..Default::default()
},
)]
.into_iter()
.collect(),
usage_snapshot_complete: true,
..Default::default()
};
let current =
std::collections::HashMap::from([("bucket".to_string(), "22222222-2222-4222-8222-222222222222".to_string())]);
assert_eq!(info.retain_current_bucket_usage_for_admin(&current), 1);
assert!(info.buckets_usage.is_empty());
assert!(info.usage_snapshot_admin_projection);
assert_eq!(info.usage_snapshot_converged, Some(false));
let mut buckets = rustfs_madmin::Buckets::default();
let mut objects = rustfs_madmin::Objects::default();
let mut versions = rustfs_madmin::Versions::default();
let mut delete_markers = rustfs_madmin::DeleteMarkers::default();
let mut usage = rustfs_madmin::Usage::default();
apply_data_usage_result(Ok(info), &mut buckets, &mut objects, &mut versions, &mut delete_markers, &mut usage);
assert_eq!(buckets.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(objects.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(versions.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(delete_markers.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
assert_eq!(usage.error.as_deref(), Some(DATA_USAGE_UNAVAILABLE_ERROR));
}
#[test]
fn incomplete_data_usage_is_unavailable_in_server_info() {
let mut buckets = rustfs_madmin::Buckets::default();
@@ -1,349 +0,0 @@
// Copyright 2026 RustFS Team
// Licensed under the Apache License, Version 2.0.
use super::ScannerBucketListing;
use rustfs_data_usage::DataUsageInfo;
use rustfs_madmin::ClusterInventory;
use std::collections::HashSet;
use crate::data_usage::{ADMIN_USAGE_INCARNATION_TIMEOUT, current_admin_bucket_incarnations};
use crate::error::Result;
use crate::store::ECStore;
use std::collections::HashMap;
use std::sync::Arc;
pub(super) async fn collect(
store: &Arc<ECStore>,
load_snapshot: impl Future<Output = Result<DataUsageInfo>>,
list_namespace: impl Future<Output = Result<ScannerBucketListing>>,
) -> (Result<DataUsageInfo>, Result<ScannerBucketListing>, ClusterInventory) {
let snapshot = load_snapshot.await;
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
let namespace = bounded_namespace(deadline, list_namespace).await;
let mut current_ids = HashMap::new();
if let (Ok(namespace), Ok(snapshot)) = (&namespace, &snapshot)
&& namespace.topology_complete
{
let names = namespace
.buckets
.iter()
.filter(|bucket| {
!bucket.name.starts_with('.')
&& snapshot
.buckets_usage
.get(&bucket.name)
.is_some_and(|usage| usage.bucket_incarnation.is_some())
})
.map(|bucket| bucket.name.clone())
.collect();
current_ids = current_admin_bucket_incarnations(store.clone(), names, deadline).await;
}
let measured = summarize(namespace.as_ref().ok(), snapshot.as_ref().ok(), &current_ids);
(snapshot, namespace, measured)
}
pub(super) async fn bounded_namespace(
deadline: tokio::time::Instant,
read: impl Future<Output = crate::error::Result<ScannerBucketListing>>,
) -> crate::error::Result<ScannerBucketListing> {
tokio::time::timeout_at(deadline, read)
.await
.map_err(|_| crate::error::Error::other("inventory namespace read timed out"))?
}
pub(super) async fn namespace_or_fallback(
previous: Option<crate::error::Result<ScannerBucketListing>>,
read: impl Future<Output = crate::error::Result<ScannerBucketListing>>,
) -> crate::error::Result<ScannerBucketListing> {
// A failed or timed-out optional listing is already an observation.
// Retrying it without the deadline would stall the independent health response.
match previous {
Some(result) => result,
None => read.await,
}
}
pub(super) fn summarize(
namespace: Option<&ScannerBucketListing>,
snapshot: Option<&DataUsageInfo>,
current_ids: &HashMap<String, String>,
) -> ClusterInventory {
// An admin projection is a validated display-only view produced by the loader.
let snapshot = snapshot.filter(|info| {
info.usage_snapshot_admin_projection || info.is_complete_bucket_usage_snapshot() || info.is_valid_partial_snapshot()
});
let mut inventory = ClusterInventory {
snapshot_at: snapshot
.and_then(|info| info.last_update)
.and_then(|time| time.try_into().ok()),
..Default::default()
};
let Some(namespace) = namespace.filter(|listing| listing.topology_complete) else {
return inventory;
};
let names: HashSet<_> = namespace
.buckets
.iter()
.map(|bucket| bucket.name.as_str())
.filter(|name| !name.starts_with('.'))
.collect();
inventory.current_buckets = u64::try_from(names.len()).ok();
let Some(snapshot) = snapshot else {
return inventory;
};
let mut measured = 0_u64;
let mut objects = Some(0_u64);
let mut bytes = Some(0_u64);
for &name in &names {
let Some(usage) = snapshot.buckets_usage.get(name) else { continue };
if usage
.bucket_incarnation
.as_ref()
.is_none_or(|id| current_ids.get(name) != Some(id))
{
continue;
}
measured += 1;
objects = objects.and_then(|total| total.checked_add(usage.objects_count));
bytes = bytes.and_then(|total| total.checked_add(usage.size));
}
inventory.measured_buckets = Some(measured);
if measured != 0 || names.is_empty() {
inventory.measured_objects = objects;
inventory.measured_bytes = bytes;
}
inventory.converged = if objects.is_none() || bytes.is_none() {
None
} else if inventory.current_buckets != Some(measured)
|| snapshot.buckets_usage.len() != names.len()
|| snapshot.usage_snapshot_pending_bucket_count > 0
|| !snapshot.usage_snapshot_pending_buckets.is_empty()
|| !snapshot.is_complete_bucket_usage_snapshot()
{
Some(false)
} else {
snapshot.usage_snapshot_converged
};
inventory
}
#[cfg(test)]
mod tests {
use super::*;
use rustfs_data_usage::BucketUsageInfo;
use std::time::{Duration, SystemTime};
fn namespace(names: &[&str]) -> ScannerBucketListing {
ScannerBucketListing {
buckets: names
.iter()
.map(|name| crate::storage_api_contracts::bucket::BucketInfo {
name: name.to_string(),
..Default::default()
})
.collect(),
set_buckets: vec![],
topology_complete: true,
}
}
fn snapshot(names: &[(&str, u64)]) -> DataUsageInfo {
DataUsageInfo {
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)),
usage_snapshot_complete: true,
usage_snapshot_converged: Some(true),
buckets_count: u64::try_from(names.len()).unwrap(),
buckets_usage: names
.iter()
.map(|&(name, count)| {
(
name.to_owned(),
BucketUsageInfo {
objects_count: count,
size: count,
bucket_incarnation: Some("11111111-1111-4111-8111-111111111111".into()),
..Default::default()
},
)
})
.collect(),
..Default::default()
}
}
fn view(namespace: Option<&ScannerBucketListing>, snapshot: Option<&DataUsageInfo>) -> ClusterInventory {
let ids = namespace
.into_iter()
.flat_map(|ns| &ns.buckets)
.map(|bucket| (bucket.name.clone(), "11111111-1111-4111-8111-111111111111".to_string()))
.collect();
summarize(namespace, snapshot, &ids)
}
#[tokio::test(start_paused = true)]
async fn inventory_namespace_timeout_is_reused_by_the_legacy_fallback() {
use tokio::time::{Duration, Instant};
let deadline = Instant::now() + Duration::from_secs(2);
let result = bounded_namespace(deadline, std::future::pending()).await;
assert!(result.is_err());
assert_eq!(Instant::now(), deadline);
let result = namespace_or_fallback(Some(result), async { panic!("must not retry a failed namespace read") }).await;
assert!(result.is_err());
let inventory = view(result.as_ref().ok(), None);
assert_eq!(inventory.current_buckets, None);
assert_eq!(inventory.measured_objects, None);
}
#[tokio::test]
#[serial_test::serial]
async fn inventory_excludes_stale_bucket_incarnations_after_a_slow_cold_snapshot_refresh() {
use crate::bucket::metadata_sys::{init_bucket_metadata_sys, test_support::isolated_store_over_temp_disks};
use crate::config::com::save_config;
use crate::data_usage::{DATA_USAGE_OBJ_NAME_PATH, invalidate_data_usage_snapshot_cache};
use crate::storage_api_contracts::bucket::{BucketOperations as _, BucketOptions, MakeBucketOptions};
let (_dirs, store) = isolated_store_over_temp_disks().await;
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
for bucket in ["unchanged", "recreated", "new"] {
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
}
let mut scanned = snapshot(&[("unchanged", 4), ("recreated", 99), ("deleted", 6)]);
let current = store.bucket_incarnation_id_from_disk("unchanged").await.unwrap();
scanned.buckets_usage.get_mut("unchanged").unwrap().bucket_incarnation = Some(current.to_string());
scanned.usage_snapshot_converged = None;
scanned.calculate_totals();
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&scanned).unwrap())
.await
.unwrap();
invalidate_data_usage_snapshot_cache().await;
let options = BucketOptions {
no_metadata: true,
..Default::default()
};
let cold_refresh = async {
// Model a refresh that outlasts the inventory budget; keep disk I/O
// on the real clock so its independent timeouts behave normally.
tokio::time::pause();
tokio::time::advance(ADMIN_USAGE_INCARNATION_TIMEOUT + Duration::from_secs(1)).await;
tokio::time::resume();
super::super::load_server_info_usage_snapshot(store.clone()).await
};
let (loaded, listing, result) = collect(&store, cold_refresh, store.list_bucket_for_scanner(&options)).await;
let loaded = loaded.expect("cold admin snapshot should load");
assert!(loaded.usage_snapshot_admin_projection);
assert_eq!(loaded.usage_snapshot_converged, Some(false));
assert_eq!(loaded.buckets_usage.len(), 1);
assert_eq!(loaded.buckets_usage["unchanged"].objects_count, 4);
assert!(listing.unwrap().topology_complete);
assert_eq!(result.current_buckets, Some(3));
assert_eq!(result.measured_buckets, Some(1));
assert_eq!(result.measured_objects, Some(4));
assert_eq!(result.converged, Some(false));
// A complete canonical snapshot from before the convergence field was
// added inherits the admin loader's existing convergence interpretation.
let mut legacy = snapshot(&[("unchanged", 4), ("recreated", 0), ("new", 0)]);
legacy.usage_snapshot_converged = None;
for (name, usage) in &mut legacy.buckets_usage {
usage.bucket_incarnation = Some(store.bucket_incarnation_id_from_disk(name).await.unwrap().to_string());
}
legacy.calculate_totals();
save_config(store.clone(), DATA_USAGE_OBJ_NAME_PATH.as_str(), serde_json::to_vec(&legacy).unwrap())
.await
.unwrap();
invalidate_data_usage_snapshot_cache().await;
let (_, _, result) = collect(
&store,
super::super::load_server_info_usage_snapshot(store.clone()),
store.list_bucket_for_scanner(&options),
)
.await;
assert_eq!(result.measured_objects, Some(4));
assert_eq!(result.converged, Some(true));
invalidate_data_usage_snapshot_cache().await;
}
#[test]
fn inventory_reports_only_the_intersection_of_current_and_measured_buckets() {
let scope = namespace(&["existing", "new", ".rustfs.sys"]);
let before = snapshot(&[("existing", 300_000), ("deleted", 7)]);
let result = view(Some(&scope), Some(&before));
assert_eq!(result.current_buckets, Some(2));
assert_eq!(result.measured_buckets, Some(1));
assert_eq!(result.measured_objects, Some(300_000));
assert_eq!(result.measured_bytes, Some(300_000));
assert_eq!(result.converged, Some(false));
assert_eq!(result.snapshot_at.unwrap().as_second(), 1);
}
#[test]
fn inventory_distinguishes_unavailable_and_confirmed_empty_measurements() {
let empty = namespace(&[]);
let missing = view(Some(&empty), Some(&DataUsageInfo::default()));
assert_eq!(missing.current_buckets, Some(0));
assert_eq!(missing.measured_objects, None);
assert_eq!(missing.measured_buckets, None);
let available = view(Some(&empty), Some(&snapshot(&[])));
assert_eq!(available.measured_objects, Some(0));
assert_eq!(available.converged, Some(true));
let scope = namespace(&["new"]);
let no_overlap = view(Some(&scope), Some(&snapshot(&[("deleted", 7)])));
assert_eq!(no_overlap.measured_buckets, Some(0));
assert_eq!(no_overlap.measured_objects, None);
let known_empty = view(Some(&scope), Some(&snapshot(&[("new", 0)])));
assert_eq!(known_empty.measured_objects, Some(0));
assert_eq!(known_empty.measured_buckets, Some(1));
}
#[test]
fn inventory_keeps_the_recorded_snapshot_convergence_and_age() {
let scope = namespace(&["a"]);
let mut scanned = snapshot(&[("a", 12)]);
scanned.usage_snapshot_converged = None;
assert_eq!(view(Some(&scope), Some(&scanned)).converged, None);
scanned.usage_snapshot_converged = Some(true);
scanned.usage_snapshot_pending_buckets = vec!["a".into()];
assert_eq!(view(Some(&scope), Some(&scanned)).converged, Some(false));
scanned.usage_snapshot_pending_buckets.clear();
scanned.usage_snapshot_converged = Some(false);
scanned.usage_snapshot_complete = false;
scanned.usage_snapshot_admin_projection = true;
let result = view(Some(&scope), Some(&scanned));
assert_eq!(result.measured_objects, Some(12));
assert_eq!(result.converged, Some(false));
assert_eq!(result.snapshot_at.unwrap().as_second(), 1);
}
#[test]
fn inventory_requires_complete_namespace_and_checks_each_sum() {
let mut scope = namespace(&["a", "b"]);
let mut scanned = snapshot(&[("a", u64::MAX), ("b", 1)]);
scanned.buckets_usage.get_mut("a").unwrap().size = 1;
scope.topology_complete = false;
let missing = view(Some(&scope), Some(&scanned));
assert_eq!(missing.current_buckets, None);
assert_eq!(missing.measured_buckets, None);
assert_eq!(missing.converged, None);
scope.topology_complete = true;
let overflow = view(Some(&scope), Some(&scanned));
assert_eq!(overflow.measured_buckets, Some(2));
assert_eq!(overflow.measured_objects, None);
assert_eq!(overflow.measured_bytes, Some(2));
assert_eq!(overflow.converged, None);
}
#[test]
fn inventory_checks_even_cached_canonical_incarnations_on_main() {
let scope = namespace(&["recreated", "unreadable", "legacy"]);
let mut scanned = snapshot(&[("recreated", 5), ("unreadable", 6), ("legacy", 7)]);
scanned.buckets_usage.get_mut("legacy").unwrap().bucket_incarnation = None;
let ids = HashMap::from([
("recreated".to_string(), "22222222-2222-4222-8222-222222222222".to_string()),
("legacy".to_string(), "33333333-3333-4333-8333-333333333333".to_string()),
]);
let result = summarize(Some(&scope), Some(&scanned), &ids);
assert_eq!(result.current_buckets, Some(3));
assert_eq!(result.measured_buckets, Some(0));
assert_eq!(result.measured_objects, None);
}
}
+29 -55
View File
@@ -15,7 +15,7 @@
use crate::disk::cleanup_runtime;
use crate::disk::io_admission::{
AdmissionReader, BoxedChunkReader, DiskIoAdmission, DiskIoClass, DiskIoContext, current_disk_io_context,
current_resource_unit, with_detached_disk_io_context, with_disk_io_context, with_disk_io_permit, with_optional_resource_unit,
current_resource_unit, with_disk_io_context, with_disk_io_permit, with_optional_resource_unit,
};
use crate::disk::{
CheckPartsResp, DataDirDeleteStatus, DeleteOptions, DiskAPI, DiskError, DiskInfo, DiskInfoOptions, DiskLocation, Endpoint,
@@ -479,13 +479,10 @@ where
if external_guard.is_none() {
return operation().await;
}
tokio::spawn(with_optional_resource_unit(
current_resource_unit(),
with_detached_disk_io_context(async move {
let _external_guard = external_guard;
operation().await
}),
))
tokio::spawn(with_optional_resource_unit(current_resource_unit(), async move {
let _external_guard = external_guard;
operation().await
}))
.await
.map_err(|_| Error::other("owned mutation task failed"))?
}
@@ -1631,8 +1628,6 @@ pub struct LocalDiskWrapper {
health_check: bool,
/// Cancellation token for monitoring tasks
cancel_token: CancellationToken,
/// Retirement belongs to this wrapper instance, not its monitoring policy.
retired: CancellationToken,
/// Disk ID for stale checking
disk_id: Arc<RwLock<Option<Uuid>>>,
/// Timeout policy for scanner-sensitive operations, loaded once on wrapper initialization.
@@ -1786,7 +1781,6 @@ impl LocalDiskWrapper {
physical_admission: Arc::new(crate::disk::io_admission::PhysicalDiskBinding::default()),
health_check: health_check && env_health_check,
cancel_token: CancellationToken::new(),
retired: CancellationToken::new(),
disk_id: Arc::new(RwLock::new(None)),
timeout_health_policy: get_drive_timeout_health_policy(),
};
@@ -1834,7 +1828,6 @@ impl LocalDiskWrapper {
current_disk_io_context().unwrap_or_else(|| DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: None,
permit: None,
resource_unit: current_resource_unit(),
@@ -1876,9 +1869,29 @@ impl LocalDiskWrapper {
}
async fn acquire_disk_io_permit(&self) -> Result<Option<crate::disk::io_admission::DiskIoPermit>> {
crate::disk::io_admission::acquire_wrapper_disk_io_permit(&self.io_admission)
.await
.map_err(DiskError::Io)
if let Some(context) = current_disk_io_context() {
if let Some(permit) = context.permit
&& permit.is_for(&self.io_admission)
{
return Ok(Some(permit));
}
if context
.admission
.as_ref()
.is_some_and(|admission| Arc::ptr_eq(admission, &self.io_admission))
{
return Ok(None);
}
if context.class == DiskIoClass::Background {
return self
.io_admission
.background(&context.cancellation)
.await
.map(Some)
.map_err(DiskError::Io);
}
}
Ok(Some(self.io_admission.foreground()))
}
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
@@ -1975,11 +1988,6 @@ impl LocalDiskWrapper {
self.cancel_token.cancel();
}
/// Observe retirement without granting callers authority to retire this wrapper.
pub fn retirement_token(&self) -> CancellationToken {
self.retired.child_token()
}
fn spawn_recovery_monitor_if_needed(&self) {
if !self.health_check {
return;
@@ -2455,14 +2463,7 @@ impl LocalDiskWrapper {
transaction: uuid::Uuid,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
) -> Result<
Option<(
crate::disk::DeleteRecoveryJournal,
bool,
bool,
Option<super::local::delete_recovery::LocalPublishedDeleteState>,
)>,
> {
) -> Result<Option<(crate::disk::DeleteRecoveryJournal, bool, bool)>> {
self.track_disk_health_mutation(
"settle_delete_transaction",
DiskMetricMutation::Delete,
@@ -2478,7 +2479,6 @@ impl LocalDiskWrapper {
.await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn try_finish_and_finalize_prepared_delete_local(
&self,
volume: &str,
@@ -2487,7 +2487,6 @@ impl LocalDiskWrapper {
journal: &crate::disk::DeleteRecoveryJournal,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
published_state: Option<super::local::delete_recovery::LocalPublishedDeleteState>,
) -> Result<bool> {
self.track_disk_health_mutation(
"settle_delete_transaction",
@@ -2502,7 +2501,6 @@ impl LocalDiskWrapper {
journal,
namespace_owner,
work_budget,
published_state,
)
.await
})
@@ -2987,7 +2985,6 @@ impl DiskAPI for LocalDiskWrapper {
}
async fn close(&self) -> Result<()> {
self.retired.cancel();
self.stop_monitoring().await;
self.disk.close().await
}
@@ -4412,29 +4409,6 @@ mod tests {
assert!(matches!(wrapper.read_all(volume, &body_path).await, Err(DiskError::FileNotFound)));
}
#[tokio::test]
async fn owned_mutation_retains_background_class_without_waiter_cancellation() {
let cancellation = CancellationToken::new();
let caller = cancellation.clone();
let guard: Arc<dyn Send + Sync> = Arc::new(());
crate::disk::with_background_disk_io(
cancellation,
run_owned_mutation(Some(guard), move || async move {
caller.cancel();
let context = current_disk_io_context().expect("publication owner retains background class");
assert_eq!(context.class, DiskIoClass::Background);
assert!(!context.cancellation.is_cancelled(), "waiter cancellation must not interrupt publication");
assert!(
context.admission_deadline.is_some(),
"queued publication must retain a bounded admission lifetime"
);
Ok(())
}),
)
.await
.expect("owned publication completes");
}
#[tokio::test]
async fn owned_mutation_keeps_publication_guard_after_waiter_cancellation() {
use rustfs_concurrency::adaptive::AdaptiveAdmission;
+1 -11
View File
@@ -139,17 +139,7 @@ pub fn create_dir_all_std(path: &Path) -> io::Result<()> {
match std::fs::create_dir(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent)?;
return match std::fs::create_dir(path) {
Ok(()) => Ok(()),
Err(_) if path.is_dir() => Ok(()),
Err(e) => Err(e),
};
}
std::fs::create_dir_all(path)
}
Err(e) if e.kind() == io::ErrorKind::NotFound => std::fs::create_dir_all(path),
Err(e) => Err(e),
}
}
+25 -335
View File
@@ -161,24 +161,11 @@ pub(crate) enum DiskIoClass {
pub(crate) struct DiskIoContext {
pub(crate) class: DiskIoClass,
pub(crate) cancellation: CancellationToken,
pub(crate) admission_deadline: Option<Instant>,
pub(crate) admission: Option<Arc<DiskIoAdmission>>,
pub(crate) permit: Option<DiskIoPermit>,
pub(crate) resource_unit: Option<ResourceIoUnit>,
}
impl DiskIoContext {
pub(crate) async fn background_permit(&self, admission: &Arc<DiskIoAdmission>) -> io::Result<DiskIoPermit> {
let acquire = admission.background_with_resource(&self.cancellation, self.resource_unit.clone());
match self.admission_deadline {
Some(deadline) => tokio::time::timeout_at(deadline, acquire)
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "owned background disk admission timed out"))?,
None => acquire.await,
}
}
}
/// Mark disk I/O issued by `future` as background work for local-disk admission.
#[doc(hidden)]
pub async fn with_background_disk_io<F: Future>(cancellation: CancellationToken, future: F) -> F::Output {
@@ -186,7 +173,6 @@ pub async fn with_background_disk_io<F: Future>(cancellation: CancellationToken,
DiskIoContext {
class: DiskIoClass::Background,
cancellation,
admission_deadline: None,
admission: None,
permit: None,
resource_unit: current_resource_unit(),
@@ -259,7 +245,6 @@ pub(crate) async fn with_disk_io_permit<F: Future>(permit: Option<DiskIoPermit>,
let mut context = current_disk_io_context().unwrap_or_else(|| DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: None,
permit: None,
resource_unit: None,
@@ -294,122 +279,35 @@ pub(crate) fn with_optional_disk_io_context<F: Future>(
}
}
#[cfg(test)]
tokio::task_local! {
static TEST_CONTEXT_CLONES: std::sync::atomic::AtomicUsize;
}
fn clone_context_with_current_resource_unit(context: &DiskIoContext) -> DiskIoContext {
#[cfg(test)]
let _ = TEST_CONTEXT_CLONES.try_with(|c| c.fetch_add(1, Ordering::Relaxed));
let mut cloned = context.clone();
if let Ok(unit) = RESOURCE_IO_UNIT.try_with(Clone::clone) {
cloned.resource_unit = Some(unit);
}
cloned
}
/// An owned commit outlives its waiter. Retain an outer I/O class and physical
/// ownership, but give admission its own cancellation lifetime. Leave per-disk
/// scopes to the caller's existing ownership handoff: inheriting their class
/// without a lease could wait behind the parent awaiting this commit.
/// The drive timeout bounds only queued admission; an admitted mutation still
/// drains to completion. Nested owners retain the original admission deadline.
pub(crate) fn with_detached_disk_io_context<F: Future>(future: F) -> impl Future<Output = F::Output> {
let context = DISK_IO_CONTEXT
pub(crate) fn current_disk_io_context() -> Option<DiskIoContext> {
DISK_IO_CONTEXT
.try_with(|context| {
(context.admission.is_none() && context.permit.is_none()).then(|| {
let mut context = clone_context_with_current_resource_unit(context);
context.cancellation = CancellationToken::new();
let timeout = super::disk_store::get_max_timeout_duration();
if context.class == DiskIoClass::Background
&& !timeout.is_zero()
&& let Some(deadline) = Instant::now().checked_add(timeout)
{
context.admission_deadline = Some(context.admission_deadline.map_or(deadline, |old| old.min(deadline)));
}
context
})
let mut context = context.clone();
if let Ok(unit) = RESOURCE_IO_UNIT.try_with(Clone::clone) {
context.resource_unit = Some(unit);
}
context
})
.ok()
.flatten();
async move {
match context {
Some(context) => with_disk_io_context(context, future).await,
None => future.await,
}
}
}
pub(crate) fn current_disk_io_context() -> Option<DiskIoContext> {
DISK_IO_CONTEXT.try_with(clone_context_with_current_resource_unit).ok()
}
pub(crate) async fn acquire_wrapper_disk_io_permit(admission: &Arc<DiskIoAdmission>) -> io::Result<Option<DiskIoPermit>> {
enum WrapperPermitAction {
Immediate(Option<DiskIoPermit>),
Background(DiskIoContext),
}
let action = match DISK_IO_CONTEXT.try_with(|context| {
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(admission)
{
return WrapperPermitAction::Immediate(Some(permit.clone()));
}
if context
.admission
.as_ref()
.is_some_and(|ctx_admission| Arc::ptr_eq(ctx_admission, admission))
{
return WrapperPermitAction::Immediate(None);
}
match context.class {
DiskIoClass::Foreground => WrapperPermitAction::Immediate(Some(admission.foreground())),
DiskIoClass::Background => WrapperPermitAction::Background(clone_context_with_current_resource_unit(context)),
}
}) {
Ok(action) => action,
Err(_) => return Ok(Some(admission.foreground())),
};
match action {
WrapperPermitAction::Immediate(permit) => Ok(permit),
WrapperPermitAction::Background(context) => context.background_permit(admission).await.map(Some),
}
}
/// Acquire one low-level permit only when the current walker explicitly owns a gate.
/// Ordinary wrapper calls use their outer operation permit instead.
pub(crate) async fn acquire_context_disk_io_permit() -> io::Result<Option<DiskIoPermit>> {
enum ContextPermitAction {
Immediate(Option<DiskIoPermit>),
Background(Arc<DiskIoAdmission>, DiskIoContext),
}
let action = match DISK_IO_CONTEXT.try_with(|context| {
let Some(admission) = context.admission.as_ref() else {
return ContextPermitAction::Immediate(None);
};
if let Some(permit) = context.permit.as_ref()
&& permit.is_for(admission)
{
return ContextPermitAction::Immediate(Some(permit.clone()));
}
match context.class {
DiskIoClass::Foreground => ContextPermitAction::Immediate(Some(admission.foreground())),
DiskIoClass::Background => {
ContextPermitAction::Background(Arc::clone(admission), clone_context_with_current_resource_unit(context))
}
}
}) {
Ok(action) => action,
Err(_) => return Ok(None),
let Some(context) = current_disk_io_context() else {
return Ok(None);
};
match action {
ContextPermitAction::Immediate(permit) => Ok(permit),
ContextPermitAction::Background(admission, context) => context.background_permit(&admission).await.map(Some),
let Some(admission) = context.admission else {
return Ok(None);
};
if let Some(permit) = context.permit
&& permit.is_for(&admission)
{
return Ok(Some(permit));
}
match context.class {
DiskIoClass::Foreground => Ok(Some(admission.foreground())),
DiskIoClass::Background => Ok(Some(admission.background(&context.cancellation).await?)),
}
}
@@ -483,7 +381,6 @@ impl DiskIoAdmission {
}
}
#[cfg(test)]
pub(crate) async fn background(self: &Arc<Self>, cancellation: &CancellationToken) -> std::io::Result<DiskIoPermit> {
self.background_with_resource(cancellation, current_resource_unit()).await
}
@@ -766,8 +663,11 @@ impl<R> AdmissionReader<R> {
let mut wait = self.wait.lock().unwrap_or_else(|error| error.into_inner());
if wait.is_none() {
let admission = self.admission.clone();
let context = self.context.clone();
*wait = Some(Box::pin(async move { context.background_permit(&admission).await }));
let cancellation = self.context.cancellation.clone();
let resource_unit = self.context.resource_unit.clone();
*wait = Some(Box::pin(
async move { admission.background_with_resource(&cancellation, resource_unit).await },
));
}
let Some(wait_future) = wait.as_mut() else {
return Poll::Ready(Err(io::Error::other("background disk I/O admission waiter is missing")));
@@ -1009,7 +909,6 @@ mod tests {
let existing = DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: cancellation.clone(),
admission_deadline: None,
admission: None,
permit: None,
resource_unit: None,
@@ -1055,94 +954,6 @@ mod tests {
assert_eq!(gate.snapshot().active, 0);
}
#[tokio::test(start_paused = true)]
async fn detached_commit_keeps_background_admission_after_waiter_cancellation() {
let admission = DiskIoAdmission::new("detached-commit".to_string());
let foreground = admission.foreground();
let cancellation = CancellationToken::new();
let worker_admission = admission.clone();
with_background_disk_io(cancellation.clone(), async {
let worker = tokio::spawn(with_detached_disk_io_context(async move {
let context = current_disk_io_context().expect("owned commit retains its class");
assert_eq!(context.class, DiskIoClass::Background);
context.background_permit(&worker_admission).await
}));
wait_for_background_waiters(&admission, 1).await;
cancellation.cancel();
tokio::task::yield_now().await;
assert!(!worker.is_finished(), "caller cancellation must not abandon a queued commit");
drop(foreground);
let permit = tokio::time::timeout(Duration::from_secs(1), worker)
.await
.expect("commit admission should finish after foreground work")
.expect("owned worker joins")
.expect("owned commit survives waiter cancellation");
assert_eq!(admission.background_admissions_for_tests(), 1);
drop(permit);
})
.await;
assert!(!admission.background_active_for_tests());
}
#[tokio::test]
async fn detached_commit_does_not_inherit_a_parent_disk_lease() {
let admission = DiskIoAdmission::new("parent-lease".to_string());
let cancellation = CancellationToken::new();
let permit = admission.background(&cancellation).await.expect("parent disk admission");
with_background_disk_io(
cancellation,
with_disk_io_permit(Some(permit), async {
tokio::spawn(with_detached_disk_io_context(async {
assert!(current_disk_io_context().is_none(), "do not queue behind the parent's disk lease");
}))
.await
.expect("resource-only commit joins while parent keeps its disk lease");
assert!(admission.background_active_for_tests());
}),
)
.await;
assert!(!admission.background_active_for_tests());
}
#[tokio::test(start_paused = true)]
async fn detached_commit_bounds_queued_admission_without_extending_an_existing_deadline() {
let admission = DiskIoAdmission::new("stalled-background-disk");
let held = admission
.background(&CancellationToken::new())
.await
.expect("existing native I/O");
let deadline = Instant::now() + Duration::from_secs(2);
let worker_admission = admission.clone();
let error = with_background_disk_io(CancellationToken::new(), async {
let mut context = current_disk_io_context().expect("background scope");
context.admission_deadline = Some(deadline);
with_disk_io_context(context, async {
let worker = tokio::spawn(with_detached_disk_io_context(async move {
let context = current_disk_io_context().expect("owned scope");
assert_eq!(
context.admission_deadline,
Some(deadline),
"nested ownership must not reset admission time"
);
context.background_permit(&worker_admission).await
}));
wait_for_background_waiters(&admission, 1).await;
tokio::time::advance(Duration::from_secs(2)).await;
worker
.await
.expect("owned admission worker")
.expect_err("stalled disk must not retain queued commit")
})
.await
})
.await;
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
assert_eq!(admission.background_waiters.load(Ordering::Acquire), 0);
assert!(admission.background_active_for_tests(), "timeout must not interrupt admitted native I/O");
drop(held);
assert!(!admission.background_active_for_tests());
}
struct BlockingWorker(tokio::task::JoinHandle<()>);
async fn wait_for_background_waiters(admission: &DiskIoAdmission, expected: usize) {
@@ -1261,7 +1072,6 @@ mod tests {
DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: None,
permit: None,
resource_unit: None,
@@ -1332,124 +1142,4 @@ mod tests {
assert!(tokio::time::timeout(Duration::from_millis(10), worker.0).await.is_err());
wait_for_foreground_active(&admission, 0).await;
}
#[tokio::test]
async fn wrapper_and_context_permit_fast_paths_avoid_context_clones_and_preserve_resource_projection() {
use rustfs_concurrency::adaptive::AdaptiveAdmission;
use std::num::NonZeroU16;
use std::sync::atomic::AtomicUsize;
TEST_CONTEXT_CLONES
.scope(AtomicUsize::new(0), async {
let take_clones = || TEST_CONTEXT_CLONES.with(|c| c.swap(0, Ordering::Relaxed));
let admission = DiskIoAdmission::new("disk-fast");
let other_admission = DiskIoAdmission::new("disk-other");
// 1. No ambient context: wrapper returns Foreground permit, walker context returns None, 0 clones.
let wrapper_p = acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper permit")
.expect("foreground permit");
drop(wrapper_p);
assert!(acquire_context_disk_io_permit().await.expect("walker permit").is_none());
assert_eq!(take_clones(), 0);
// 2. Foreground context with admission=Some(admission), permit=None:
// - wrapper sees matching admission and returns Ok(None) (walker owns per-step permits)
// - walker acquires a Foreground permit from context.admission
// - 0 context clones.
let fg_ctx = DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: None,
resource_unit: None,
};
with_disk_io_context(fg_ctx, async {
assert!(
acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper under walker")
.is_none()
);
let step_p = acquire_context_disk_io_permit()
.await
.expect("walker step")
.expect("walker foreground permit");
assert!(step_p.is_for(&admission));
let other_p = acquire_wrapper_disk_io_permit(&other_admission)
.await
.expect("other disk wrapper")
.expect("other disk foreground permit");
assert!(other_p.is_for(&other_admission));
})
.await;
assert_eq!(take_clones(), 0);
// 3. Permit-match fast path on both helpers: 0 context clones.
let held_permit = admission.foreground();
let permit_ctx = DiskIoContext {
class: DiskIoClass::Foreground,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: Some(held_permit),
resource_unit: None,
};
with_disk_io_context(permit_ctx, async {
let wp = acquire_wrapper_disk_io_permit(&admission)
.await
.expect("wrapper permit match")
.expect("matched permit");
assert!(wp.is_for(&admission));
let cp = acquire_context_disk_io_permit()
.await
.expect("context permit match")
.expect("matched context permit");
assert!(cp.is_for(&admission));
})
.await;
assert_eq!(take_clones(), 0);
// 4. Background context with inner RESOURCE_IO_UNIT override preserved across with_detached_disk_io_context.
let adaptive = AdaptiveAdmission::new(NonZeroU16::new(2).expect("two units"), 2);
let outer_unit = adaptive.acquire().await;
let inner_unit = adaptive.acquire().await;
with_background_disk_io(
CancellationToken::new(),
with_background_resource_unit(outer_unit, async {
with_background_resource_unit(inner_unit, async {
let bg_ctx = DiskIoContext {
class: DiskIoClass::Background,
cancellation: CancellationToken::new(),
admission_deadline: None,
admission: Some(admission.clone()),
permit: None,
resource_unit: None,
};
with_disk_io_context(bg_ctx, async {
let bg_step = acquire_context_disk_io_permit()
.await
.expect("background walker step")
.expect("background walker permit");
assert!(bg_step.is_for(&admission));
})
.await;
assert!(take_clones() >= 1, "background path must clone context with resource unit");
let spawned = tokio::spawn(with_detached_disk_io_context(async {
let ctx = current_disk_io_context().expect("detached background context");
assert_eq!(ctx.class, DiskIoClass::Background);
assert!(ctx.resource_unit.is_some(), "inner resource unit must be merged");
}));
spawned.await.expect("detached task joins");
})
.await;
}),
)
.await;
})
.await;
}
}
+8 -51
View File
@@ -79,21 +79,12 @@ impl BackgroundMemoryBudget {
pub(crate) fn reserve(self: &Arc<Self>, bytes: usize) -> io::Result<Reservation> {
let bytes = u64::try_from(bytes).map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?;
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let expired = Instant::now() >= state.valid_until;
let exhausted = || {
io::Error::new(
io::ErrorKind::WouldBlock,
BackgroundMemoryExhausted {
requested: bytes,
used: state.used,
limit: state.limit,
expired,
},
)
};
let used = state.used.checked_add(bytes).ok_or_else(exhausted)?;
if bytes != 0 && (expired || used > state.limit) {
return Err(exhausted());
let used = state
.used
.checked_add(bytes)
.ok_or_else(|| io::Error::new(io::ErrorKind::WouldBlock, BackgroundMemoryExhausted))?;
if bytes != 0 && (Instant::now() >= state.valid_until || used > state.limit) {
return Err(io::Error::new(io::ErrorKind::WouldBlock, BackgroundMemoryExhausted));
}
state.used = used;
Ok(Reservation {
@@ -104,20 +95,11 @@ impl BackgroundMemoryBudget {
}
#[derive(Debug)]
struct BackgroundMemoryExhausted {
requested: u64,
used: u64,
limit: u64,
expired: bool,
}
struct BackgroundMemoryExhausted;
impl std::fmt::Display for BackgroundMemoryExhausted {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"background buffer memory budget exhausted (requested={}, used={}, limit={}, expired={})",
self.requested, self.used, self.limit, self.expired,
)
formatter.write_str("background buffer memory budget exhausted")
}
}
@@ -339,31 +321,6 @@ impl io::Write for BackgroundEncodeBuffer {
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn rejected_reservation_reports_capacity_and_expiration_without_charging() {
let owner = BackgroundMemoryBudget::new();
owner.set_sampled_limit(64, Duration::from_secs(3));
let held = owner.reserve(32).expect("initial reservation fits");
let error = owner.reserve(33).err().expect("one byte over remaining capacity");
assert!(is_memory_pressure(&error));
assert_eq!(
error.to_string(),
"background buffer memory budget exhausted (requested=33, used=32, limit=64, expired=false)"
);
assert_eq!(owner.snapshot().used, 32);
tokio::time::advance(Duration::from_secs(3)).await;
let error = owner.reserve(1).err().expect("expired lease rejects a fitting request");
assert!(is_memory_pressure(&error));
assert_eq!(
error.to_string(),
"background buffer memory budget exhausted (requested=1, used=32, limit=64, expired=true)"
);
assert_eq!(owner.snapshot().used, 32);
drop(held);
assert_eq!(owner.snapshot().used, 0);
}
#[test]
fn encoded_buffer_growth_retains_both_allocations_and_the_last_slice() {
use std::io::Write;
@@ -140,28 +140,6 @@ pub(crate) fn admit(binding: &PhysicalDiskBinding) -> io::Result<()> {
.unwrap_or(Ok(()))
}
/// Wait only at the namespace RPC entry, before storage locks or native I/O.
/// The caller owns the deadline; dropping this future releases its queue turn.
pub(crate) async fn admit_scanner_preflight(binding: &PhysicalDiskBinding) -> io::Result<()> {
let node = REMOTE_RESOURCES
.try_with(|context| context.admitted.borrow().is_none().then(|| context.node.clone()))
.ok()
.flatten();
let Some(node) = node else {
return admit(binding);
};
let deferred = || io::Error::from(io::ErrorKind::WouldBlock);
let plan = binding.plan().ok_or_else(deferred)?;
let permit = plan.acquire(&node).await.ok_or_else(deferred)?;
REMOTE_RESOURCES.with(|context| {
let mut admitted = context.admitted.borrow_mut();
if admitted.is_none() {
*admitted = Some(permit);
}
});
admit(binding)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -184,76 +162,6 @@ mod tests {
node
}
#[tokio::test(start_paused = true)]
async fn scanner_preflight_cancellation_and_timeout_release_queued_capacity() {
let node = node();
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
let binding = PhysicalDiskBinding::default();
binding.set_test_capacity(vec![gate.clone()]).expect("device plan");
for deadline in [false, true] {
let held = gate.try_acquire().expect("concurrent disk operation");
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
let mut wait = Box::pin(admit_scanner_preflight(&binding));
assert!(futures_util::poll!(&mut wait).is_pending());
assert_eq!(node.snapshot().active, 0, "queued disk work cannot reserve node capacity");
if deadline {
assert!(tokio::time::timeout(std::time::Duration::from_secs(1), wait).await.is_err());
} else {
drop(wait);
}
drop(held);
admit(&binding).expect("cancelled queue turn cannot block the immediate path");
})
.await;
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
assert_eq!([node.completed(), gate.completed()], [Some(0), Some(0)]);
}
}
#[tokio::test]
async fn scanner_preflight_rejects_a_plan_replaced_while_waiting() {
let node = node();
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
let binding = PhysicalDiskBinding::default();
binding.set_test_capacity(vec![gate.clone()]).expect("old plan");
let held = gate.try_acquire().expect("busy disk");
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
let wait = admit_scanner_preflight(&binding);
tokio::pin!(wait);
assert!(futures_util::poll!(&mut wait).is_pending());
binding
.set_test_capacity(vec![AdaptiveAdmission::new(NonZeroU16::MIN, 1)])
.expect("new plan");
drop(held);
assert_eq!(wait.await.expect_err("old plan is invalid").kind(), io::ErrorKind::WouldBlock);
assert!(resources().is_none());
})
.await;
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
assert_eq!(node.completed(), Some(0));
}
#[tokio::test]
async fn scanner_preflight_never_waits_for_additional_devices_under_existing_admission() {
let node = node();
let first = PhysicalDiskBinding::default();
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
first.set_test_capacity(vec![gate.clone()]).expect("first plan");
let other = PhysicalDiskBinding::default();
other
.set_test_capacity(vec![AdaptiveAdmission::new(NonZeroU16::MIN, 0)])
.expect("closed plan");
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
admit(&first).expect("existing request admission");
let other = admit_scanner_preflight(&other);
tokio::pin!(other);
assert!(matches!(futures_util::poll!(other), std::task::Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::WouldBlock));
assert_eq!([node.snapshot().active, gate.snapshot().active], [1, 1]);
})
.await;
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
}
#[tokio::test]
async fn receiver_reuses_one_receipt_across_phases_and_releases_only_native_subsets() {
let node = node();
File diff suppressed because it is too large Load Diff
+6 -21
View File
@@ -744,7 +744,7 @@ impl LocalDisk {
}
}
if dst_volume == crate::disk::RUSTFS_META_BUCKET {
crate::bucket::metadata_sys::maybe_bump_local_meta_mutation_gen_for_path(dst_volume, dst_path);
crate::bucket::metadata_sys::bump_local_meta_mutation_gen();
}
if fi.is_legacy_indexed_delete_marker() {
fi.erasure.index = 0;
@@ -864,13 +864,6 @@ impl LocalDisk {
} else {
None
};
// Healing a transitioned object stages no data dir, so nothing has created its tmp source parent.
let remote_metadata_source = no_inline
&& fi.is_remote()
&& has_data_dir_path.is_none()
&& multipart_publication.is_none()
&& src_volume == super::super::RUSTFS_META_TMP_BUCKET;
let create_source_parent = (!no_inline || remote_metadata_source) && !preserve_upload_metadata;
if multipart_publication.is_none()
&& let Some((source_directory, target_directory)) = has_data_dir_path.as_ref()
@@ -950,7 +943,7 @@ impl LocalDisk {
let fused_attempt = move |is_cancelled: &dyn Fn() -> bool| -> std::io::Result<FusedCommitAttempt> {
let source_mode = if flat_inline_tmp {
SourcePreparationMode::FlatInlineTmp { defer_dst_preflight }
} else if !no_inline || remote_metadata_source {
} else if !no_inline {
SourcePreparationMode::CreateParent
} else {
SourcePreparationMode::ExistingParent
@@ -982,26 +975,18 @@ impl LocalDisk {
Box::new(fi_moved),
));
}
let version_id = fi_moved.version_id.unwrap_or_default();
let mut xlmeta = FileMeta::new();
let mut dst_meta_unparsable = false;
if let Some(ref old_file) = old_destination_file {
if FileMeta::is_xl2_v1_format(&old_file.bytes)
&& let Ok((mut nmeta, old_inline_buf)) = FileMeta::load_with_borrowed_inline_data(&old_file.bytes)
&& let Ok(nmeta) = FileMeta::load(&old_file.bytes)
{
if !old_inline_buf.is_empty()
&& nmeta
.versions
.iter()
.any(|v| v.header.version_id.unwrap_or_default() != version_id)
{
nmeta.data.update(old_inline_buf);
}
xlmeta = nmeta;
} else {
dst_meta_unparsable = true;
}
}
let version_id = fi_moved.version_id.unwrap_or_default();
let has_old_data_dir = xlmeta.find_unshared_data_dir_for_version(Some(version_id));
let rollback_data_dir = has_old_data_dir.or_else(|| {
if old_destination_file.is_some() && xlmeta.find_version(Some(version_id)).is_ok() {
@@ -1708,7 +1693,7 @@ impl LocalDisk {
}
} else {
prepare_rename_commit_and_destination_metadata(
create_source_parent,
!no_inline && !preserve_upload_metadata,
src_file_parent,
dst_file_parent,
&dst_file_path,
@@ -1724,7 +1709,7 @@ impl LocalDisk {
// Multipart authority already created its source tree. Recreating it
// here would resurrect staging retired before a delayed request arrived.
let (rename_commit_guard, has_dst_buf) = prepare_rename_commit_and_destination_metadata(
create_source_parent,
!no_inline && !preserve_upload_metadata,
src_file_parent,
dst_file_parent,
&dst_file_path,
File diff suppressed because it is too large Load Diff
@@ -122,27 +122,17 @@ fn validate_certificate_shape(
}
impl LocalDisk {
// Separate inspection, abort and recovery layouts, and construct the
// selected boxed future outside caller poll frames.
// Give readonly inspection its own future layout while retaining one
// selected Box per request and constructing it outside caller poll frames.
#[inline(never)]
pub(super) fn recover_multipart_source_native(
&self,
request: MultipartSourceRequest,
) -> impl std::future::Future<Output = Result<MultipartSourceResponse>> + Send + '_ {
match &request.operation {
MultipartSourceOperation::Inspect { .. } => {
futures::future::Either::Left(Box::pin(self.inspect_multipart_source_native(request)))
}
MultipartSourceOperation::UpgradeLegacy { .. }
| MultipartSourceOperation::PrepareAbort { .. }
| MultipartSourceOperation::CommitAbort { .. }
| MultipartSourceOperation::DeleteAborted { .. }
| MultipartSourceOperation::ConfirmCleanupTarget { .. } => futures::future::Either::Right(
futures::future::Either::Left(Box::pin(self.abort_multipart_source_native(request))),
),
_ => futures::future::Either::Right(futures::future::Either::Right(Box::pin(
self.recover_multipart_source_native_inner(request),
))),
if matches!(&request.operation, MultipartSourceOperation::Inspect { .. }) {
futures::future::Either::Left(Box::pin(self.inspect_multipart_source_native(request)))
} else {
futures::future::Either::Right(Box::pin(self.recover_multipart_source_native_inner(request)))
}
}
@@ -190,24 +180,20 @@ impl LocalDisk {
}))
}
async fn abort_multipart_source_native(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
request.validate()?;
let store = self.open_multipart_source_store(&request.path, None).await?;
self.recover_multipart_abort_owned(store, request.operation).await
}
async fn recover_multipart_source_native_inner(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
request.validate()?;
// Source RW ownership precedes source namespace, target metadata, and
// target publication ownership. Every filesystem tail retains it.
let store = self.open_multipart_source_store(&request.path, None).await?;
match request.operation {
MultipartSourceOperation::Inspect { .. }
| MultipartSourceOperation::UpgradeLegacy { .. }
operation @ (MultipartSourceOperation::UpgradeLegacy { .. }
| MultipartSourceOperation::PrepareAbort { .. }
| MultipartSourceOperation::CommitAbort { .. }
| MultipartSourceOperation::DeleteAborted { .. }
| MultipartSourceOperation::ConfirmCleanupTarget { .. } => Err(DiskError::UnsupportedDisk),
| MultipartSourceOperation::ConfirmCleanupTarget { .. }) => {
self.recover_multipart_abort_owned(store, operation).await
}
MultipartSourceOperation::Inspect { .. } => Err(DiskError::UnsupportedDisk),
MultipartSourceOperation::Claim { expected, round } => {
let loaded = store.load().await?;
require_expected(&loaded, &expected)?;
@@ -316,18 +316,11 @@ pub(super) fn put_active_multipart_source_head(source: impl AsRef<Path>, raw: By
}
fn stamp_matches_active_disk(source: &Path, expected_head_stamp: FileStamp) -> bool {
let stamp_matches = FileStamp::from_path(&source.join(STORAGE_FORMAT_FILE)) == Some(expected_head_stamp);
#[cfg(test)]
{
stamp_matches
&& !source.join(STATE).exists()
&& !source.join(crate::disk::MULTIPART_RECOVERY_DIR).exists()
&& !source.join(".mpu-completions").exists()
}
#[cfg(not(test))]
{
stamp_matches
}
FileStamp::from_path(&source.join(STORAGE_FORMAT_FILE)) == Some(expected_head_stamp)
&& !(cfg!(test)
&& (source.join(STATE).exists()
|| source.join(crate::disk::MULTIPART_RECOVERY_DIR).exists()
|| source.join(".mpu-completions").exists()))
}
pub(super) fn get_active_multipart_source_head(source: &Path) -> Option<(Bytes, FileInfo)> {
@@ -607,13 +600,11 @@ impl SourceStore {
let disk_id = self.disk_id;
let physical_slot = self.physical_slot;
let disk_ids = self.disk_ids.clone();
// Keep the loaded state out of each blocking-queue and oneshot poll frame.
os::run_blocking_namespace_operation(self.lease.clone(), move || {
Ok(load_source(&source, &base, &root, &path, disk_id, physical_slot, &disk_ids).map(Box::new))
Ok(load_source(&source, &base, &root, &path, disk_id, physical_slot, &disk_ids))
})
.await
.map_err(DiskError::from)?
.map(|loaded| *loaded)
}
pub async fn persist(&self, state: &SourceState) -> Result<()> {
self.persist_with_source_sync(state, false).await.map(|_| ())
+2 -49
View File
@@ -45,7 +45,7 @@ pub use local::pool_meta_native::{PoolMetaNativeCasCondition, PoolMetaNativeFile
pub(crate) use io_admission::{DiskIoClass, test_resource_units};
pub(crate) use io_admission::{
PhysicalHealBinding, acquire_context_disk_io_permit, current_disk_io_context, current_resource_unit, has_resource_io_scope,
with_detached_disk_io_context, with_optional_disk_io_context, with_optional_resource_unit,
with_optional_disk_io_context, with_optional_resource_unit,
};
pub const RUSTFS_META_BUCKET: &str = ".rustfs.sys";
@@ -77,8 +77,6 @@ pub fn validate_format_control_path(path: &str) -> Result<()> {
/// Per-disk marker present while an erasure-set heal is rebuilding this disk.
/// `LocalDisk::disk_info` reports `healing = true` while the file exists.
pub const HEALING_MARKER_PATH: &str = "healing.bin";
/// Boot-time crash fence and clean scanner continuity receipt.
pub const UNCLEAN_SHUTDOWN_MARKER_PATH: &str = "unclean-shutdown";
pub const STORAGE_FORMAT_FILE: &str = "xl.meta";
pub const STORAGE_FORMAT_FILE_BACKUP: &str = "xl.meta.bkp";
/// Original upload authority after it stops admitting active part mutations.
@@ -121,7 +119,6 @@ use sha2::Digest as _;
use std::{fmt::Debug, path::PathBuf, sync::Arc, time::Duration};
use time::OffsetDateTime;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
/// Independent admission and physical ownership for one disk rename.
@@ -242,14 +239,6 @@ pub enum PoolMetaNativeRecoveryResponse {
pub type DiskStore = Arc<Disk>;
/// Filesystem evidence for a replacement data directory on its expected mount.
#[derive(Debug)]
pub struct ReplacementMount {
pub canonical_path: PathBuf,
pub physical_device_ids: Vec<String>,
pub filesystem_identity: String,
}
pub trait DiskFileWriter: AsyncWrite + Send + Sync + Unpin + std::any::Any {}
impl<T: AsyncWrite + Send + Sync + Unpin + 'static> DiskFileWriter for T {}
@@ -356,14 +345,6 @@ pub enum Disk {
}
impl Disk {
/// Open format metadata through the control transport, including before shard I/O is available.
pub(crate) async fn read_format_control(&self, volume: &str, path: &str) -> Result<FileReader> {
match self {
Self::Local(disk) => disk.read_file(volume, path).await,
Self::Remote(disk) => disk.read_format_control(volume, path).await,
}
}
/// Physical ownership belongs to the node hosting the local attachment.
pub fn physical_admission(&self) -> Option<Arc<PhysicalDiskBinding>> {
match self {
@@ -468,14 +449,7 @@ impl Disk {
transaction: Uuid,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
) -> Result<
Option<(
DeleteRecoveryJournal,
bool,
bool,
Option<local::delete_recovery::LocalPublishedDeleteState>,
)>,
> {
) -> Result<Option<(DeleteRecoveryJournal, bool, bool)>> {
match self {
Self::Local(disk) => {
disk.try_publish_prepared_delete_local(volume, object, transaction, namespace_owner, work_budget)
@@ -485,7 +459,6 @@ impl Disk {
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn try_finish_and_finalize_prepared_delete_local(
&self,
volume: &str,
@@ -494,7 +467,6 @@ impl Disk {
journal: &DeleteRecoveryJournal,
namespace_owner: Option<Arc<dyn Send + Sync>>,
work_budget: Option<Arc<crate::object_api::DeleteRecoveryWorkBudget>>,
published_state: Option<local::delete_recovery::LocalPublishedDeleteState>,
) -> Result<bool> {
match self {
Self::Local(disk) => {
@@ -505,7 +477,6 @@ impl Disk {
journal,
namespace_owner,
work_budget,
published_state,
)
.await
}
@@ -1489,15 +1460,6 @@ impl Disk {
}
}
/// Observe a local wrapper's retirement. Remote handles have their own RPC lifecycle.
/// Cancelling the returned child token does not retire the underlying wrapper.
pub fn local_retirement_token(&self) -> Option<CancellationToken> {
match self {
Disk::Local(local_disk) => Some(local_disk.retirement_token()),
Disk::Remote(_) => None,
}
}
pub fn offline_duration_secs(&self) -> Option<u64> {
match self {
Disk::Local(local_disk) => local_disk.offline_duration_secs(),
@@ -1621,15 +1583,6 @@ impl Disk {
}
}
/// Observe the expected mount through the same local disk handle that will
/// execute recovery. Call from a blocking context.
pub fn replacement_mount(&self, mount_roots: &[PathBuf]) -> Option<ReplacementMount> {
match self {
Self::Local(disk) => disk.get_disk().replacement_mount(mount_roots),
Self::Remote(_) => None,
}
}
pub async fn acquire_replacement_execution_lease(&self) -> Result<std::sync::Arc<local::ReplacementExecutionLease>> {
match self {
Self::Local(disk) => disk.get_disk().acquire_replacement_execution_lease().await,
+26 -117
View File
@@ -417,33 +417,11 @@ pub(crate) mod prepared_publication_test_hooks {
}
pub(crate) fn has_any_hooks() -> bool {
let before_publication = !BEFORE_PUBLICATION.lock().is_empty();
#[cfg(test)]
{
before_publication || !RENAME_DESTINATIONS.lock().is_empty() || !HARDLINK_DESTINATIONS.lock().is_empty()
}
#[cfg(not(test))]
{
before_publication
}
}
#[cfg(target_os = "linux")]
pub(crate) fn has_rename_hooks(source: &Path, destination: &Path) -> bool {
let before_publication = {
let guard = BEFORE_PUBLICATION.lock();
!guard.is_empty()
&& (guard.contains_key(&(Stage::Rename, source.to_path_buf()))
|| guard.contains_key(&(Stage::Rename, destination.to_path_buf())))
};
#[cfg(test)]
{
before_publication || RENAME_DESTINATIONS.lock().contains_key(source)
}
#[cfg(not(test))]
{
before_publication
if !RENAME_DESTINATIONS.lock().is_empty() || !HARDLINK_DESTINATIONS.lock().is_empty() {
return true;
}
!BEFORE_PUBLICATION.lock().is_empty()
}
#[cfg(test)]
@@ -2689,7 +2667,6 @@ pub(crate) const MAX_FSYNC_WORKERS_PER_DISK: usize = 8;
// Return busy workers to the shared pool so other disks can acquire a slot.
const MAX_BLOCKING_JOBS_PER_WORKER: usize = 64;
const WORKER_IDLE_SPIN_ITERS: usize = 256;
const FSYNC_IDLE_YIELD_ITERS: usize = 2;
const DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 256;
const MAX_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 1024;
const FALLBACK_NAMESPACE_QUEUE_SHARDS: usize = 8;
@@ -2888,11 +2865,6 @@ impl DiskBlockingQueue {
self.lanes.iter().map(|lane| lane.state.lock().submitted_jobs).sum()
}
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn submitted_fsync_jobs_for_test(&self) -> usize {
self.lane(DiskBlockingLane::Fsync).state.lock().submitted_jobs
}
#[inline]
fn foreground_lane() -> DiskBlockingLane {
if is_isolated_io_thread() {
@@ -2995,18 +2967,6 @@ impl DiskBlockingQueue {
std::hint::spin_loop();
spun += 1;
}
if lane == DiskBlockingLane::Fsync
&& spin_iters > 0
&& spun == spin_iters
&& !queue.lane(lane).ready.load(std::sync::atomic::Ordering::Relaxed)
{
for _ in 0..FSYNC_IDLE_YIELD_ITERS {
std::thread::yield_now();
if queue.lane(lane).ready.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
}
}
if let Some(metrics) = spin_metrics {
metrics.finish(spun);
}
@@ -3307,37 +3267,6 @@ fn disk_namespace_mutation_lock_by_key(key: &[u8]) -> Arc<NamespaceMutationLock>
static DISK_METADATA_MUTATION_LOCKS: LazyLock<ShardedPathLockRegistry<NamespaceMutationLock>> =
LazyLock::new(ShardedPathLockRegistry::new);
/// Distinct handle for the per-object metadata mutation lock domain so callers
/// cannot accidentally swap metadata and namespace lock handles across stages.
#[derive(Clone)]
pub(crate) struct MetadataMutationLockHandle(Arc<NamespaceMutationLock>);
impl MetadataMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
/// Distinct handle for the per-path namespace mutation lock domain.
#[derive(Clone)]
pub(in crate::disk) struct NamespaceMutationLockHandle(Arc<NamespaceMutationLock>);
impl NamespaceMutationLockHandle {
#[cfg(test)]
pub(crate) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
pub(crate) fn lookup_metadata_mutation_lock(object: &Path) -> MetadataMutationLockHandle {
MetadataMutationLockHandle(DISK_METADATA_MUTATION_LOCKS.get_or_create(object, || AsyncMutex::new(())))
}
pub(in crate::disk) fn lookup_namespace_mutation_lock(path: &Path) -> NamespaceMutationLockHandle {
NamespaceMutationLockHandle(disk_namespace_mutation_lock(path))
}
/// Serializes the complete xl.meta read/modify/commit transaction. This domain
/// precedes namespace/volume publication locks, whose narrower syscall leases
/// may retain it after cancellation of the async caller.
@@ -3350,16 +3279,9 @@ pub(crate) async fn acquire_metadata_mutation_lease(
object: &Path,
owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<MetadataMutationLease> {
let lock = lookup_metadata_mutation_lock(object);
acquire_metadata_mutation_lease_with_lock(&lock, owner).await
}
pub(crate) async fn acquire_metadata_mutation_lease_with_lock(
lock: &MetadataMutationLockHandle,
owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<MetadataMutationLease> {
let lock = DISK_METADATA_MUTATION_LOCKS.get_or_create(object, || AsyncMutex::new(()));
Arc::new(MetadataMutationLease {
_guard: lock.0.clone().lock_owned().await,
_guard: lock.lock_owned().await,
_owner: owner,
})
}
@@ -3396,25 +3318,8 @@ pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_owner(
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
let blocking_queue = disk_blocking_queue_for_path(path);
acquire_namespace_mutation_lease_with_queue(path, blocking_queue, namespace_owner).await
}
pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_queue(
path: &Path,
blocking_queue: Arc<DiskBlockingQueue>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
let lock = lookup_namespace_mutation_lock(path);
acquire_namespace_mutation_lease_with_lock_and_queue(&lock, blocking_queue, namespace_owner).await
}
pub(in crate::disk) async fn acquire_namespace_mutation_lease_with_lock_and_queue(
lock: &NamespaceMutationLockHandle,
blocking_queue: Arc<DiskBlockingQueue>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
) -> Arc<NamespaceMutationLease> {
Arc::new(NamespaceMutationLease {
_namespace_guard: lock.0.clone().lock_owned().await,
_namespace_guard: disk_namespace_mutation_lock(path).lock_owned().await,
_staging_guard: None,
_volume_guard: None,
external_guard: Mutex::new(None),
@@ -5399,11 +5304,11 @@ pub(crate) async fn rename_all_with_prepared_source(
#[cfg(target_os = "linux")]
pub(crate) fn rename_all_with_commit_guard_on_thread(source: &Path, destination: &Path, guard: &RenameCommitGuard) -> Result<()> {
guard.directories.prepare_destination().map_err(to_file_error)?;
#[cfg(test)]
prepared_publication_test_hooks::run_rename_destination(source, destination);
#[cfg(any(test, feature = "test-util"))]
if prepared_publication_test_hooks::has_rename_hooks(source, destination) {
guard.directories.prepare_destination().map_err(to_file_error)?;
#[cfg(test)]
prepared_publication_test_hooks::run_rename_destination(source, destination);
{
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, source);
prepared_publication_test_hooks::run(prepared_publication_test_hooks::Stage::Rename, destination);
}
@@ -5761,13 +5666,12 @@ pub(crate) async fn acquire_file_sync_admission(disk_permits: Arc<Semaphore>) ->
/// Keep the disk admission and namespace lease with the blocking syscall if
/// the async waiter is cancelled. The process-wide admission remains with the
/// waiter so cancellation cannot starve healthy disks.
#[cfg(any(unix, test))]
pub(crate) async fn run_blocking_namespace_file_sync_operation<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
operation: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
run_cancellable_blocking_namespace_file_sync_operation(lease, admission, move |_| operation()).await
run_blocking_namespace_file_sync_operation_with_global(lease, admission, &FILE_SYNC_PERMITS, operation).await
}
pub(crate) async fn run_cancellable_blocking_namespace_file_sync_operation<T: Send + 'static>(
@@ -5778,6 +5682,16 @@ pub(crate) async fn run_cancellable_blocking_namespace_file_sync_operation<T: Se
run_cancellable_blocking_namespace_file_sync_operation_with_global(lease, admission, &FILE_SYNC_PERMITS, operation).await
}
async fn run_blocking_namespace_file_sync_operation_with_global<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
global_permits: &Semaphore,
operation: impl FnOnce() -> io::Result<T> + Send + 'static,
) -> io::Result<T> {
run_cancellable_blocking_namespace_file_sync_operation_with_global(lease, admission, global_permits, move |_| operation())
.await
}
async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: Send + 'static>(
lease: Arc<NamespaceMutationLease>,
admission: &FileSyncAdmission,
@@ -12665,16 +12579,11 @@ mod tests {
let (release_tx, release_rx) = mpsc::channel();
let waiter_global_permits = global_permits.clone();
let waiter = tokio::spawn(async move {
run_cancellable_blocking_namespace_file_sync_operation_with_global(
lease,
&admission,
waiter_global_permits.as_ref(),
move |_| {
entered_tx.send(()).expect("signal blocking work");
release_rx.recv().expect("wait for blocking work release");
Ok(())
},
)
run_blocking_namespace_file_sync_operation_with_global(lease, &admission, waiter_global_permits.as_ref(), move || {
entered_tx.send(()).expect("signal blocking work");
release_rx.recv().expect("wait for blocking work release");
Ok(())
})
.await
});
@@ -49,7 +49,6 @@ pub(crate) fn test_single_inflight_construction_count() -> u64 {
}
type FillTask = oneshot::Receiver<FillResult>;
type FillBatch = (Vec<u8>, VecDeque<Vec<u8>>);
struct FillWorker {
tx: mpsc::Sender<FillRequest>,
@@ -294,7 +293,7 @@ where
Self::new_with_fill_policy_inner(source, engine, total_length, metrics_path, fill_policy)
}
fn poll_fill_result(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<Option<FillBatch>>> {
fn poll_fill_result(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<Option<Vec<u8>>>> {
if self.fill.is_none() {
let fill_worker_tx = match self.fill_worker_tx() {
Ok(tx) => tx,
@@ -346,6 +345,15 @@ where
if let Some(deferred_error) = deferred_error {
self.prefetch_error = Some(deferred_error);
}
// Queued stripes are delivered to the client via `prefetched_bufs.pop_front()`
// in `poll_read` without touching `self.remaining`, so their bytes must be
// accounted for here. Otherwise, under multi-in-flight fill policies (e.g. the
// default `DualInFlight`), `remaining` never reaches 0 and a fully delivered
// multi-block object still terminates the GET with `LessData`. Buffers in
// `queued_buffers` come only from `Ok(true)` decodes, so they are non-empty and
// their total is bounded by `remaining - main_buf.len()`, ruling out underflow.
self.remaining -= queued_buffers.iter().map(Vec::len).sum::<usize>();
self.prefetched_bufs.extend(queued_buffers);
match result {
Ok(Some(buf)) => {
@@ -354,14 +362,8 @@ where
}
rustfs_io_metrics::record_get_object_reader_stripe(self.metrics_path);
rustfs_io_metrics::record_get_object_reader_bytes(self.metrics_path, buf.len());
// Queued stripes are delivered to the client via `prefetched_bufs.pop_front()`
// in `poll_read` without touching `self.remaining`, so their bytes must be
// accounted for here alongside the primary stripe. Buffers in `queued_buffers`
// come only from `Ok(true)` decodes, so they are non-empty and their total is
// bounded by `remaining - buf.len()`, ruling out underflow.
self.remaining -= buf.len();
self.remaining -= queued_buffers.iter().map(Vec::len).sum::<usize>();
Poll::Ready(Ok(Some((buf, queued_buffers))))
Poll::Ready(Ok(Some(buf)))
}
Ok(None) => {
if self.remaining == 0 {
@@ -399,8 +401,8 @@ where
};
match fill {
Ok(Some((buf, queued_buffers))) => {
let output_has_remaining = self.output_pos < self.output_buf.len() || !self.prefetched_bufs.is_empty();
Ok(Some(buf)) => {
let output_has_remaining = self.output_pos < self.output_buf.len();
let mut queued_count = 0usize;
let mut queued_bytes = 0usize;
@@ -418,7 +420,6 @@ where
self.output_buf = buf;
self.output_pos = 0;
}
self.prefetched_bufs.extend(queued_buffers);
if !self.prefetched_bufs.is_empty() {
let total_prefetched_bytes = self.prefetched_bufs.iter().map(Vec::len).sum::<usize>();
@@ -450,7 +451,7 @@ where
Poll::Ready(Ok(()))
}
Err(err) => {
if self.output_pos < self.output_buf.len() || !self.prefetched_bufs.is_empty() {
if self.output_pos < self.output_buf.len() {
rustfs_io_metrics::record_get_object_reader_prefetch(self.metrics_path, GET_READER_PREFETCH_ERROR_DEFERRED);
self.prefetch_error = Some(err);
Poll::Ready(Ok(()))
@@ -1859,42 +1860,6 @@ mod tests {
.expect("dual inflight policy should prefetch two future stripes before current output drains");
}
#[tokio::test]
async fn erasure_decode_reader_dual_inflight_preserves_stripe_order_when_prefetch_completes_before_output_drains() {
let erasure = Erasure::new(4, 2, 16);
let data = (0..96u8).collect::<Vec<_>>();
let read_count = Arc::new(AtomicUsize::new(0));
let mut source = source_from_data(&erasure, &data, &[]);
source.read_count = Some(Arc::clone(&read_count));
let engine = LegacyEcDecodeEngine::new(erasure);
let mut reader = ErasureDecodeReader::new_with_fill_policy(
source,
engine,
data.len(),
GET_OBJECT_PATH_CODEC_STREAMING,
FillPolicy::DualInFlight,
)
.expect("reader should be constructed");
let mut decoded = Vec::with_capacity(data.len());
let mut chunk = [0u8; 5];
loop {
let n = reader.read(&mut chunk).await.expect("chunk read should succeed");
if n == 0 {
break;
}
decoded.extend_from_slice(&chunk[..n]);
// Yield between partial reads so the DualInFlight worker completes
// a 2-stripe fill (primary + queued_buffers) while output_buf still
// has unconsumed bytes.
for _ in 0..4 {
yield_now().await;
}
}
assert_eq!(decoded, data);
}
#[tokio::test]
async fn erasure_decode_reader_dual_inflight_reads_multi_block_object_to_end() {
// Regression for the byte-accounting bug: under DualInFlight each fill
+2 -17
View File
@@ -103,11 +103,8 @@ fn use_bytesmut_ingest() -> bool {
}
fn small_ingest_capacity(erasure: &Erasure, size_hint: usize) -> usize {
if size_hint <= erasure.block_size {
erasure.encoded_capacity_for_data_len(size_hint)
} else {
erasure.block_size
}
let data_len = size_hint.min(erasure.block_size);
erasure.encoded_capacity_for_data_len(data_len).min(erasure.block_size)
}
/// Keeps the encoder producer scoped to its parent future. Tokio detaches a
@@ -3525,24 +3522,12 @@ mod tests {
assert_eq!(small_ingest_capacity(&erasure, 0), 0);
assert_eq!(small_ingest_capacity(&erasure, 4 * 1024), 6 * 1024);
assert_eq!(small_ingest_capacity(&erasure, 16 * 1024), 24 * 1024);
assert_eq!(
small_ingest_capacity(&erasure, 1024 * 1024),
erasure.encoded_capacity_for_data_len(1024 * 1024)
);
assert_eq!(small_ingest_capacity(&erasure, usize::MAX), 1024 * 1024);
let legacy = Erasure::new_with_options(4, 2, 1024 * 1024, true);
assert_eq!(small_ingest_capacity(&legacy, 4 * 1024), 6 * 1024);
assert_eq!(
small_ingest_capacity(&legacy, 1024 * 1024),
legacy.encoded_capacity_for_data_len(1024 * 1024)
);
let high_parity = Erasure::new(4, 12, 1024 * 1024);
assert_eq!(
small_ingest_capacity(&high_parity, 1024 * 1024),
high_parity.encoded_capacity_for_data_len(1024 * 1024)
);
assert_eq!(small_ingest_capacity(&high_parity, usize::MAX), 1024 * 1024);
}
+6 -23
View File
@@ -974,18 +974,12 @@ impl ReadPlan {
let _ = sequence_number;
let decrypted_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if is_multipart {
match material.mode {
ReadEncryptionMode::Object => {
// The rio-v2 reader fails a stream that ends before a
// listed part, so it must not hear about empty ones.
#[cfg(feature = "rio-v2")]
let part_numbers = without_empty_parts(part_numbers, &oi.parts);
crate::io_support::rio::decrypt_multipart_reader_with_object_key(
reader,
material.key_bytes,
part_numbers,
sequence_number,
)
}
ReadEncryptionMode::Object => crate::io_support::rio::decrypt_multipart_reader_with_object_key(
reader,
material.key_bytes,
part_numbers,
sequence_number,
),
ReadEncryptionMode::Direct { base_nonce } => crate::io_support::rio::decrypt_multipart_reader(
reader,
material.key_bytes,
@@ -1440,17 +1434,6 @@ fn multipart_part_numbers(parts: &[ObjectPartInfo]) -> Vec<usize> {
parts.iter().map(|part| part.number).collect()
}
/// Drops from `part_numbers` the parts that stored no bytes: a DARE writer
/// emits no package for an empty part, so none follows on disk.
#[cfg(feature = "rio-v2")]
fn without_empty_parts(mut part_numbers: Vec<usize>, parts: &[ObjectPartInfo]) -> Vec<usize> {
let empty_parts: Vec<usize> = parts.iter().filter(|part| part.size == 0).map(|part| part.number).collect();
if !empty_parts.is_empty() {
part_numbers.retain(|number| !empty_parts.contains(number));
}
part_numbers
}
#[cfg(test)]
mod tests {
use super::*;
+20 -31
View File
@@ -1259,11 +1259,6 @@ pub struct ObjectOptions {
pub expected_current_version_id: Option<String>,
/// Persisted bucket incarnation observed before authorization.
pub expected_bucket_incarnation_id: Option<Uuid>,
/// Bucket incarnation that was admitted for an externally visible event.
/// This is kept separate from the storage fence because recovered work may
/// be allowed to commit while its notification provenance remains unknown.
#[doc(hidden)]
pub notification_bucket_incarnation_id: Option<Uuid>,
pub no_lock: bool,
/// Require complete participant observations for internal multipart size decisions.
/// This transient flag is never derived from client input or stored on disk.
@@ -1865,12 +1860,6 @@ pub struct ObjectInfo {
pub multipart_completion_replayed: bool,
/// Previous current version's size observed during `rename_data` commit.
pub backfilled_old_current_size: Option<crate::disk::OldCurrentSize>,
/// Persisted EC block size of a local version, projected from its erasure
/// layout for response headers. It is deliberately not part of
/// `user_defined`: every writer that turns `user_defined` back into stored
/// metadata would otherwise persist it. Read it through
/// [`ObjectInfo::effective_ec_block_size`].
pub ec_block_size: Option<usize>,
}
impl Default for ObjectInfo {
@@ -1914,7 +1903,6 @@ impl Default for ObjectInfo {
checksum: None,
multipart_completion_replayed: false,
backfilled_old_current_size: None,
ec_block_size: None,
}
}
}
@@ -1959,7 +1947,6 @@ impl Clone for ObjectInfo {
checksum: self.checksum.clone(),
multipart_completion_replayed: self.multipart_completion_replayed,
backfilled_old_current_size: self.backfilled_old_current_size,
ec_block_size: self.ec_block_size,
expires: self.expires,
}
}
@@ -1969,7 +1956,12 @@ impl ObjectInfo {
/// Return the persisted EC block size exposed by the response-side
/// projection. Callers must not infer this value from request metadata.
pub fn effective_ec_block_size(&self) -> Option<usize> {
self.ec_block_size
rustfs_utils::http::metadata_compat::get_consistent_str(
&self.user_defined,
crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
)
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0)
}
pub(crate) fn shard_integrity_write_mode(&self) -> ShardIntegrityWriteMode {
@@ -2395,9 +2387,13 @@ impl ObjectInfo {
// FileInfo for the reader, but never expose the internal marker as
// ordinary S3 metadata.
rustfs_utils::http::metadata_compat::remove_str(&mut metadata, crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX);
// Earlier metadata-only writes could persist the response projection.
rustfs_utils::http::metadata_compat::remove_str(&mut metadata, crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX);
let ec_block_size = (!fi.deleted && !is_remote && fi.erasure.block_size > 0).then_some(fi.erasure.block_size);
if !fi.deleted && !is_remote && fi.erasure.block_size > 0 {
rustfs_utils::http::metadata_compat::insert_str(
&mut metadata,
crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
fi.erasure.block_size.to_string(),
);
}
let storage_class = Some(
storageclass::effective_class(
@@ -2457,7 +2453,6 @@ impl ObjectInfo {
version_purge_status_internal,
version_purge_status,
replication_decision,
ec_block_size,
..Default::default()
}
}
@@ -3377,21 +3372,16 @@ mod tests {
let mut fi = FileInfo::new("bucket/object", 4, 2);
fi.size = 1;
fi.erasure.block_size = 64 * 1024;
rustfs_utils::http::metadata_compat::insert_str(
&mut fi.metadata,
crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
"1".into(),
);
let info = ObjectInfo::from_file_info(&fi, "bucket", "object", false);
assert_eq!(info.effective_ec_block_size(), Some(64 * 1024));
for key in ["x-rustfs-internal-ec-block-size", "x-minio-internal-ec-block-size"] {
assert!(
!info.user_defined.contains_key(key),
"the projection must not enter metadata that writers persist: {key}"
);
}
assert_eq!(
info.user_defined
.get(crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_KEY)
.map(String::as_str),
Some("65536")
);
fi.erasure.block_size = 131_072;
let info = ObjectInfo::from_file_info(&fi, "bucket", "object", false);
@@ -3419,10 +3409,9 @@ mod tests {
let owned = ObjectInfo::from_owned_file_info(fi, "bucket", "object", false);
assert_eq!(owned.effective_ec_block_size(), Some(64 * 1024));
assert_eq!(borrowed.effective_ec_block_size(), Some(64 * 1024));
assert_eq!(owned.user_defined, borrowed.user_defined);
for key in ["x-rustfs-internal-ec-block-size", "x-minio-internal-ec-block-size"] {
assert!(!owned.user_defined.contains_key(key), "{key}");
assert_eq!(owned.user_defined.get(key).map(String::as_str), Some("65536"));
}
}
-7
View File
@@ -1045,13 +1045,6 @@ impl InstanceContext {
self.local_disk_map.clone()
}
/// Snapshot the boot-time disk registry before a store is published.
/// Missing local drives remain explicit so startup receipts cannot treat
/// an available subset as the complete instance inventory.
pub async fn local_disk_inventory(&self) -> Vec<Option<DiskStore>> {
self.local_disk_map.read().await.values().cloned().collect()
}
/// Handle to this instance's local disk-id→endpoint map.
pub(crate) fn local_disk_id_map(&self) -> Arc<RwLock<HashMap<Uuid, String>>> {
self.local_disk_id_map.clone()
@@ -82,8 +82,6 @@ impl EventNotifier {
#[derive(Debug, Default)]
pub struct EventArgs {
/// Bucket instance verified by storage when producing this event.
pub bucket_incarnation_id: Option<uuid::Uuid>,
pub event_name: String,
pub bucket_name: String,
pub object: ObjectInfo,
@@ -137,7 +135,6 @@ pub(crate) mod test_recorder {
#[derive(Clone, Debug)]
pub(crate) struct RecordedEvent {
pub(crate) event_name: String,
pub(crate) bucket_incarnation_id: Option<Uuid>,
pub(crate) bucket: String,
pub(crate) object: String,
pub(crate) version_id: Option<Uuid>,
@@ -157,7 +154,6 @@ pub(crate) mod test_recorder {
register_event_dispatch_hook(|args| {
recorded().lock().unwrap_or_else(|err| err.into_inner()).push(RecordedEvent {
event_name: args.event_name,
bucket_incarnation_id: args.bucket_incarnation_id,
bucket: args.bucket_name,
object: args.object.name,
version_id: args.object.version_id,
@@ -62,10 +62,6 @@ impl MetricType {
pub const RPC: MetricType = MetricType(1 << 8);
pub const HTTP: MetricType = MetricType(1 << 9);
/// Internal GetMetrics selector for a compact, generation-bound node sample.
/// Excluded from ALL so existing HTTP and rolling-upgrade peers keep their wire shape.
pub const SCANNER_SUMMARY: MetricType = MetricType(1 << 10);
// MetricsAll must be last.
pub const ALL: MetricType = MetricType((1 << 10) - 1);
@@ -162,7 +158,6 @@ fn to_madmin_scanner_metrics(metrics: rustfs_scanner_metrics::metrics::ScannerMe
last_cycle_lifecycle_transition_actions: metrics.last_cycle_lifecycle_transition_actions,
last_cycle_partial_source: metrics.last_cycle_partial_source,
last_cycle_partial_source_code: metrics.last_cycle_partial_source_code,
last_cycle_partial_stage: metrics.last_cycle_partial_stage,
last_cycle_duration_seconds: metrics.last_cycle_duration_seconds,
last_cycle_objects_scanned: metrics.last_cycle_objects_scanned,
last_cycle_directories_scanned: metrics.last_cycle_directories_scanned,
@@ -410,27 +405,6 @@ impl MetricType {
pub async fn collect_local_metrics(types: MetricType, opts: &CollectMetricsOpts) -> RealtimeMetrics {
debug!("collect_local_metrics");
let mut real_time_metrics = RealtimeMetrics::default();
if types.0 == MetricType::SCANNER_SUMMARY.0 {
let sample = global_metrics().scanner_node_observation().await;
real_time_metrics.scanner_node = Some(rustfs_madmin::metrics::ScannerNodeSample {
active: sample.active,
leader: sample.leader,
cycle: sample.cycle,
epoch: sample.epoch,
started_at: sample.started_at,
objects_scanned: sample.objects_scanned,
last_attempt: sample
.last_attempt
.map(|attempt| rustfs_madmin::metrics::ScannerAttemptSample {
epoch: attempt.epoch,
cycle: attempt.cycle,
result: attempt.result.to_string(),
partial_reason: attempt.partial_reason.map(str::to_string),
duration_seconds: attempt.duration.as_secs_f64(),
}),
});
return real_time_metrics;
}
if types.0 == MetricType::NONE.0 {
info!("types is None, return");
return real_time_metrics;
@@ -711,7 +685,6 @@ mod test {
current_started,
last_cycle_partial_source: "usage".to_string(),
last_cycle_partial_source_code: 1,
last_cycle_partial_stage: Some("object_budget".into()),
cycle_timeout_total: 3,
cycle_recovery_required_total: 2,
cycle_last_progress_age: 17,
@@ -727,7 +700,6 @@ mod test {
assert_eq!(scanner.current_started, current_started);
assert_eq!(scanner.last_cycle_partial_source, "usage");
assert_eq!(scanner.last_cycle_partial_source_code, 1);
assert_eq!(scanner.last_cycle_partial_stage.as_deref(), Some("object_budget"));
assert_eq!(scanner.cycle_timeout_total, 3);
assert_eq!(scanner.cycle_recovery_required_total, 2);
assert_eq!(scanner.cycle_last_progress_age, 17);
@@ -5958,7 +5958,6 @@ mod tests {
#[test]
fn scanner_dirty_usage_acknowledgement_preserves_newer_pending_work() {
let activity = |dirty_usage_pending| ScannerPeerActivity {
checkpoint_instance_id: None,
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
namespace_generation: 1,
maintenance_generation: 1,
@@ -4638,11 +4638,10 @@ impl SetDisks {
write_quorum,
};
let resource_unit = resource_unit.clone();
let producer = crate::disk::with_optional_resource_unit(resource_unit, async move {
tasks.spawn(crate::disk::with_optional_resource_unit(resource_unit, async move {
let outcome = Self::run_unary_rename_slot(context).await;
let _ = outcome_tx.send(outcome).await;
});
tasks.spawn(crate::disk::with_detached_disk_io_context(producer));
}));
}
for group in fanout_plan.batch_groups {
let outcome_tx = outcome_tx.clone();
@@ -4653,7 +4652,7 @@ impl SetDisks {
let group_disks = disks.clone();
let group_tokens = fence_tokens.clone();
let resource_unit = resource_unit.clone();
let producer = crate::disk::with_optional_resource_unit(resource_unit, async move {
tasks.spawn(crate::disk::with_optional_resource_unit(resource_unit, async move {
let prepared = join_all(group.slots.into_iter().map(|slot| {
let context = RenameSlotContext {
slot,
@@ -4816,8 +4815,7 @@ impl SetDisks {
}
}
}
});
tasks.spawn(crate::disk::with_detached_disk_io_context(producer));
}));
}
drop(outcome_tx);
RenameOutcomeProducers {
@@ -4872,7 +4870,7 @@ impl SetDisks {
let coordinator_failure_receipt = rollback_receipt.clone();
let early_ack_spawn_to_quorum_wait_started = rustfs_io_metrics::put_stage_timer();
let tail_drain = tokio::spawn(crate::disk::with_detached_disk_io_context({
let tail_drain = tokio::spawn({
let fanout_src_bucket = src_bucket.clone();
let fanout_src_object = src_object.clone();
let fanout_dst_bucket = dst_bucket.clone();
@@ -5126,7 +5124,7 @@ impl SetDisks {
all_online_local_succeeded,
})
}
}));
});
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_EARLY_ACK_SPAWN_TO_QUORUM_WAIT,
@@ -5307,7 +5305,6 @@ impl SetDisks {
rollback_fault_injection::after_fanout(&fanout_dst_object);
(results, fanout_file_infos)
};
let fanout_future = crate::disk::with_detached_disk_io_context(fanout_future);
let fanout = if protected_multipart {
tokio::spawn(crate::disk::with_optional_resource_unit(
crate::disk::current_resource_unit(),
@@ -16,11 +16,12 @@ use super::super::{
Cursor, DiskStore, EVENT_SET_DISK_WRITE, Error, FileInfo, HashAlgorithm, LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_SET_DISK,
Result, join_all, warn,
};
use crate::disk::{CHECK_PART_SUCCESS, Disk, DiskAPI, RUSTFS_META_TMP_BUCKET};
use crate::disk::DiskAPI;
#[cfg(test)]
use crate::disk::RUSTFS_META_TMP_BUCKET;
use crate::set_disk::coding;
#[cfg(test)]
use bytes::Bytes;
use rustfs_filemeta::{ErasureInfo, ObjectPartInfo};
/// Null out any disk whose shard writer failed (or was never created) so its
/// truncated/absent shard is not committed by the final rename, and return the
@@ -37,21 +38,14 @@ pub(in crate::set_disk::ops) fn drop_failed_writer_disks<D, W>(disks: &mut [Opti
committed
}
pub(super) enum WrittenBitrotShards<'a> {
Inline(&'a [FileInfo]),
Staged {
directory: &'a str,
layout: &'a ErasureInfo,
part_size: usize,
},
}
#[derive(Clone, Copy)]
pub(in crate::set_disk::ops) struct BitrotSelfVerifyTarget<'a> {
pub(in crate::set_disk::ops) operation: &'static str,
pub(in crate::set_disk::ops) bucket: &'a str,
pub(in crate::set_disk::ops) object: &'a str,
pub(in crate::set_disk::ops) part_number: Option<usize>,
pub(in crate::set_disk::ops) volume: &'a str,
pub(in crate::set_disk::ops) path: &'a str,
pub(in crate::set_disk::ops) logical_shard_size: usize,
pub(in crate::set_disk::ops) shard_size: usize,
pub(in crate::set_disk::ops) write_quorum: usize,
@@ -59,18 +53,52 @@ pub(in crate::set_disk::ops) struct BitrotSelfVerifyTarget<'a> {
pub(in crate::set_disk::ops) async fn verify_written_bitrot_shards(
disks: &[Option<DiskStore>],
source: WrittenBitrotShards<'_>,
inline_parts: Option<&[FileInfo]>,
target: BitrotSelfVerifyTarget<'_>,
) -> Result<usize> {
let encoded_shard_size =
coding::bitrot_shard_file_size(target.logical_shard_size, target.shard_size, HashAlgorithm::HighwayHash256S);
let algo = HashAlgorithm::HighwayHash256S;
let encoded_shard_size = coding::bitrot_shard_file_size(target.logical_shard_size, target.shard_size, algo.clone());
let tasks = disks.iter().enumerate().filter_map(|(index, disk)| {
let disk = disk.as_ref()?;
let verify = source.verify(index, disk, &target, encoded_shard_size);
Some(async move { (index, disk, verify.await) })
});
let results = join_all(tasks).await;
let results = if let Some(parts) = inline_parts {
let tasks = disks.iter().enumerate().filter_map(|(index, disk)| {
let disk = disk.as_ref()?.clone();
let data = parts.get(index).and_then(|part| part.data.as_ref()).cloned();
let algo = algo.clone();
Some(async move {
let result = match data {
Some(data) => coding::bitrot_verify(
Cursor::new(data),
encoded_shard_size,
target.logical_shard_size,
algo,
target.shard_size,
)
.await
.map_err(Error::from),
None => Err(Error::other(format!("{} inline shard {index} is missing bitrot data", target.operation))),
};
(index, disk, result)
})
});
join_all(tasks).await
} else {
let tasks = disks.iter().enumerate().filter_map(|(index, disk)| {
let disk = disk.as_ref()?.clone();
let algo = algo.clone();
Some(async move {
let result = match disk.read_file(target.volume, target.path).await {
Ok(reader) => {
coding::bitrot_verify(reader, encoded_shard_size, target.logical_shard_size, algo, target.shard_size)
.await
.map_err(Error::from)
}
Err(err) => Err(Error::from(err)),
};
(index, disk, result)
})
});
join_all(tasks).await
};
let mut verified_shards = 0usize;
for (index, disk, result) in results {
@@ -109,97 +137,9 @@ pub(in crate::set_disk::ops) async fn verify_written_bitrot_shards(
Ok(verified_shards)
}
impl WrittenBitrotShards<'_> {
async fn verify(&self, index: usize, disk: &Disk, target: &BitrotSelfVerifyTarget<'_>, encoded_size: usize) -> Result<()> {
let algo = HashAlgorithm::HighwayHash256S;
match self {
Self::Inline(parts) => {
let data = parts
.get(index)
.and_then(|part| part.data.as_ref())
.ok_or_else(|| Error::other(format!("{} inline shard {index} is missing bitrot data", target.operation)))?;
coding::bitrot_verify(
Cursor::new(data.as_ref()),
encoded_size,
target.logical_shard_size,
algo,
target.shard_size,
)
.await?;
}
Self::Staged {
directory,
layout,
part_size,
} => {
let number = target.part_number.unwrap_or(1);
match disk {
Disk::Local(local) => {
let path = format!("{directory}/part.{number}");
let reader = local.read_file(RUSTFS_META_TMP_BUCKET, &path).await?;
coding::bitrot_verify(reader, encoded_size, target.logical_shard_size, algo, target.shard_size).await?;
}
Disk::Remote(peer) => {
let fi = staged_part_file_info(layout, index + 1, number, *part_size, target.shard_size)?;
let response = peer.verify_staged_part(directory, &fi, encoded_size).await?;
require_verified_part(&response.results)?;
}
}
}
}
Ok(())
}
}
/// VerifyFile resolves `directory/part.N` using this part's write layout. Only
/// the geometry and part size are needed to verify a staged, non-inline shard.
fn staged_part_file_info(
layout: &ErasureInfo,
index: usize,
number: usize,
part_size: usize,
frame_size: usize,
) -> Result<FileInfo> {
let mut fi = FileInfo {
size: i64::try_from(part_size).map_err(Error::other)?,
erasure: ErasureInfo {
algorithm: layout.algorithm.clone(),
data_blocks: layout.data_blocks,
parity_blocks: layout.parity_blocks,
block_size: layout.block_size,
index,
distribution: layout.distribution.clone(),
..Default::default()
},
parts: vec![ObjectPartInfo {
number,
size: part_size,
..Default::default()
}],
..Default::default()
};
if frame_size != coding::calc_shard_size(layout.block_size, layout.data_blocks) {
crate::object_api::insert_ec_read_quantum(&mut fi.metadata, frame_size);
}
Ok(fi)
}
fn require_verified_part(results: &[usize]) -> Result<()> {
match results {
[CHECK_PART_SUCCESS] => Ok(()),
[crate::disk::CHECK_PART_DISK_NOT_FOUND] => Err(Error::DiskNotFound),
[crate::disk::CHECK_PART_VOLUME_NOT_FOUND] => Err(Error::VolumeNotFound),
[crate::disk::CHECK_PART_FILE_NOT_FOUND] => Err(Error::FileNotFound),
[crate::disk::CHECK_PART_FILE_CORRUPT] => Err(Error::FileCorrupt),
_ => Err(Error::Unexpected),
}
}
#[cfg(test)]
mod tests {
use super::super::object::hermetic_set_disks_support::{
hermetic_set_disks_for_pool_with_default_parity, hermetic_set_disks_for_pool_with_default_parity_isolated,
};
use super::super::object::hermetic_set_disks_support::hermetic_set_disks_for_pool_with_default_parity;
use super::*;
use crate::storage_api_contracts::object::ObjectIO as _;
@@ -243,12 +183,6 @@ mod tests {
let logical_shard_size = 8_250_370usize;
let payload = vec![0x5a; logical_shard_size];
let encoded = encode_streaming_shard(&payload, shard_size).await;
let layout = &FileInfo::new("object", 1, 0).erasure;
let staged = || WrittenBitrotShards::Staged {
directory: "issue-5173",
layout,
part_size: payload.len(),
};
let path = "issue-5173/part.1";
assert_eq!(encoded.len(), 8_250_626);
@@ -257,12 +191,14 @@ mod tests {
.expect("healthy temp shard should be written");
let verified = verify_written_bitrot_shards(
&[Some(disk.clone())],
staged(),
None,
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "object",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path,
logical_shard_size,
shard_size,
write_quorum: 1,
@@ -280,12 +216,14 @@ mod tests {
.expect("oversized temp shard should be staged");
let err = verify_written_bitrot_shards(
&[Some(disk.clone())],
staged(),
None,
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "object",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path,
logical_shard_size,
shard_size,
write_quorum: 1,
@@ -305,12 +243,14 @@ mod tests {
let err = verify_written_bitrot_shards(
&[Some(disk)],
staged(),
None,
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "object",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path,
logical_shard_size,
shard_size,
write_quorum: 1,
@@ -321,179 +261,6 @@ mod tests {
assert!(err.to_string().contains("bitrot self-verify failed"));
}
#[test]
fn staged_part_requires_exactly_one_success() {
require_verified_part(&[CHECK_PART_SUCCESS]).expect("one verified shard");
for results in [
vec![],
vec![CHECK_PART_SUCCESS; 2],
vec![crate::disk::CHECK_PART_UNKNOWN],
vec![usize::MAX],
] {
assert!(
matches!(require_verified_part(&results), Err(Error::Unexpected)),
"unexpected peer result {results:?}"
);
}
assert!(matches!(
require_verified_part(&[crate::disk::CHECK_PART_DISK_NOT_FOUND]),
Err(Error::DiskNotFound)
));
assert!(matches!(
require_verified_part(&[crate::disk::CHECK_PART_VOLUME_NOT_FOUND]),
Err(Error::VolumeNotFound)
));
assert!(matches!(
require_verified_part(&[crate::disk::CHECK_PART_FILE_NOT_FOUND]),
Err(Error::FileNotFound)
));
assert!(matches!(
require_verified_part(&[crate::disk::CHECK_PART_FILE_CORRUPT]),
Err(Error::FileCorrupt)
));
}
#[tokio::test]
async fn tcp_and_nixl_verify_staged_shards_at_the_owner() {
let (_dirs, disks, _) = hermetic_set_disks_for_pool_with_default_parity(2, 0, 0).await;
let owner = disks[1].clone();
let frame_size = 64 * 1024;
let mut layout = FileInfo::new("bucket/key", 2, 0).erasure;
layout.block_size = 256 * 1024;
let part_size = layout.block_size + 5;
let logical_shard_size = layout.block_size / 2 + 3;
let bytes = encode_streaming_shard(&vec![0x43; logical_shard_size], frame_size).await;
crate::cluster::rpc::remote_disk::with_staged_part_peer(owner.clone(), |tcp, nixl| async move {
for peer in [tcp, nixl] {
let set = [
Some(disks[0].clone()),
Some(std::sync::Arc::new(Disk::Remote(Box::new(peer)))),
];
for (directory, part_number) in [("staging/data", None), ("upload-stage", Some(7))] {
let path = format!("{directory}/part.{}", part_number.unwrap_or(1));
let verify = || {
verify_written_bitrot_shards(
&set,
WrittenBitrotShards::Staged {
directory,
layout: &layout,
part_size,
},
BitrotSelfVerifyTarget {
operation: "test",
bucket: "bucket",
object: "key",
part_number,
logical_shard_size,
shard_size: frame_size,
write_quorum: 2,
},
)
};
for disk in &disks {
disk.write_all(RUSTFS_META_TMP_BUCKET, &path, bytes.clone())
.await
.expect("stage shard");
}
assert_eq!(verify().await.expect("peer verified its local bytes over gRPC"), 2);
let mut corrupt = bytes.to_vec();
*corrupt.last_mut().expect("non-empty shard") ^= 1;
let mut oversized = bytes.to_vec();
oversized.push(0);
for damaged in [Bytes::from(corrupt), bytes.slice(..bytes.len() - 1), Bytes::from(oversized)] {
owner
.write_all(RUSTFS_META_TMP_BUCKET, &path, damaged)
.await
.expect("damage peer shard");
assert!(
verify()
.await
.expect_err("invalid peer shard")
.to_string()
.contains("failed for shard 1")
);
}
}
}
})
.await;
}
#[tokio::test]
async fn put_object_remote_verification_failure_does_not_publish_object() {
use crate::cluster::rpc::remote_disk::with_lost_staged_shard_peer;
use crate::set_disk::{ObjectOptions, PutObjReader};
use crate::storage_api_contracts::object::ObjectOperations as _;
let (_dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(2, 0, 0).await;
let bucket = "peer-verify-put";
let key = "object";
let opts = ObjectOptions::default();
for disk in &disks {
disk.make_volume(bucket).await.expect("create bucket");
}
with_lost_staged_shard_peer(disks[1].clone(), |peer| async {
set.disks.write().await[1] = Some(std::sync::Arc::new(Disk::Remote(Box::new(peer))));
let mut reader = PutObjReader::from_vec(vec![0x42; 2 * 1024 * 1024]);
let error = set
.put_object(bucket, key, &mut reader, &opts)
.await
.expect_err("remote verification must fail the PUT");
assert!(error.to_string().contains("bitrot self-verify failed for shard"), "{error}");
assert!(error.to_string().ends_with(&Error::FileNotFound.to_string()), "{error}");
set.disks.write().await[1] = Some(disks[1].clone());
})
.await;
let error = set
.get_object_info(bucket, key, &opts)
.await
.expect_err("failed PUT must leave the object absent");
assert!(crate::error::is_err_object_not_found(&error), "{error}");
for disk in disks {
assert!(matches!(
disk.read_version("", bucket, key, "", &Default::default()).await,
Err(crate::disk::error::DiskError::FileNotFound)
));
}
}
#[tokio::test]
async fn upload_part_remote_verification_failure_does_not_publish_part() {
use crate::cluster::rpc::remote_disk::with_lost_staged_shard_peer;
use crate::set_disk::{ObjectOptions, PutObjReader};
use crate::storage_api_contracts::multipart::MultipartOperations as _;
let (_dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(2, 0, 0).await;
let bucket = "peer-verify-multipart";
let key = "object";
let opts = ObjectOptions::default();
for disk in &disks {
disk.make_volume(bucket).await.expect("create bucket");
}
let upload_id = set
.new_multipart_upload(bucket, key, &opts)
.await
.expect("create multipart upload")
.upload_id;
with_lost_staged_shard_peer(disks[1].clone(), |peer| async {
set.disks.write().await[1] = Some(std::sync::Arc::new(Disk::Remote(Box::new(peer))));
let mut reader = PutObjReader::from_vec(vec![0x53; 1024 * 1024]);
let error = set
.put_object_part(bucket, key, &upload_id, 7, &mut reader, &opts)
.await
.expect_err("remote verification must fail UploadPart");
assert!(error.to_string().contains("bitrot self-verify failed for shard"), "{error}");
assert!(error.to_string().ends_with(&Error::FileNotFound.to_string()), "{error}");
set.disks.write().await[1] = Some(disks[1].clone());
})
.await;
let listed = set
.list_object_parts(bucket, key, &upload_id, None, 10, &opts)
.await
.expect("upload must remain listable");
assert!(listed.parts.is_empty(), "failed UploadPart published a part");
}
#[tokio::test]
async fn no_parity_inline_self_verify_rejects_trailing_bytes() {
let (_temp_dirs, disks, _set_disks) = hermetic_set_disks_for_pool_with_default_parity(1, 0, 0).await;
@@ -511,12 +278,14 @@ mod tests {
}];
let err = verify_written_bitrot_shards(
&disks,
WrittenBitrotShards::Inline(&parts),
Some(&parts),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "inline-object",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path: "unused-for-inline",
logical_shard_size: payload.len(),
shard_size,
write_quorum: 1,
@@ -558,12 +327,14 @@ mod tests {
}];
let err = verify_written_bitrot_shards(
&disks_opt,
WrittenBitrotShards::Inline(&empty_parts),
Some(&empty_parts),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "missing-inline-data",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path: "unused",
logical_shard_size: payload.len(),
shard_size,
write_quorum: 1,
@@ -576,16 +347,14 @@ mod tests {
// 2. Disk shard missing on disk (FileNotFound) fails closed with shard error context.
let err = verify_written_bitrot_shards(
&disks_opt,
WrittenBitrotShards::Staged {
directory: "missing",
layout: &FileInfo::new("object", 1, 0).erasure,
part_size: payload.len(),
},
None,
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "missing-disk-file",
part_number: Some(3),
volume: RUSTFS_META_TMP_BUCKET,
path: "nonexistent-temp-shard",
logical_shard_size: payload.len(),
shard_size,
write_quorum: 1,
@@ -606,12 +375,14 @@ mod tests {
let two_slots = vec![disks_opt[0].clone(), None];
let err = verify_written_bitrot_shards(
&two_slots,
WrittenBitrotShards::Inline(&valid_parts),
Some(&valid_parts),
BitrotSelfVerifyTarget {
operation: "put_object",
bucket: "bucket",
object: "under-quorum",
part_number: None,
volume: RUSTFS_META_TMP_BUCKET,
path: "unused",
logical_shard_size: payload.len(),
shard_size,
write_quorum: 2,
@@ -17,8 +17,8 @@
use crate::disk::error::{DiskError, Result, RpcStatusError};
use crate::disk::{
DELETE_RECOVERY_PROTOCOL_VERSION, DeleteRecoveryAction, DeleteRecoveryInspection, DeleteRecoveryJournal, DeleteRecoveryState,
DeleteRecoveryVersionIdentity, DeleteTransactionId, DiskAPI, DiskStore,
DELETE_RECOVERY_PROTOCOL_VERSION, DeleteRecoveryAction, DeleteRecoveryInspection, DeleteRecoveryState, DeleteTransactionId,
DiskAPI, DiskStore,
};
use crate::error::StorageError;
use crate::set_disk::SetDisks;
@@ -204,39 +204,16 @@ pub(in crate::set_disk) fn unsupported_recovery(error: &DiskError) -> bool {
.is_some_and(|status| status.status().code() == tonic::Code::Unimplemented))
}
/// Set authority needs generation identities, not the potentially large
/// per-version apply requests carried by returning-drive adoption.
struct DecisionEvidence {
transaction: Uuid,
deleted_versions: HashSet<Uuid>,
original_null_versions: HashSet<DeleteRecoveryVersionIdentity>,
original_versions: HashSet<crate::disk::DeleteRecoveryVersionIdentity>,
predecessors: HashSet<Uuid>,
target_absent: bool,
}
impl From<&DeleteRecoveryJournal> for DecisionEvidence {
fn from(journal: &DeleteRecoveryJournal) -> Self {
let deleted_versions: HashSet<_> = journal.deleted_versions.iter().copied().collect();
// Only the null version can be reused for a different generation.
// Adjacent transactions deleting unique version IDs need no identity index.
let original_null_versions = if deleted_versions.contains(&Uuid::nil()) {
journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.cloned()
.collect()
} else {
HashSet::new()
};
Self {
transaction: journal.transaction,
deleted_versions,
original_null_versions,
predecessors: journal.predecessors.iter().copied().collect(),
target_absent: journal.target_digest.is_none(),
}
}
}
fn receipt(state: DeleteRecoveryState) -> bool {
matches!(state, DeleteRecoveryState::QuorumCommitted | DeleteRecoveryState::CommitFinished)
}
@@ -557,7 +534,7 @@ impl SetDisks {
};
let mut fast_receipt_quorum = false;
if can_try_local_fast_path && can_commit() {
let mut fast_published = join_all(disks.iter().map(|disk| async {
let fast_published = join_all(disks.iter().map(|disk| async {
if !can_commit() {
return Err(DiskError::other("delete recovery namespace fence was lost"));
}
@@ -581,17 +558,13 @@ impl SetDisks {
return Ok(());
}
let all_fast_published = fast_published.len() == self.set_drive_count
&& fast_published.iter().all(|res| matches!(res, Ok(Some((_, true, true, _)))));
&& fast_published.iter().all(|res| matches!(res, Ok(Some((_, true, true)))));
if all_fast_published && can_commit() {
#[cfg(test)]
test_hooks::record_cleanup_attempt(bucket, object);
let finalized = join_all(disks.iter().zip(fast_published.iter_mut()).map(|(disk, pub_res)| {
let finalized = join_all(disks.iter().zip(fast_published.iter()).map(|(disk, pub_res)| {
let ns_owner = context.namespace_owner.clone();
let work_budget = context.work_budget.clone();
let published_input = match pub_res {
Ok(Some((journal, _, _, state))) => Some((&*journal, state.take())),
_ => None,
};
async move {
if !can_commit() {
return Ok(false);
@@ -599,7 +572,7 @@ impl SetDisks {
let Some(disk) = disk.as_ref() else {
return Ok(false);
};
let Some((journal, state)) = published_input else {
let Ok(Some((journal, _, _))) = pub_res else {
return Ok(false);
};
disk.try_finish_and_finalize_prepared_delete_local(
@@ -609,7 +582,6 @@ impl SetDisks {
journal,
ns_owner,
work_budget,
state,
)
.await
}
@@ -628,9 +600,6 @@ impl SetDisks {
return Ok(());
}
}
// Flush any unconsumed Stage 2 receipt entries into `PUBLISHED_DELETE_RECEIPTS`
// (via `LocalPublishedDeleteState::drop`) before falling back to `inspect`.
drop(fast_published);
}
let states = inspect(disks, bucket, object, transaction, context.work_budget.as_deref()).await;
if states
@@ -1069,7 +1038,13 @@ impl SetDisks {
.flatten()
.filter(|state| receipt(state.state))
.filter_map(|state| state.journal.as_ref())
.map(DecisionEvidence::from)
.map(|journal| DecisionEvidence {
transaction: journal.transaction,
deleted_versions: journal.deleted_versions.iter().copied().collect(),
original_versions: journal.original_versions.iter().cloned().collect(),
predecessors: journal.predecessors.iter().copied().collect(),
target_absent: journal.target_digest.is_none(),
})
.collect::<Vec<_>>();
let mut unresolved = false;
let mut mutated = false;
@@ -1125,43 +1100,49 @@ impl SetDisks {
.iter()
.filter(|state| receipt(state.state))
.filter_map(|state| state.journal.as_ref())
.max_by_key(|journal| !journal.requests.is_empty());
let finished =
|copy: &DeleteRecoveryInspection| copy.state == DeleteRecoveryState::CommitFinished && copy.commit_data_safe;
if authority.is_some() && copies.iter().all(finished) {
// Neither settlement phase writes. The sibling inspections
// remain valid under the same key fence.
summary.committed += 1;
continue;
}
.max_by_key(|journal| !journal.requests.is_empty())
.cloned();
let prepared = copies.iter().find_map(|state| state.journal.as_ref());
let can_finish = authority.is_some()
|| fresh_absence_decision
|| prepared
.filter(|journal| !journal.deleted_versions.is_empty())
.is_some_and(|journal| {
authorities.iter().any(|authority| {
journal.deleted_versions.iter().all(|version| {
authority.deleted_versions.contains(version)
&& (!version.is_nil()
|| journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.all(|source| authority.original_null_versions.contains(source))
|| (authority.predecessors.contains(&journal.transaction)
&& journal.target_digest.is_none()
&& authority.target_absent
&& copies.iter().all(|copy| {
copy.current_digest.is_none()
|| copy.current_versions == journal.original_versions
})))
})
let covered = prepared
.filter(|journal| !journal.deleted_versions.is_empty())
.is_some_and(|journal| {
authorities.iter().any(|authority| {
journal.deleted_versions.iter().all(|version| {
authority.deleted_versions.contains(version)
&& (!version.is_nil()
|| journal
.original_versions
.iter()
.filter(|source| source.version_id.is_none_or(|id| id.is_nil()))
.all(|source| authority.original_versions.contains(source))
|| (authority.predecessors.contains(&journal.transaction)
&& journal.target_digest.is_none()
&& authority.target_absent
&& copies.iter().all(|copy| {
copy.current_digest.is_none() || copy.current_versions == journal.original_versions
})))
})
});
if can_finish {
})
});
let original_quorum = prepared.is_some_and(|journal| {
copies
.iter()
.filter(|copy| copy.current_versions == journal.original_versions)
.count()
> self.set_drive_count / 2
});
let all_decisions_precede = !authorities.is_empty()
&& authorities.iter().all(|authority| {
copies
.iter()
.filter_map(|copy| copy.journal.as_ref())
.any(|journal| journal.predecessors.contains(&authority.transaction))
});
if authority.is_some() || covered || fresh_absence_decision {
let certified_same_transaction = authority.is_some();
let reference = authority.or(prepared).ok_or(DiskError::FileCorrupt)?;
let reference = authority
.or_else(|| copies.iter().find_map(|state| state.journal.clone()))
.ok_or(DiskError::FileCorrupt)?;
if dry_run {
if copies.iter().any(|copy| {
if certified_same_transaction
@@ -1171,7 +1152,7 @@ impl SetDisks {
{
copy.journal
.as_ref()
.is_none_or(|local| !local.matches_prepared_authority(reference))
.is_none_or(|local| !local.matches_prepared_authority(&reference))
} else if copy.state == DeleteRecoveryState::Absent {
copy.current_digest.is_some() && !reference.matches_adoption_source(&copy.current_versions)
} else {
@@ -1184,14 +1165,6 @@ impl SetDisks {
}
continue;
}
let needs_adoption = |copy: &DeleteRecoveryInspection| {
copy.state == DeleteRecoveryState::Absent
|| (certified_same_transaction
&& copy.state == DeleteRecoveryState::NewPrepared
&& copy.current_digest.is_none()
&& !copy.commit_data_safe)
};
let adoption_source = copies.iter().any(needs_adoption).then(|| reference.clone());
mutated = true;
let mut pending = settle_group(
&disks,
@@ -1201,12 +1174,20 @@ impl SetDisks {
if receipt(copy.state) && copy.commit_data_safe {
return None;
}
Some(match adoption_source.as_ref().filter(|_| needs_adoption(copy)) {
Some(authority) => DeleteRecoveryAction::AdoptCommit {
authority: Box::new(authority.clone()),
Some(
if copy.state == DeleteRecoveryState::Absent
|| (certified_same_transaction
&& copy.state == DeleteRecoveryState::NewPrepared
&& copy.current_digest.is_none()
&& !copy.commit_data_safe)
{
DeleteRecoveryAction::AdoptCommit {
authority: Box::new(reference.clone()),
}
} else {
DeleteRecoveryAction::PublishCommit
},
None => DeleteRecoveryAction::PublishCommit,
})
)
},
can_commit,
RecoveryWorkScope {
@@ -1221,7 +1202,10 @@ impl SetDisks {
&disks,
bucket,
copies,
|copy| (!finished(copy)).then_some(DeleteRecoveryAction::FinishCommit),
|copy| {
(copy.state != DeleteRecoveryState::CommitFinished || !copy.commit_data_safe)
.then_some(DeleteRecoveryAction::FinishCommit)
},
can_commit,
RecoveryWorkScope {
namespace_owner: namespace_owner.as_ref(),
@@ -1240,21 +1224,7 @@ impl SetDisks {
} else {
// A sibling decision or foreign generation can supersede this
// snapshot. Never guess by restoring the whole old backup.
let conflicts_with_decision = !authorities.is_empty()
&& !prepared.is_some_and(|journal| {
copies
.iter()
.filter(|copy| copy.current_versions == journal.original_versions)
.count()
> self.set_drive_count / 2
})
&& !authorities.iter().all(|authority| {
copies
.iter()
.filter_map(|copy| copy.journal.as_ref())
.any(|journal| journal.predecessors.contains(&authority.transaction))
});
if conflicts_with_decision
if (!authorities.is_empty() && !original_quorum && !all_decisions_precede)
|| copies
.iter()
.any(|state| state.state != DeleteRecoveryState::Absent && !state.rollback_data_complete)
@@ -3768,128 +3738,6 @@ mod tests {
}
}
#[test]
fn delete_recovery_decision_indexes_only_null_generation_evidence() {
let mut current = DeleteRecoveryVersionIdentity {
version_id: None,
mod_time: None,
data_dir: Some(Uuid::from_u128(1)),
deleted: false,
metadata_digest: [0; 32],
};
let null_without_id = current.clone();
current.version_id = Some(Uuid::nil());
current.data_dir = Some(Uuid::from_u128(2));
let mut original_versions: Vec<_> = (1..=8_192)
.map(|id| DeleteRecoveryVersionIdentity {
version_id: Some(Uuid::from_u128(id)),
..current.clone()
})
.collect();
original_versions.extend([null_without_id.clone(), current.clone()]);
let mut journal = DeleteRecoveryJournal {
protocol_version: DELETE_RECOVERY_PROTOCOL_VERSION,
volume: "bucket".to_owned(),
object: "object".to_owned(),
transaction: Uuid::from_u128(20_000),
bucket_incarnation: None,
original_digest: None,
target_digest: None,
data_dirs: Vec::new(),
deleted_versions: vec![Uuid::from_u128(1)],
requests: Vec::new(),
original_versions,
predecessors: Vec::new(),
};
let versioned = DecisionEvidence::from(&journal);
assert!(versioned.original_null_versions.is_empty());
assert!(versioned.deleted_versions.contains(&Uuid::from_u128(1)));
journal.deleted_versions.push(Uuid::nil());
let mixed = DecisionEvidence::from(&journal);
assert_eq!(mixed.original_null_versions, HashSet::from([null_without_id, current.clone()]));
current.metadata_digest = [1; 32];
assert!(
!mixed.original_null_versions.contains(&current),
"reusing the null version ID cannot authorize a different generation"
);
}
#[tokio::test]
async fn delete_recovery_finished_receipts_do_not_rescan_blocked_siblings() {
let bucket = "recover-finished-before-legacy";
let (dirs, store, disks) = fixture(bucket).await;
let first = put(&store, bucket, &[11; 4096], true).await.expect("first version");
let second = put(&store, bucket, &[12; 4096], true).await.expect("second version");
let survivor = put(&store, bucket, &[13; 4096], true).await.expect("surviving version");
for (id, version) in [(10, first), (20, second)] {
let transaction = applied_at(&store, &disks, bucket, Some(version), disks.len(), Uuid::from_u128(id)).await;
for disk in &disks {
publish(disk, bucket, transaction).await;
let state = disk
.inspect_delete_transaction(bucket, "object", transaction)
.await
.expect("certified transaction");
let finished = disk
.settle_delete_transaction(
bucket,
"object",
transaction,
state.fingerprint,
DeleteRecoveryAction::FinishCommit,
)
.await
.expect("finish certified transaction before coordinator retry");
assert_eq!(finished.state, DeleteRecoveryState::CommitFinished);
}
}
let legacy = Uuid::from_u128(30);
for dir in &dirs {
let data = dir.path().join(bucket).join("object").join(Uuid::from_u128(40).to_string());
tokio::fs::create_dir(&data).await.expect("legacy data directory");
tokio::fs::write(data.join(format!("reserve-delete-data.{legacy}")), [])
.await
.expect("legacy reservation without a decision");
}
// Admit enough work for complete discovery and exactly one inspection
// per transaction and drive. No-op settlement must fit this budget.
let mut entries = 0;
for disk in &disks {
let page = disk
.discover_delete_transactions_bounded(bucket, "object", 4096)
.await
.expect("inspect bounded discovery cost");
assert!(page.complete);
assert_eq!(page.transactions.len(), 3);
entries += page.visited;
for id in page.transactions {
let cost = disk
.inspect_delete_transaction_bounded(bucket, "object", id.transaction, 4096)
.await
.expect("inspect bounded evidence cost");
entries += cost.visited;
}
}
let incarnation = store.bucket_incarnation_id_from_disk(bucket).await.expect("bucket identity");
let mut context = DeleteRecoveryContext::new(Some(incarnation), &|| true);
context.work_budget = Some(Arc::new(crate::object_api::DeleteRecoveryWorkBudget::new(entries)));
let report = store.pools[0].disk_set[0]
.recover_delete_object(bucket, "object", context)
.await
.expect("finished receipts must not invalidate sibling inspections");
assert_eq!(report.committed, 2);
assert_eq!(report.legacy_ambiguous, 1);
for disk in &disks {
let page = disk
.discover_delete_transactions(bucket, Some("object"), None, 128)
.await
.expect("unresolved key still retains its evidence");
assert_eq!(page.transactions.len(), 3, "the key-wide GC barrier keeps certified receipts");
}
assert_eq!(body(&store, bucket, Some(survivor)).await, vec![13; 4096]);
}
#[tokio::test]
async fn delete_recovery_partial_receipt_converges_after_later_version_absence() {
let bucket = "recover-partial-chained-versions";

Some files were not shown because too many files have changed in this diff Show More