mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-23 16:38:49 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4f279d4e35 |
@@ -1,2 +1,2 @@
|
||||
sha256-linux=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
|
||||
sha256-darwin=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
|
||||
sha256-linux=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
|
||||
sha256-darwin=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
sha256-darwin=d5f2a266740f695cf6734965a4d25b390e669aaaa2fc87805c45e42de83f13ca
|
||||
sha256-linux=448ac2ebd537def9f2a63b8961d80a6521f7ef05f952834ec997faed52bfb901
|
||||
sha256-darwin=9ccb03f4139e99ec11a63810523d504df39191b86e74b28a72dd9a075682293b
|
||||
sha256-linux=5ef052b03a03afbd00ebfcbbdcb754bbde414b7e6151aae3e2ee78024ce1d0b6
|
||||
|
||||
@@ -1 +1 @@
|
||||
sha256=a304838fe8ded98a781d7e2e1cf5b22a5cbc11ddfdc4fbaeea91149e5f88d699
|
||||
sha256=fd5683273bba1eae3b4402a4e854a5d168ace845bd0e5fc801f8e336485a4394
|
||||
|
||||
@@ -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::/)
|
||||
|
||||
@@ -13,6 +13,6 @@
|
||||
# s3_error_lines lines holding s3_error!, same scope, minus those the script
|
||||
# header's rule clears (rustfs_s3_types's macro); fails closed
|
||||
# ecstore_files Rust files referencing s3s paths under crates/ecstore/src
|
||||
files=6
|
||||
s3_error_lines=16
|
||||
files=33
|
||||
s3_error_lines=89
|
||||
ecstore_files=0
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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}" \
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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
@@ -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. |
|
||||
|
||||
@@ -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
+219
-330
File diff suppressed because it is too large
Load Diff
+36
-35
@@ -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" }
|
||||
@@ -152,17 +148,20 @@ rustfs-tls-runtime = { path = "crates/tls-runtime", version = "1.0.5" }
|
||||
rustfs-utils = { path = "crates/utils", version = "1.0.5" }
|
||||
rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
|
||||
|
||||
# Pin the gateway and its protocol crates to the same revision.
|
||||
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", version = "0.42.0", default-features = false }
|
||||
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", version = "0.2.0", default-features = false }
|
||||
# The gateway's S3 types: the DTOs and persisted bucket-configuration codecs the
|
||||
# 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 = "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 = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", 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 = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", default-features = false }
|
||||
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", version = "0.63.0", default-features = false }
|
||||
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "5ea2ef14a1e7bd9e8025c7327ff65d8c86445864", 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"
|
||||
@@ -176,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" }
|
||||
@@ -217,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" }
|
||||
@@ -259,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
|
||||
@@ -279,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" }
|
||||
@@ -299,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"
|
||||
@@ -314,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"
|
||||
@@ -339,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"
|
||||
@@ -353,10 +351,16 @@ rustify = { version = "0.7", default-features = false }
|
||||
rustix = { version = "1.1.6" }
|
||||
rust-embed = { version = "8.14.0" }
|
||||
rustc-hash = { version = "2.1.3" }
|
||||
s3s = { git = "https://github.com/s3s-project/s3s", rev = "5761ddfe4c509fcac87e3b99fd5bd9e176b442c0", features = ["minio"] }
|
||||
s3s-sigv4 = { git = "https://github.com/s3s-project/s3s", rev = "5761ddfe4c509fcac87e3b99fd5bd9e176b442c0" }
|
||||
# The same s3s pin under the name the legacy edge of the gateway migration uses
|
||||
# (crates/s3-types, feature `compat-s3s`). Keep `rev` identical to `s3s` above.
|
||||
# DELETE BY T4.2 (rustfs/backlog#2784).
|
||||
legacy-s3s = { package = "s3s", git = "https://github.com/s3s-project/s3s", rev = "5761ddfe4c509fcac87e3b99fd5bd9e176b442c0", features = ["minio"] }
|
||||
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" }
|
||||
@@ -374,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" }
|
||||
@@ -401,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"
|
||||
@@ -419,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
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -65,7 +65,7 @@ pub const MAX_HEAL_REQUEST_SIZE: usize = 1024 * 1024; // 1 MB
|
||||
pub const MAX_S3_CLIENT_RESPONSE_SIZE: usize = 10 * 1024 * 1024; // 10 MB
|
||||
|
||||
/// Maximum body size accepted by a single `PutObject` or `UploadPart` request (5 GiB).
|
||||
/// Enforced on the upload body and at request-header admission.
|
||||
/// Used for: the s3s streaming-body limit and the request-header admission check.
|
||||
/// Rationale: matches the AWS S3 single-PUT / single-part ceiling. Larger objects
|
||||
/// must use multipart upload. The header check rejects an oversize
|
||||
/// `Content-Length` before any body byte is read so the client gets
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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"]
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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}; }
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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::*;
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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
File diff suppressed because it is too large
Load Diff
@@ -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(¤t), 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());
|
||||
}
|
||||
|
||||
@@ -138,13 +138,8 @@ rustls = { workspace = true, default-features = false, features = ["aws-lc-rs",
|
||||
clap = { workspace = true, features = ["derive", "env"] }
|
||||
|
||||
[dev-dependencies]
|
||||
rustfs-gateway.workspace = true
|
||||
rustfs-gateway-types.workspace = true
|
||||
rustfs-gateway-stream.workspace = true
|
||||
serde-value.workspace = true
|
||||
s3s = { git = "https://github.com/s3s-project/s3s", rev = "5761ddfe4c509fcac87e3b99fd5bd9e176b442c0", features = ["minio"] }
|
||||
s3s-sigv4 = { git = "https://github.com/s3s-project/s3s", rev = "5761ddfe4c509fcac87e3b99fd5bd9e176b442c0" }
|
||||
url.workspace = true
|
||||
s3s = { workspace = true, features = ["minio"] }
|
||||
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,587 +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.
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
// 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(×tamp).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", ×tamp),
|
||||
],
|
||||
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();
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -1035,7 +1035,8 @@ pub async fn execute_awscurl(
|
||||
|
||||
/// `POST` with SigV4 `--service sts` and explicit `Content-Type: application/x-www-form-urlencoded`.
|
||||
///
|
||||
/// RustFS uses this content type to recognize an STS query on `POST /`.
|
||||
/// RustFS `AssumeRole` is handled on `POST /` by the admin router; `is_match` requires this
|
||||
/// content type so s3s routes to the custom handler instead of `Unknown operation`.
|
||||
pub async fn awscurl_post_sts_form_urlencoded(
|
||||
url: &str,
|
||||
body: &str,
|
||||
|
||||
@@ -21,8 +21,23 @@
|
||||
//! when it fails to parse (`amztime.ParseHeader` error is swallowed), so the copy
|
||||
//! proceeds.
|
||||
//!
|
||||
//! The RustFS gateway profile rejects unreadable conditional dates before the copy handler runs.
|
||||
//! The signed requests below pin both the successful copy and the HTTP 400 `InvalidArgument` response.
|
||||
//! RustFS routes S3 through the `s3s` crate, which models the copy-source
|
||||
//! conditional-date headers as typed `Timestamp` fields and rejects an
|
||||
//! unparsable value with `400 InvalidArgument` during request deserialization —
|
||||
//! this happens *after* SigV4 verification but *before* the RustFS `CopyObject`
|
||||
//! handler runs. Because the header is part of the client's `SignedHeaders`, the
|
||||
//! value cannot be stripped or rewritten by a pre-`s3s` layer without breaking the
|
||||
//! signature, and `s3s` exposes no hook between auth and typed deserialization.
|
||||
//! Matching MinIO's tolerant behavior therefore requires a change in `s3s`
|
||||
//! (lenient parsing of conditional-date headers). See the PR description for
|
||||
//! details.
|
||||
//!
|
||||
//! This test pins the two ends of the current behavior:
|
||||
//! * a *valid* HTTP-date copy-source conditional header is accepted and the copy
|
||||
//! succeeds (the common, real-SDK path), and
|
||||
//! * an *invalid* date value is rejected with `400 InvalidArgument` at the `s3s`
|
||||
//! layer (the documented gap). When `s3s` gains lenient parsing, the second
|
||||
//! assertion should be flipped to expect a successful copy.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -86,7 +101,7 @@ mod tests {
|
||||
|
||||
let copy_source = format!("/{bucket}/src.txt");
|
||||
|
||||
// A valid future HTTP-date allows the copy.
|
||||
// A valid future HTTP-date is accepted by s3s and the copy succeeds.
|
||||
let (status, body) = signed_copy(
|
||||
&env.url,
|
||||
&format!("/{bucket}/dst-valid.txt"),
|
||||
@@ -99,7 +114,10 @@ mod tests {
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "valid copy-source date must succeed: {body}");
|
||||
assert!(body.contains("CopyObjectResult"), "expected CopyObjectResult XML: {body}");
|
||||
|
||||
// The signed header reaches the RustFS profile's conditional-date check unchanged.
|
||||
// An unparsable date ("Invalid Date") is currently rejected by s3s at the
|
||||
// deserialization layer with 400 InvalidArgument. This documents the s3s
|
||||
// limitation described in backlog#618 item 8. When s3s parses these headers
|
||||
// leniently (matching MinIO), this should become a successful copy.
|
||||
let (status, body) = signed_copy(
|
||||
&env.url,
|
||||
&format!("/{bucket}/dst-invalid.txt"),
|
||||
@@ -112,7 +130,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::BAD_REQUEST,
|
||||
"expected the signed invalid date to be rejected (backlog#618): {body}"
|
||||
"invalid copy-source date currently rejected by s3s (backlog#618): {body}"
|
||||
);
|
||||
assert!(body.contains("InvalidArgument"), "expected InvalidArgument for invalid date: {body}");
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
# Programmable fake S3 target
|
||||
|
||||
This module is the shared failure-injection boundary for replication end-to-end tests and the programmable external source for on-demand-migration (ODM) tests. It runs an in-process, path-style S3 endpoint with the RustFS gateway and an in-memory store.
|
||||
This module is the shared failure-injection boundary for replication end-to-end tests and the programmable external source for on-demand-migration (ODM) tests. It runs an in-process, path-style S3 endpoint backed by `s3s`; no production crate depends on it.
|
||||
|
||||
`FakeS3Target::start()` creates the listener. Add target buckets with `create_bucket`, point a RustFS remote target at `address()`, use `FAKE_ACCESS_KEY` / `FAKE_SECRET_KEY`, then enqueue per-operation faults with `inject`. Faults for one operation are consumed in FIFO order and do not consume faults queued for another operation. A fault is consumed only after the gateway verifies the request signature, so anonymous, other-access-key, and bad-signature traffic cannot disturb a script.
|
||||
`FakeS3Target::start()` creates the listener. Add target buckets with `create_bucket`, point a RustFS remote target at `address()`, use `FAKE_ACCESS_KEY` / `FAKE_SECRET_KEY`, then enqueue per-operation faults with `inject`. Faults for one operation are consumed in FIFO order and do not consume faults queued for another operation. A fault is consumed only after `s3s` verifies the full request signature, so anonymous, other-access-key, and bad-signature traffic cannot disturb a script.
|
||||
|
||||
Supported data operations are HeadBucket, GetBucketVersioning, ListObjectsV2, PUT/GET/HEAD/DELETE Object, Get/Put/Delete ObjectTagging (tags live per version; Put replaces the whole set, Delete clears it), and create/upload/complete/abort multipart upload. `create_bucket` models general-purpose buckets in S3's shared global namespace; account-regional namespace buckets and their `-an` names are intentionally out of scope. Buckets created with `create_bucket` are versioned: PUT creates a version, DELETE without `versionId` creates a delete marker, and DELETE with `versionId` removes exactly that version. Internal source version IDs must be UUIDs and are stored canonically. Source mtime is honored only for source-replication PUT/DELETE requests; absent or invalid values use receipt time, matching RustFS, while multipart completion always uses receipt time. Replicated versions are ordered newest-first by source mtime so late older versions and delete markers do not become current. Equal mtimes prefer objects over delete markers, then canonical UUID order; RustFS's internal FileMeta signature tie-break is intentionally out of scope because it is not part of the target S3 protocol. Multipart part numbers follow S3's `1..=10000` range, and every completed part except the final part must be at least 5 MiB.
|
||||
|
||||
|
||||
@@ -1,234 +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::*;
|
||||
use rustfs_gateway::{ETag, ObjectKey, dto};
|
||||
|
||||
impl FakeBackend {
|
||||
pub(super) async fn head_bucket(
|
||||
&self,
|
||||
req: TargetRequest<dto::HeadBucketInput>,
|
||||
) -> S3Result<TargetResponse<dto::HeadBucketOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
if !lock(&self.store).buckets.contains_key(req.input.bucket.as_str()) {
|
||||
return Err(s3_error!(NoSuchBucket, "bucket does not exist"));
|
||||
}
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::HeadBucketOutput::default()),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_bucket_versioning(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetBucketVersioningInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetBucketVersioningOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let versioned = lock(&self.store)
|
||||
.buckets
|
||||
.get(req.input.bucket.as_str())
|
||||
.map(|bucket| bucket.versioned)
|
||||
.ok_or_else(|| s3_error!(NoSuchBucket, "bucket does not exist"))?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetBucketVersioningOutput {
|
||||
status: versioned.then_some(dto::Status::ENABLED),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object_lock_configuration(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectLockConfigurationInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectLockConfigurationOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let object_lock = lock(&self.store)
|
||||
.buckets
|
||||
.get(req.input.bucket.as_str())
|
||||
.map(|bucket| bucket.object_lock)
|
||||
.ok_or_else(|| s3_error!(NoSuchBucket, "bucket does not exist"))?;
|
||||
if !object_lock {
|
||||
return Err(s3_error!(
|
||||
ObjectLockConfigurationNotFoundError,
|
||||
"Object Lock configuration does not exist for this bucket"
|
||||
));
|
||||
}
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetObjectLockConfigurationOutput {
|
||||
object_lock_configuration: Some(dto::ObjectLockConfiguration {
|
||||
object_lock_enabled: Some(dto::ObjectLockEnabled::ENABLED),
|
||||
..Default::default()
|
||||
}),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Current versions only (a key whose newest version is a delete marker
|
||||
/// is hidden), keys in byte order, `delimiter` folding into common
|
||||
/// prefixes that count toward `max-keys`, and `start-after` /
|
||||
/// `continuation-token` cursors. `encoding-type` and `fetch-owner` are
|
||||
/// accepted but ignored.
|
||||
pub(super) async fn list_objects_v2(
|
||||
&self,
|
||||
req: TargetRequest<dto::ListObjectsV2Input>,
|
||||
) -> S3Result<TargetResponse<dto::ListObjectsV2Output>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let prefix = input.prefix.unwrap_or_default();
|
||||
let delimiter = input.delimiter.as_deref().filter(|delimiter| !delimiter.is_empty());
|
||||
let max_keys = input.max_keys.unwrap_or(MAX_LIST_KEYS).clamp(0, MAX_LIST_KEYS);
|
||||
let resume_after = input
|
||||
.continuation_token
|
||||
.as_ref()
|
||||
.map(|token| decode_continuation_token(token.as_str()))
|
||||
.transpose()?;
|
||||
let mut cursors = Vec::with_capacity(2);
|
||||
if let Some(start_after) = input.start_after.as_deref() {
|
||||
cursors.push(ListCursor {
|
||||
after: start_after,
|
||||
skips_group: false,
|
||||
});
|
||||
}
|
||||
if let Some(resume_after) = resume_after.as_deref() {
|
||||
cursors.push(ListCursor {
|
||||
after: resume_after,
|
||||
skips_group: delimiter.is_some_and(|delimiter| resume_after.ends_with(delimiter)),
|
||||
});
|
||||
}
|
||||
let page = {
|
||||
let state = lock(&self.store);
|
||||
let bucket_state = state
|
||||
.buckets
|
||||
.get(input.bucket.as_str())
|
||||
.ok_or_else(|| s3_error!(NoSuchBucket, "bucket does not exist"))?;
|
||||
list_page(
|
||||
bucket_state,
|
||||
&prefix,
|
||||
delimiter,
|
||||
&cursors,
|
||||
usize::try_from(max_keys).map_err(S3Error::internal_error)?,
|
||||
)
|
||||
};
|
||||
let next_continuation_token = page
|
||||
.truncated
|
||||
.then(|| {
|
||||
page.entries
|
||||
.last()
|
||||
.map(|entry| encode_continuation_token(entry.name()).into())
|
||||
})
|
||||
.flatten();
|
||||
let key_count = i32::try_from(page.entries.len()).map_err(S3Error::internal_error)?;
|
||||
let mut contents = Vec::new();
|
||||
let mut common_prefixes = Vec::new();
|
||||
for entry in page.entries {
|
||||
match entry {
|
||||
ListEntry::Object {
|
||||
key,
|
||||
e_tag,
|
||||
last_modified,
|
||||
size,
|
||||
} => contents.push(dto::Object {
|
||||
key: ObjectKey::new(key).map_err(S3Error::internal_error)?,
|
||||
e_tag: Some(ETag::from_stored(e_tag)),
|
||||
last_modified,
|
||||
size: i64::try_from(size).map_err(S3Error::internal_error)?,
|
||||
storage_class: dto::StorageClass::STANDARD,
|
||||
..Default::default()
|
||||
}),
|
||||
ListEntry::CommonPrefix(prefix) => common_prefixes.push(dto::CommonPrefix { prefix }),
|
||||
}
|
||||
}
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::ListObjectsV2Output {
|
||||
name: input.bucket,
|
||||
prefix,
|
||||
delimiter: input.delimiter,
|
||||
max_keys,
|
||||
key_count,
|
||||
continuation_token: input.continuation_token,
|
||||
start_after: input.start_after,
|
||||
encoding_type: input.encoding_type,
|
||||
is_truncated: page.truncated,
|
||||
next_continuation_token,
|
||||
contents,
|
||||
common_prefixes,
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Prefix + max-keys subset only — enough for the replication-check probe
|
||||
/// key allocation. No pagination markers or delimiter folding.
|
||||
pub(super) async fn list_object_versions(
|
||||
&self,
|
||||
req: TargetRequest<dto::ListObjectVersionsInput>,
|
||||
) -> S3Result<TargetResponse<dto::ListObjectVersionsOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let state = lock(&self.store);
|
||||
let Some(bucket_state) = state.buckets.get(req.input.bucket.as_str()) else {
|
||||
return Err(s3_error!(NoSuchBucket, "bucket does not exist"));
|
||||
};
|
||||
let prefix = req.input.prefix.as_deref().unwrap_or_default();
|
||||
let max_keys = usize::try_from(req.input.max_keys.unwrap_or(MAX_LIST_KEYS).max(0)).map_err(S3Error::internal_error)?;
|
||||
|
||||
let mut keys: Vec<&String> = bucket_state.objects.keys().filter(|key| key.starts_with(prefix)).collect();
|
||||
keys.sort();
|
||||
|
||||
let mut versions = Vec::new();
|
||||
let mut delete_markers = Vec::new();
|
||||
'keys: for key in keys {
|
||||
for version in bucket_state.objects[key].iter().rev() {
|
||||
if versions.len() + delete_markers.len() >= max_keys {
|
||||
break 'keys;
|
||||
}
|
||||
if version.delete_marker {
|
||||
delete_markers.push(dto::DeleteMarkerEntry {
|
||||
key: ObjectKey::new(key.clone()).map_err(S3Error::internal_error)?,
|
||||
version_id: version.version_id.clone().into(),
|
||||
last_modified: version.last_modified,
|
||||
..Default::default()
|
||||
});
|
||||
} else {
|
||||
versions.push(dto::ObjectVersion {
|
||||
key: ObjectKey::new(key.clone()).map_err(S3Error::internal_error)?,
|
||||
version_id: version.version_id.clone().into(),
|
||||
last_modified: version.last_modified,
|
||||
e_tag: Some(ETag::from_stored(version.e_tag.clone())),
|
||||
size: i64::try_from(version.body.len()).map_err(S3Error::internal_error)?,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(state);
|
||||
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::ListObjectVersionsOutput {
|
||||
name: req.input.bucket,
|
||||
versions,
|
||||
delete_markers,
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,327 +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.
|
||||
|
||||
//! Multipart staging and publication for the programmable remote S3 target.
|
||||
|
||||
use super::*;
|
||||
use rustfs_gateway::{BucketName, ObjectKey, RecordedUpload, UploadIdClaim, dto};
|
||||
use rustfs_s3_types::{S3Result, s3_error};
|
||||
|
||||
impl RecordedUpload for MultipartState {
|
||||
fn bucket(&self) -> &str {
|
||||
&self.bucket
|
||||
}
|
||||
|
||||
fn key(&self) -> &str {
|
||||
&self.key
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_upload<'id, 'store>(
|
||||
state: &'store StoreState,
|
||||
claim: &'id UploadIdClaim,
|
||||
bucket: &BucketName,
|
||||
key: &ObjectKey,
|
||||
) -> S3Result<(&'id str, &'store MultipartState)> {
|
||||
let (id, upload) = rustfs_gateway::resolve_upload(claim, bucket, key, |id| state.uploads.get(id))
|
||||
.map_err(|_| s3_error!(NoSuchUpload, "multipart upload does not exist"))?;
|
||||
Ok((id.id(), upload))
|
||||
}
|
||||
|
||||
impl FakeBackend {
|
||||
pub(super) async fn create_multipart_upload(
|
||||
&self,
|
||||
req: TargetRequest<dto::CreateMultipartUploadInput>,
|
||||
) -> S3Result<TargetResponse<dto::CreateMultipartUploadOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let headers = req.headers;
|
||||
let input = req.input;
|
||||
let mut state = lock(&self.store);
|
||||
if !state.buckets.contains_key(input.bucket.as_str()) {
|
||||
return Err(s3_error!(NoSuchBucket, "bucket does not exist"));
|
||||
}
|
||||
ensure_upload_budget(&state)?;
|
||||
let metadata = (!input.metadata.is_empty()).then(|| input.metadata.into_iter().collect());
|
||||
validate_stored_metadata(&input.content_type, &metadata)?;
|
||||
let standard_headers = StandardHeaders {
|
||||
cache_control: input.cache_control,
|
||||
content_disposition: input.content_disposition,
|
||||
content_encoding: input.content_encoding,
|
||||
content_language: input.content_language,
|
||||
expires: input.expires.map(|value| value.as_str().to_owned()),
|
||||
};
|
||||
standard_headers.validate()?;
|
||||
let upload_id = Uuid::new_v4().to_string();
|
||||
// Read the flags before the mutable borrow of `state.uploads` below
|
||||
// (and never re-lock the store: the mutex is not reentrant).
|
||||
let mint_own = state.assign_own_version_ids || state.assign_own_multipart_version_ids;
|
||||
let drop_unlisted = state.drop_unlisted_replication_headers;
|
||||
let version_id = if bucket_versioned(&state, input.bucket.as_str()) {
|
||||
new_version_id(&headers, mint_own)?
|
||||
} else {
|
||||
NULL_VERSION_ID.to_string()
|
||||
};
|
||||
state.uploads.insert(
|
||||
upload_id.clone(),
|
||||
MultipartState {
|
||||
bucket: input.bucket.as_str().to_owned(),
|
||||
key: input.key.as_str().to_owned(),
|
||||
version_id,
|
||||
content_type: input.content_type,
|
||||
metadata,
|
||||
standard_headers,
|
||||
replication_sse_headers: captured_replication_sse_headers(&headers, drop_unlisted),
|
||||
lock: VersionLock::from_headers(
|
||||
input.object_lock_mode,
|
||||
input.object_lock_retain_until_date,
|
||||
input.object_lock_legal_hold_status,
|
||||
),
|
||||
parts: BTreeMap::new(),
|
||||
},
|
||||
);
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::CreateMultipartUploadOutput {
|
||||
bucket: input.bucket,
|
||||
key: input.key,
|
||||
upload_id,
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn upload_part(
|
||||
&self,
|
||||
req: TargetRequest<dto::UploadPartInput>,
|
||||
) -> S3Result<TargetResponse<dto::UploadPartOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
let declared_actual_size = req
|
||||
.headers
|
||||
.get("x-rustfs-replication-part-actual-size")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<usize>().ok());
|
||||
let _body_permit = timeout(MAX_FAULT_DURATION, Arc::clone(&self.body_limit).acquire_owned())
|
||||
.await
|
||||
.map_err(|_| s3_error!(RequestTimeout, "fake target body limiter wait exceeded 30 seconds"))?
|
||||
.map_err(|_| s3_error!(ServiceUnavailable, "fake target body limiter closed"))?;
|
||||
let input = req.input;
|
||||
if !(1..=10_000).contains(&input.part_number) {
|
||||
return Err(s3_error!(InvalidArgument, "part number must be in 1..=10000"));
|
||||
}
|
||||
let max_object_bytes = lock(&self.store).limits.max_object_bytes;
|
||||
let body =
|
||||
collect_stream(input.body, Some(input.content_length), fault.as_ref(), &self.control, max_object_bytes).await?;
|
||||
let (digest, _body_permit) = md5_digest(body.clone(), _body_permit).await?;
|
||||
let e_tag = hex_simd::encode_to_string(digest, hex_simd::AsciiCase::Lower);
|
||||
let mut state = lock(&self.store);
|
||||
let (upload_id, upload) = resolve_upload(&state, &input.upload_id, &input.bucket, &input.key)?;
|
||||
let existing = upload.parts.get(&input.part_number);
|
||||
let existing_bytes = existing.map_or(0, |part| part.body.len());
|
||||
let adds_part = existing.is_none();
|
||||
ensure_part_budget(&state, adds_part)?;
|
||||
ensure_store_budget(&state, existing_bytes, body.len(), false)?;
|
||||
state.total_bytes = state.total_bytes - existing_bytes + body.len();
|
||||
if adds_part {
|
||||
state.total_parts += 1;
|
||||
}
|
||||
let upload = state.uploads.get_mut(upload_id).expect("upload existence checked above");
|
||||
upload.parts.insert(
|
||||
input.part_number,
|
||||
MultipartPart {
|
||||
body,
|
||||
e_tag: e_tag.clone(),
|
||||
digest,
|
||||
actual_size: declared_actual_size,
|
||||
},
|
||||
);
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::UploadPartOutput {
|
||||
e_tag: rustfs_gateway::ETag::from_stored(maybe_wrong_etag(fault.as_ref(), e_tag)),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn complete_multipart_upload(
|
||||
&self,
|
||||
mut req: TargetRequest<dto::CompleteMultipartUploadInput>,
|
||||
) -> S3Result<TargetResponse<dto::CompleteMultipartUploadOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let _body_permits = match req.extensions.remove::<PrebodyPermit>().and_then(PrebodyPermit::take) {
|
||||
Some(permit) => permit,
|
||||
None => timeout(
|
||||
MAX_FAULT_DURATION,
|
||||
Arc::clone(&self.body_limit).acquire_many_owned(MAX_CONCURRENT_BODY_REQUESTS as u32),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| s3_error!(RequestTimeout, "fake target body limiter wait exceeded 30 seconds"))?
|
||||
.map_err(|_| s3_error!(ServiceUnavailable, "fake target body limiter closed"))?,
|
||||
};
|
||||
let headers = req.headers;
|
||||
let input = req.input;
|
||||
let requested = input.multipart_upload.parts;
|
||||
if requested.is_empty() {
|
||||
return Err(s3_error!(InvalidPart, "completion omitted parts"));
|
||||
}
|
||||
let mut requested_parts = Vec::with_capacity(requested.len());
|
||||
let mut previous = 0;
|
||||
for part in &requested {
|
||||
let number = part.part_number;
|
||||
if number <= previous {
|
||||
return Err(s3_error!(InvalidPartOrder, "parts are not strictly ordered"));
|
||||
}
|
||||
previous = number;
|
||||
let requested_etag = part
|
||||
.e_tag
|
||||
.as_ref()
|
||||
.ok_or_else(|| s3_error!(InvalidPart, "part ETag is missing"))?;
|
||||
requested_parts.push((number, normalize_etag(requested_etag.opaque_tag())));
|
||||
}
|
||||
|
||||
let (upload_id, upload, selected_parts) = {
|
||||
let state = lock(&self.store);
|
||||
let (upload_id, upload) = resolve_upload(&state, &input.upload_id, &input.bucket, &input.key)?;
|
||||
let mut selected = Vec::with_capacity(requested_parts.len());
|
||||
for (index, (number, requested_etag)) in requested_parts.iter().enumerate() {
|
||||
let stored = upload
|
||||
.parts
|
||||
.get(number)
|
||||
.ok_or_else(|| s3_error!(InvalidPart, "part was not uploaded"))?;
|
||||
if requested_etag != &stored.e_tag {
|
||||
return Err(s3_error!(InvalidPart, "part ETag does not match"));
|
||||
}
|
||||
if index + 1 != requested_parts.len()
|
||||
&& stored.actual_size.unwrap_or(stored.body.len()) < MIN_MULTIPART_PART_BYTES
|
||||
{
|
||||
return Err(s3_error!(EntityTooSmall, "non-final multipart part is smaller than 5 MiB"));
|
||||
}
|
||||
selected.push((*number, stored.clone()));
|
||||
}
|
||||
(
|
||||
upload_id,
|
||||
MultipartState {
|
||||
bucket: upload.bucket.clone(),
|
||||
key: upload.key.clone(),
|
||||
version_id: upload.version_id.clone(),
|
||||
content_type: upload.content_type.clone(),
|
||||
metadata: upload.metadata.clone(),
|
||||
standard_headers: upload.standard_headers.clone(),
|
||||
replication_sse_headers: upload.replication_sse_headers.clone(),
|
||||
lock: upload.lock.clone(),
|
||||
parts: BTreeMap::new(),
|
||||
},
|
||||
selected,
|
||||
)
|
||||
};
|
||||
let max_total_bytes = lock(&self.store).limits.max_total_bytes;
|
||||
let total_len = selected_parts.iter().try_fold(0usize, |total, (_, part)| {
|
||||
total
|
||||
.checked_add(part.body.len())
|
||||
.filter(|total| *total <= max_total_bytes)
|
||||
.ok_or_else(|| s3_error!(EntityTooLarge, "multipart object exceeds {max_total_bytes} bytes"))
|
||||
})?;
|
||||
let assembly_parts = selected_parts
|
||||
.iter()
|
||||
.map(|(_, stored)| (stored.body.clone(), stored.digest))
|
||||
.collect();
|
||||
let (body, digests, _body_permits) = assemble_multipart(assembly_parts, total_len, _body_permits).await?;
|
||||
let part_count = requested.len();
|
||||
let ignore_source_etags = lock(&self.store).ignore_source_etags;
|
||||
let e_tag = source_etag(&headers)?
|
||||
.filter(|_| !ignore_source_etags)
|
||||
.unwrap_or_else(|| format!("{}-{part_count}", md5_hex(digests)));
|
||||
let version = ObjectVersion {
|
||||
version_id: upload.version_id.clone(),
|
||||
body,
|
||||
e_tag: e_tag.clone(),
|
||||
last_modified: now_timestamp(),
|
||||
delete_marker: false,
|
||||
content_type: upload.content_type,
|
||||
metadata: upload.metadata,
|
||||
standard_headers: upload.standard_headers,
|
||||
tags: Vec::new(),
|
||||
replication_sse_headers: upload.replication_sse_headers,
|
||||
lock: upload.lock,
|
||||
};
|
||||
let mut state = lock(&self.store);
|
||||
let versioned = bucket_versioned(&state, input.bucket.as_str());
|
||||
let current = state
|
||||
.uploads
|
||||
.get(upload_id)
|
||||
.filter(|current| current.bucket == input.bucket.as_str() && current.key == input.key.as_str())
|
||||
.ok_or_else(|| s3_error!(NoSuchUpload, "multipart upload does not exist"))?;
|
||||
for (part, (selected_number, selected_part)) in requested.iter().zip(&selected_parts) {
|
||||
let number = part.part_number;
|
||||
debug_assert_eq!(number, *selected_number);
|
||||
let current_part = current
|
||||
.parts
|
||||
.get(&number)
|
||||
.ok_or_else(|| s3_error!(InvalidPart, "part changed during completion"))?;
|
||||
if current_part.e_tag != selected_part.e_tag {
|
||||
return Err(s3_error!(InvalidPart, "part changed during completion"));
|
||||
}
|
||||
}
|
||||
let upload_bytes = current.parts.values().map(|part| part.body.len()).sum::<usize>();
|
||||
let upload_part_count = current.parts.len();
|
||||
let existing = state
|
||||
.buckets
|
||||
.get(input.bucket.as_str())
|
||||
.ok_or_else(|| s3_error!(NoSuchBucket, "bucket does not exist"))?
|
||||
.objects
|
||||
.get(input.key.as_str())
|
||||
.and_then(|versions| versions.iter().find(|candidate| candidate.version_id == version.version_id))
|
||||
.map(|version| version.body.len());
|
||||
ensure_store_budget(
|
||||
&state,
|
||||
upload_bytes + existing.unwrap_or_default(),
|
||||
version.body.len(),
|
||||
existing.is_none(),
|
||||
)?;
|
||||
state.total_bytes -= upload_bytes;
|
||||
state.total_parts -= upload_part_count;
|
||||
state.uploads.remove(upload_id);
|
||||
upsert_version(&mut state, input.bucket.as_str(), input.key.as_str().to_owned(), version)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::CompleteMultipartUploadOutput {
|
||||
bucket: Some(input.bucket),
|
||||
key: Some(input.key),
|
||||
e_tag: Some(rustfs_gateway::ETag::from_stored(maybe_wrong_etag(fault.as_ref(), e_tag))),
|
||||
version_id: versioned.then_some(upload.version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn abort_multipart_upload(
|
||||
&self,
|
||||
req: TargetRequest<dto::AbortMultipartUploadInput>,
|
||||
) -> S3Result<TargetResponse<dto::AbortMultipartUploadOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let mut state = lock(&self.store);
|
||||
let (upload_id, _) = resolve_upload(&state, &input.upload_id, &input.bucket, &input.key)?;
|
||||
let removed = state.uploads.remove(upload_id).expect("upload existence checked above");
|
||||
state.total_bytes -= removed.parts.values().map(|part| part.body.len()).sum::<usize>();
|
||||
state.total_parts -= removed.parts.len();
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::AbortMultipartUploadOutput::default()),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,545 +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.
|
||||
|
||||
//! Object operations for the programmable S3 target.
|
||||
|
||||
use super::*;
|
||||
use rustfs_gateway::{ByteStream, ETag, dto};
|
||||
|
||||
impl FakeBackend {
|
||||
pub(super) async fn put_object(
|
||||
&self,
|
||||
req: TargetRequest<dto::PutObjectInput>,
|
||||
) -> S3Result<TargetResponse<dto::PutObjectOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
let _body_permit = timeout(MAX_FAULT_DURATION, Arc::clone(&self.body_limit).acquire_owned())
|
||||
.await
|
||||
.map_err(|_| s3_error!(RequestTimeout, "fake target body limiter wait exceeded 30 seconds"))?
|
||||
.map_err(|_| s3_error!(ServiceUnavailable, "fake target body limiter closed"))?;
|
||||
let headers = req.headers;
|
||||
let input = req.input;
|
||||
let (assign_own, drop_unlisted, require_checksum, ignore_source_etags, limits, versioned) = {
|
||||
let state = lock(&self.store);
|
||||
(
|
||||
state.assign_own_version_ids,
|
||||
state.drop_unlisted_replication_headers,
|
||||
state.require_checksum_for_object_lock,
|
||||
state.ignore_source_etags,
|
||||
state.limits,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
let transport = TransportSnapshot::from_headers(&headers);
|
||||
if require_checksum
|
||||
&& transport.object_lock_params
|
||||
&& transport.content_md5.is_none()
|
||||
&& transport.checksum_headers.is_empty()
|
||||
{
|
||||
return Err(s3_error!(
|
||||
InvalidRequest,
|
||||
"Content-MD5 OR x-amz-checksum- HTTP header is required for Put Object requests with Object Lock parameters"
|
||||
));
|
||||
}
|
||||
let body = collect_stream(
|
||||
input.body,
|
||||
Some(input.content_length),
|
||||
fault.as_ref(),
|
||||
&self.control,
|
||||
limits.max_object_bytes,
|
||||
)
|
||||
.await?;
|
||||
let mut body_permit = _body_permit;
|
||||
if let Some(expected) = &transport.content_md5 {
|
||||
let (digest, permit) = md5_digest(body.clone(), body_permit).await?;
|
||||
body_permit = permit;
|
||||
if BASE64_STANDARD.encode_to_string(digest) != expected.trim() {
|
||||
return Err(s3_error!(BadDigest, "The Content-MD5 you specified did not match what we received."));
|
||||
}
|
||||
}
|
||||
let metadata = (!input.metadata.is_empty()).then(|| input.metadata.into_iter().collect());
|
||||
validate_stored_metadata(&input.content_type, &metadata)?;
|
||||
let standard_headers = StandardHeaders {
|
||||
cache_control: input.cache_control,
|
||||
content_disposition: input.content_disposition,
|
||||
content_encoding: input.content_encoding,
|
||||
content_language: input.content_language,
|
||||
expires: input.expires.map(|value| value.into_string()),
|
||||
};
|
||||
standard_headers.validate()?;
|
||||
let version_id = if versioned {
|
||||
new_version_id(&headers, assign_own)?
|
||||
} else {
|
||||
NULL_VERSION_ID.to_string()
|
||||
};
|
||||
let e_tag = match source_etag(&headers)?.filter(|_| !ignore_source_etags) {
|
||||
Some(value) => value,
|
||||
None => {
|
||||
let (digest, permit) = md5_digest(body.clone(), body_permit).await?;
|
||||
body_permit = permit;
|
||||
hex_simd::encode_to_string(digest, hex_simd::AsciiCase::Lower)
|
||||
}
|
||||
};
|
||||
// Held until the version is stored, like every other body-bearing op.
|
||||
let _body_permit = body_permit;
|
||||
let version = ObjectVersion {
|
||||
version_id: version_id.clone(),
|
||||
body,
|
||||
e_tag: e_tag.clone(),
|
||||
last_modified: source_mtime(&headers),
|
||||
delete_marker: false,
|
||||
content_type: input.content_type,
|
||||
metadata,
|
||||
standard_headers,
|
||||
tags: Vec::new(),
|
||||
replication_sse_headers: captured_replication_sse_headers(&headers, drop_unlisted),
|
||||
lock: VersionLock::from_headers(
|
||||
input.object_lock_mode,
|
||||
input.object_lock_retain_until_date,
|
||||
input.object_lock_legal_hold_status,
|
||||
),
|
||||
};
|
||||
upsert_version(&mut lock(&self.store), input.bucket.as_str(), input.key.as_str().to_owned(), version)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::PutObjectOutput {
|
||||
e_tag: ETag::from_stored(maybe_wrong_etag(fault.as_ref(), e_tag)),
|
||||
version_id: versioned.then_some(version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let held_get = lock(&self.control)
|
||||
.held_get
|
||||
.as_ref()
|
||||
.filter(|held| held.bucket == input.bucket.as_str() && held.key == input.key.as_str())
|
||||
.cloned();
|
||||
if let Some(mut held) = held_get {
|
||||
held.entered.send_modify(|count| *count += 1);
|
||||
// Keep the gate installed when a request is cancelled or times out:
|
||||
// a retry must cross the same boundary before returning any bytes.
|
||||
let _ = held.released.wait_for(|released| *released).await;
|
||||
}
|
||||
let (version, versioned) = {
|
||||
let state = lock(&self.store);
|
||||
(
|
||||
find_version(&state, input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
let sse_customer_algorithm = stored_sse_customer_algorithm(&version);
|
||||
let served = resolve_range(input.range.as_ref(), version.body.len())?;
|
||||
let body = version.body.slice(served.range.clone());
|
||||
let body = match fault.as_ref().map(|fault| &fault.action) {
|
||||
Some(FaultAction::TruncateBodyAt(truncate_at)) => truncated_body(body, *truncate_at),
|
||||
Some(FaultAction::SlowSendBody { chunk_bytes, delay }) => slow_sent_body(body, *chunk_bytes, *delay),
|
||||
_ => ByteStream::from_bytes(body),
|
||||
};
|
||||
let mut response = TargetResponse::new(dto::GetObjectOutput {
|
||||
body: Some(body),
|
||||
content_length: Some(served.len() as i64),
|
||||
content_range: served.content_range,
|
||||
accept_ranges: Some("bytes".to_string()),
|
||||
content_type: version.content_type,
|
||||
metadata: version.metadata.unwrap_or_default().into_iter().collect(),
|
||||
cache_control: version.standard_headers.cache_control,
|
||||
content_disposition: version.standard_headers.content_disposition,
|
||||
content_encoding: version.standard_headers.content_encoding,
|
||||
content_language: version.standard_headers.content_language,
|
||||
expires: version.standard_headers.expires.map(Into::into),
|
||||
e_tag: Some(ETag::from_stored(version.e_tag)),
|
||||
last_modified: Some(version.last_modified),
|
||||
version_id: versioned.then_some(version.version_id),
|
||||
sse_customer_algorithm,
|
||||
object_lock_mode: version
|
||||
.lock
|
||||
.retention
|
||||
.as_ref()
|
||||
.map(|(mode, _)| dto::ObjectLockMode::custom(mode.clone())),
|
||||
object_lock_retain_until_date: version.lock.retention.as_ref().map(|(_, until)| *until),
|
||||
object_lock_legal_hold_status: version.lock.legal_hold_status(),
|
||||
..Default::default()
|
||||
});
|
||||
response.status = served.status;
|
||||
Ok(apply_response_fault(response, fault.as_ref()))
|
||||
}
|
||||
|
||||
pub(super) async fn head_object(
|
||||
&self,
|
||||
req: TargetRequest<dto::HeadObjectInput>,
|
||||
) -> S3Result<TargetResponse<dto::HeadObjectOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let (version, versioned) = {
|
||||
let state = lock(&self.store);
|
||||
(
|
||||
find_version(&state, input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
let sse_customer_algorithm = stored_sse_customer_algorithm(&version);
|
||||
let served = resolve_range(input.range.as_ref(), version.body.len())?;
|
||||
let mut response = TargetResponse::new(dto::HeadObjectOutput {
|
||||
content_length: Some(served.len() as i64),
|
||||
content_range: served.content_range,
|
||||
accept_ranges: Some("bytes".to_string()),
|
||||
content_type: version.content_type,
|
||||
metadata: version.metadata.unwrap_or_default().into_iter().collect(),
|
||||
cache_control: version.standard_headers.cache_control,
|
||||
content_disposition: version.standard_headers.content_disposition,
|
||||
content_encoding: version.standard_headers.content_encoding,
|
||||
content_language: version.standard_headers.content_language,
|
||||
expires: version.standard_headers.expires.map(Into::into),
|
||||
e_tag: Some(ETag::from_stored(version.e_tag)),
|
||||
last_modified: Some(version.last_modified),
|
||||
version_id: versioned.then_some(version.version_id),
|
||||
sse_customer_algorithm,
|
||||
object_lock_mode: version
|
||||
.lock
|
||||
.retention
|
||||
.as_ref()
|
||||
.map(|(mode, _)| dto::ObjectLockMode::custom(mode.clone())),
|
||||
object_lock_retain_until_date: version.lock.retention.as_ref().map(|(_, until)| *until),
|
||||
object_lock_legal_hold_status: version.lock.legal_hold_status(),
|
||||
..Default::default()
|
||||
});
|
||||
response.status = served.status;
|
||||
Ok(apply_response_fault(response, fault.as_ref()))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object_tagging(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectTaggingInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectTaggingOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let (version, versioned) = {
|
||||
let state = lock(&self.store);
|
||||
(
|
||||
find_version(&state, input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
let tag_set = version
|
||||
.tags
|
||||
.into_iter()
|
||||
.map(|(key, value)| dto::Tag {
|
||||
key: Some(key),
|
||||
value: Some(value),
|
||||
})
|
||||
.collect();
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetObjectTaggingOutput {
|
||||
tag_set,
|
||||
version_id: versioned.then_some(version.version_id),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn put_object_tagging(
|
||||
&self,
|
||||
req: TargetRequest<dto::PutObjectTaggingInput>,
|
||||
) -> S3Result<TargetResponse<dto::PutObjectTaggingOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let tags = input
|
||||
.tagging
|
||||
.tag_set
|
||||
.into_iter()
|
||||
.map(|tag| (tag.key.unwrap_or_default(), tag.value.unwrap_or_default()))
|
||||
.collect();
|
||||
let (version_id, versioned) = {
|
||||
let mut state = lock(&self.store);
|
||||
(
|
||||
set_version_tags(&mut state, input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref(), tags)?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::PutObjectTaggingOutput {
|
||||
version_id: versioned.then_some(version_id),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object_retention(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectRetentionInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectRetentionOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let version = find_version(&lock(&self.store), input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetObjectRetentionOutput {
|
||||
retention: version.lock.retention.map(|(mode, until)| dto::ObjectLockRetention {
|
||||
mode: Some(dto::Mode::custom(mode)),
|
||||
retain_until_date: Some(until),
|
||||
..Default::default()
|
||||
}),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn put_object_retention(
|
||||
&self,
|
||||
req: TargetRequest<dto::PutObjectRetentionInput>,
|
||||
) -> S3Result<TargetResponse<dto::PutObjectRetentionOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let retention = input
|
||||
.retention
|
||||
.mode
|
||||
.zip(input.retention.retain_until_date)
|
||||
.map(|(mode, until)| (mode.as_str().to_string(), until));
|
||||
update_version_lock(
|
||||
&mut lock(&self.store),
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
|lock| {
|
||||
lock.retention = retention;
|
||||
},
|
||||
)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::PutObjectRetentionOutput::default()),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn get_object_legal_hold(
|
||||
&self,
|
||||
req: TargetRequest<dto::GetObjectLegalHoldInput>,
|
||||
) -> S3Result<TargetResponse<dto::GetObjectLegalHoldOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let version = find_version(&lock(&self.store), input.bucket.as_str(), input.key.as_str(), input.version_id.as_deref())?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::GetObjectLegalHoldOutput {
|
||||
legal_hold: Some(dto::ObjectLockLegalHold {
|
||||
status: Some(if version.lock.legal_hold == Some(true) {
|
||||
dto::Status::ON
|
||||
} else {
|
||||
dto::Status::OFF
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn put_object_legal_hold(
|
||||
&self,
|
||||
req: TargetRequest<dto::PutObjectLegalHoldInput>,
|
||||
) -> S3Result<TargetResponse<dto::PutObjectLegalHoldOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let legal_hold_on = input
|
||||
.legal_hold
|
||||
.status
|
||||
.is_some_and(|status| status.as_str().eq_ignore_ascii_case("ON"));
|
||||
update_version_lock(
|
||||
&mut lock(&self.store),
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
|lock| {
|
||||
lock.legal_hold = Some(legal_hold_on);
|
||||
},
|
||||
)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::PutObjectLegalHoldOutput::default()),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn delete_object_tagging(
|
||||
&self,
|
||||
req: TargetRequest<dto::DeleteObjectTaggingInput>,
|
||||
) -> S3Result<TargetResponse<dto::DeleteObjectTaggingOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let input = req.input;
|
||||
let (version_id, versioned) = {
|
||||
let mut state = lock(&self.store);
|
||||
(
|
||||
set_version_tags(
|
||||
&mut state,
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str(),
|
||||
input.version_id.as_deref(),
|
||||
Vec::new(),
|
||||
)?,
|
||||
bucket_versioned(&state, input.bucket.as_str()),
|
||||
)
|
||||
};
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectTaggingOutput {
|
||||
version_id: versioned.then_some(version_id),
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) async fn delete_object(
|
||||
&self,
|
||||
req: TargetRequest<dto::DeleteObjectInput>,
|
||||
) -> S3Result<TargetResponse<dto::DeleteObjectOutput>> {
|
||||
let fault = request_fault(&req);
|
||||
apply_non_body_fault(fault.as_ref(), &self.control).await?;
|
||||
let headers = req.headers;
|
||||
let input = req.input;
|
||||
let held_delete = lock(&self.control)
|
||||
.held_delete
|
||||
.as_ref()
|
||||
.filter(|held| held.bucket == input.bucket.as_str() && held.key == input.key.as_str())
|
||||
.cloned();
|
||||
if let Some(mut held) = held_delete {
|
||||
held.entered.send_modify(|count| *count += 1);
|
||||
let _ = held.released.wait_for(|released| *released).await;
|
||||
}
|
||||
let mut state = lock(&self.store);
|
||||
let Some(versioned) = state.buckets.get(input.bucket.as_str()).map(|bucket| bucket.versioned) else {
|
||||
return Err(s3_error!(NoSuchBucket, "bucket does not exist"));
|
||||
};
|
||||
if !versioned {
|
||||
// Unversioned buckets know only the `null` version: DELETE removes
|
||||
// the key outright and never writes a delete marker.
|
||||
if input
|
||||
.version_id
|
||||
.as_deref()
|
||||
.is_some_and(|version_id| version_id != NULL_VERSION_ID)
|
||||
{
|
||||
return Err(s3_error!(InvalidArgument, "invalid version id specified"));
|
||||
}
|
||||
let removed = state
|
||||
.buckets
|
||||
.get_mut(input.bucket.as_str())
|
||||
.expect("bucket existence checked above")
|
||||
.objects
|
||||
.remove(input.key.as_str())
|
||||
.unwrap_or_default();
|
||||
state.total_bytes -= removed.iter().map(|version| version.body.len()).sum::<usize>();
|
||||
state.total_versions -= removed.len();
|
||||
return Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectOutput::default()),
|
||||
fault.as_ref(),
|
||||
));
|
||||
}
|
||||
if let Some(version_id) = input.version_id {
|
||||
let reject_unknown = state.reject_unknown_version_deletes;
|
||||
let (removed_bytes, removed_versions, delete_marker, remove_key) = {
|
||||
let Some(versions) = state
|
||||
.buckets
|
||||
.get_mut(input.bucket.as_str())
|
||||
.expect("bucket existence checked above")
|
||||
.objects
|
||||
.get_mut(input.key.as_str())
|
||||
else {
|
||||
if reject_unknown {
|
||||
return Err(s3_error!(NoSuchVersion, "The specified version does not exist."));
|
||||
}
|
||||
return Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectOutput {
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
));
|
||||
};
|
||||
if reject_unknown && !versions.iter().any(|version| version.version_id == version_id) {
|
||||
return Err(s3_error!(NoSuchVersion, "The specified version does not exist."));
|
||||
}
|
||||
let mut removed_bytes = 0usize;
|
||||
let mut removed_versions = 0usize;
|
||||
let mut delete_marker = None;
|
||||
versions.retain(|version| {
|
||||
if version.version_id == version_id {
|
||||
removed_bytes += version.body.len();
|
||||
removed_versions += 1;
|
||||
delete_marker.get_or_insert(version.delete_marker);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
(removed_bytes, removed_versions, delete_marker, versions.is_empty())
|
||||
};
|
||||
if remove_key {
|
||||
state
|
||||
.buckets
|
||||
.get_mut(input.bucket.as_str())
|
||||
.expect("bucket existence checked above")
|
||||
.objects
|
||||
.remove(input.key.as_str());
|
||||
}
|
||||
state.total_bytes -= removed_bytes;
|
||||
state.total_versions -= removed_versions;
|
||||
return Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectOutput {
|
||||
delete_marker,
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
));
|
||||
}
|
||||
|
||||
// `state` is the live store guard: read the flag from it. Re-locking
|
||||
// would self-deadlock (the store mutex is not reentrant).
|
||||
let version_id = new_version_id(&headers, state.assign_own_version_ids)?;
|
||||
upsert_version(
|
||||
&mut state,
|
||||
input.bucket.as_str(),
|
||||
input.key.as_str().to_owned(),
|
||||
ObjectVersion {
|
||||
version_id: version_id.clone(),
|
||||
body: Bytes::new(),
|
||||
e_tag: String::new(),
|
||||
last_modified: source_mtime(&headers),
|
||||
delete_marker: true,
|
||||
content_type: None,
|
||||
metadata: None,
|
||||
standard_headers: StandardHeaders::default(),
|
||||
tags: Vec::new(),
|
||||
replication_sse_headers: Vec::new(),
|
||||
lock: VersionLock::default(),
|
||||
},
|
||||
)?;
|
||||
Ok(apply_response_fault(
|
||||
TargetResponse::new(dto::DeleteObjectOutput {
|
||||
delete_marker: Some(true),
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
}),
|
||||
fault.as_ref(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,255 +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.
|
||||
|
||||
//! The loopback target's authenticated gateway and scripted wire responses.
|
||||
|
||||
use super::*;
|
||||
use rustfs_gateway::{
|
||||
Authorizer, AuthzRequest, BoxFuture, CodecError, Credentials, Decision, ErrorCode, Handler, HandlerDeadlineConfig,
|
||||
HandlerError, HandlerErrorContext, HandlerResult, InputAuthzRequest, InputDecisions, LegacyRustfsFacts, LegacyRustfsRefusal,
|
||||
Operation as GatewayOperation, PlaintextCustomerKeyAck, RegionSet, Req, RequestBodyDeadlineConfig, RequestContext, Resp,
|
||||
ServiceBuilder, ServiceConfig, SigV4Authenticator, SseConfig, StaticCredentials,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct RequestState(Arc<State>);
|
||||
|
||||
struct State {
|
||||
method: Method,
|
||||
uri: Uri,
|
||||
headers: HeaderMap,
|
||||
sequence: RequestSequence,
|
||||
admitted: OnceLock<http::Extensions>,
|
||||
// A scripted target can deliberately replace a typed header such as ETag on the wire.
|
||||
response_headers: OnceLock<(u16, HeaderMap)>,
|
||||
}
|
||||
|
||||
impl RequestState {
|
||||
pub(super) fn new<B>(request: &Request<B>) -> Self {
|
||||
Self(Arc::new(State {
|
||||
method: request.method().clone(),
|
||||
uri: request.uri().clone(),
|
||||
headers: request.headers().clone(),
|
||||
sequence: RequestSequence::default(),
|
||||
admitted: OnceLock::new(),
|
||||
response_headers: OnceLock::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn sequence(&self) -> Option<u64> {
|
||||
self.0.sequence.0.get().copied()
|
||||
}
|
||||
|
||||
fn save_headers(&self, status: u16, headers: HeaderMap) {
|
||||
if !headers.is_empty() {
|
||||
let _ = self.0.response_headers.set((status, headers));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn apply_response<B>(&self, response: &mut Response<B>) {
|
||||
let Some((status, headers)) = self.0.response_headers.get() else { return };
|
||||
if *status == response.status().as_u16() {
|
||||
response.headers_mut().extend(headers.clone());
|
||||
} else if let Some(disconnect) = headers.get(DISCONNECT_HEADER) {
|
||||
// Dropping a partially consumed upload can also produce a gateway body error. The
|
||||
// scripted transport disconnect was already reached and must still close the socket.
|
||||
response.headers_mut().insert(DISCONNECT_HEADER, disconnect.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn error(&self, error: S3Error) -> HandlerError {
|
||||
let parts = error.into_parts();
|
||||
let status = parts
|
||||
.status
|
||||
.or_else(|| parts.code.status_code())
|
||||
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
|
||||
let code = ErrorCode::custom(parts.code.as_str().to_owned(), status);
|
||||
let message = parts
|
||||
.message
|
||||
.map(|message| message.into_owned())
|
||||
.or_else(|| parts.code.default_message().map(str::to_owned));
|
||||
match LegacyRustfsRefusal::new(code, message, LegacyRustfsFacts::default()) {
|
||||
Ok(refusal) => {
|
||||
self.save_headers(status.as_u16(), parts.headers.unwrap_or_default());
|
||||
HandlerErrorContext::legacy_rustfs(refusal).into()
|
||||
}
|
||||
Err(_) => HandlerError::internal_error("invalid fake target error"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn credential_decision(request: &AuthzRequest<'_>) -> Decision {
|
||||
if request
|
||||
.identity
|
||||
.is_some_and(|identity| identity.access_key_id() == FAKE_ACCESS_KEY)
|
||||
{
|
||||
Decision::Allow
|
||||
} else {
|
||||
Decision::Deny
|
||||
}
|
||||
}
|
||||
|
||||
impl Authorizer for FaultAccess {
|
||||
fn authorize_route<'a>(&'a self, _context: &'a RequestContext<'a>, request: &'a AuthzRequest<'a>) -> BoxFuture<'a, Decision> {
|
||||
Box::pin(async move { credential_decision(request) })
|
||||
}
|
||||
|
||||
fn authorize_route_result<'a>(
|
||||
&'a self,
|
||||
context: &'a RequestContext<'a>,
|
||||
request: &'a AuthzRequest<'a>,
|
||||
) -> BoxFuture<'a, Result<Decision, HandlerError>> {
|
||||
Box::pin(async move {
|
||||
if credential_decision(request) != Decision::Allow {
|
||||
return Err(HandlerError::new(ErrorCode::ACCESS_DENIED, "valid fixture credentials are required"));
|
||||
}
|
||||
let state = context.server_extensions().get::<RequestState>().ok_or_else(missing_state)?;
|
||||
// The gateway can ask several permissions for a single operation. Dispatch consumes
|
||||
// one fault and journals one request, after the signature has been verified.
|
||||
if state.0.admitted.get().is_none() {
|
||||
let extensions = self
|
||||
.admit(
|
||||
&state.0.method,
|
||||
&state.0.uri,
|
||||
&state.0.headers,
|
||||
operation_from_s3_name(request.operation),
|
||||
&state.0.sequence,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| state.error(error))?;
|
||||
state
|
||||
.0
|
||||
.admitted
|
||||
.set(extensions)
|
||||
.map_err(|_| HandlerError::internal_error("fixture request admitted twice"))?;
|
||||
}
|
||||
Ok(Decision::Allow)
|
||||
})
|
||||
}
|
||||
|
||||
fn authorize_input<'a>(
|
||||
&'a self,
|
||||
_context: &'a RequestContext<'a>,
|
||||
request: &'a InputAuthzRequest<'a>,
|
||||
) -> BoxFuture<'a, InputDecisions> {
|
||||
Box::pin(async move { request.decide_all(credential_decision(request.route()), credential_decision) })
|
||||
}
|
||||
}
|
||||
|
||||
fn missing_state() -> HandlerError {
|
||||
HandlerError::internal_error("missing fake target request state")
|
||||
}
|
||||
|
||||
fn target_request<O: GatewayOperation>(request: Req<O>) -> Result<(RequestState, TargetRequest<O::Input>), HandlerError> {
|
||||
let state = request
|
||||
.context()
|
||||
.transport_extensions()
|
||||
.get::<RequestState>()
|
||||
.cloned()
|
||||
.ok_or_else(missing_state)?;
|
||||
let extensions = state.0.admitted.get().cloned().ok_or_else(missing_state)?;
|
||||
let target = TargetRequest {
|
||||
input: request.into_input(),
|
||||
headers: state.0.headers.clone(),
|
||||
extensions,
|
||||
};
|
||||
Ok((state, target))
|
||||
}
|
||||
|
||||
fn target_response<O: GatewayOperation>(state: &RequestState, response: S3Result<TargetResponse<O::Output>>) -> HandlerResult<O> {
|
||||
let TargetResponse { output, headers, status } = response.map_err(|error| state.error(error))?;
|
||||
let response = match status {
|
||||
Some(status) => Resp::<O>::with_status(output, status.as_u16()),
|
||||
None => Resp::<O>::new(output),
|
||||
};
|
||||
state.save_headers(response.status(), headers);
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
macro_rules! fixture_operations {
|
||||
($($operation:ident => $method:ident),+ $(,)?) => {
|
||||
$(impl Handler<dto::$operation> for FakeBackend {
|
||||
async fn call(&self, request: Req<dto::$operation>) -> HandlerResult<dto::$operation> {
|
||||
let (state, request) = target_request(request)?;
|
||||
target_response::<dto::$operation>(&state, self.$method(request).await)
|
||||
}
|
||||
})+
|
||||
|
||||
fn register_operations(builder: ServiceBuilder, backend: &Arc<FakeBackend>) -> ServiceBuilder {
|
||||
builder$(.register::<dto::$operation, _>(Arc::clone(backend)))+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fixture_operations! {
|
||||
HeadBucket => head_bucket,
|
||||
GetBucketVersioning => get_bucket_versioning,
|
||||
GetObjectLockConfiguration => get_object_lock_configuration,
|
||||
ListObjectsV2 => list_objects_v2,
|
||||
ListObjectVersions => list_object_versions,
|
||||
PutObject => put_object,
|
||||
GetObject => get_object,
|
||||
HeadObject => head_object,
|
||||
GetObjectTagging => get_object_tagging,
|
||||
PutObjectTagging => put_object_tagging,
|
||||
DeleteObjectTagging => delete_object_tagging,
|
||||
GetObjectRetention => get_object_retention,
|
||||
PutObjectRetention => put_object_retention,
|
||||
GetObjectLegalHold => get_object_legal_hold,
|
||||
PutObjectLegalHold => put_object_legal_hold,
|
||||
DeleteObject => delete_object,
|
||||
CreateMultipartUpload => create_multipart_upload,
|
||||
UploadPart => upload_part,
|
||||
AbortMultipartUpload => abort_multipart_upload,
|
||||
}
|
||||
|
||||
impl Handler<dto::CompleteMultipartUpload> for FakeBackend {
|
||||
async fn call(&self, request: Req<dto::CompleteMultipartUpload>) -> HandlerResult<dto::CompleteMultipartUpload> {
|
||||
let (state, request) = target_request(request)?;
|
||||
target_response::<dto::CompleteMultipartUpload>(&state, self.complete_multipart_upload(request).await)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn build(backend: FakeBackend, access: FaultAccess) -> Result<S3Service, BoxError> {
|
||||
let credentials = Credentials::new(FAKE_ACCESS_KEY, FAKE_SECRET_KEY.as_bytes())?;
|
||||
let authenticator =
|
||||
SigV4Authenticator::new(Arc::new(StaticCredentials::new().with(credentials)), RegionSet::new(["us-east-1"])?);
|
||||
// The target bounds the body reader and the entire request itself. A scripted delay or
|
||||
// slow drain must reach that bound without the gateway timing it out earlier.
|
||||
let config = ServiceConfig::new(MAX_BUFFERED_BODY_BYTES as u64)
|
||||
.with_handler_deadlines(HandlerDeadlineConfig::new(MAX_REQUEST_DURATION, MAX_REQUEST_DURATION)?)
|
||||
.with_request_body_deadlines(
|
||||
RequestBodyDeadlineConfig::S3
|
||||
.without_idle_deadlines()
|
||||
.without_throughput_floor(),
|
||||
);
|
||||
let (builder, _) = ServiceBuilder::new()
|
||||
.rustfs_profile()
|
||||
.authenticate_before_rejecting_unframed_upload_trailers()
|
||||
.config(config);
|
||||
let backend = Arc::new(backend);
|
||||
let service = register_operations(builder, &backend)
|
||||
.sse_config(SseConfig::allowing_customer_keys_over_plaintext(
|
||||
PlaintextCustomerKeyAck::i_understand_customer_keys_will_be_sent_in_the_clear(),
|
||||
))
|
||||
.authenticator(authenticator.rustfs_profile())
|
||||
.authorizer(access)
|
||||
.register_with_decode_error_mapping::<dto::CompleteMultipartUpload, _>(
|
||||
backend,
|
||||
CodecError::malformed_xml("the body omits a member the schema requires").about("PartNumber"),
|
||||
CodecError::new(ErrorCode::INVALID_PART, "part number is missing"),
|
||||
)
|
||||
.build()?;
|
||||
Ok(service)
|
||||
}
|
||||
@@ -114,7 +114,7 @@ async fn select_projects_encryption_headers_and_rejects_invalid_sse_c_before_str
|
||||
let log_path = format!("{}/server.log", kms.base_env.temp_dir);
|
||||
kms.base_env.capture_log_path = Some(log_path.clone());
|
||||
kms.base_env
|
||||
.start_rustfs_server_with_env(Vec::new(), &[("RUST_LOG", "rustfs_gateway=debug,rustfs=info")])
|
||||
.start_rustfs_server_with_env(Vec::new(), &[("RUST_LOG", "s3s=debug,rustfs=info")])
|
||||
.await?;
|
||||
let key_id = kms.configure_local_kms().await?;
|
||||
start_kms(&kms.base_env.url, &kms.base_env.access_key, &kms.base_env.secret_key).await?;
|
||||
|
||||
@@ -12,8 +12,6 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
mod access_request_validation_test;
|
||||
|
||||
#[cfg(test)]
|
||||
mod storage_metric_ownership_test;
|
||||
|
||||
@@ -107,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;
|
||||
|
||||
@@ -269,54 +269,6 @@ fn encode_signed_aws_chunked(signer: &SigV4, headers: &SignedHeaders, decoded: &
|
||||
encoded
|
||||
}
|
||||
|
||||
async fn assert_signature_refusal_preserves_part(
|
||||
client: &aws_sdk_s3::Client,
|
||||
key: &str,
|
||||
upload_id: &str,
|
||||
overwrite: reqwest::RequestBuilder,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let original = b"abc";
|
||||
let uploaded = client
|
||||
.upload_part()
|
||||
.bucket(BUCKET)
|
||||
.key(key)
|
||||
.upload_id(upload_id)
|
||||
.part_number(1)
|
||||
.body(aws_sdk_s3::primitives::ByteStream::from_static(original))
|
||||
.send()
|
||||
.await?;
|
||||
let etag = uploaded.e_tag().ok_or("successful UploadPart omitted ETag")?;
|
||||
assert_eq!(etag.trim_matches('"'), "900150983cd24fb0d6963f7d28e17f72");
|
||||
|
||||
let response = overwrite.send().await?;
|
||||
assert_eq!(response.status().as_u16(), 403);
|
||||
assert_error_code(&response.text().await?, "SignatureDoesNotMatch");
|
||||
|
||||
let listed = client
|
||||
.list_parts()
|
||||
.bucket(BUCKET)
|
||||
.key(key)
|
||||
.upload_id(upload_id)
|
||||
.send()
|
||||
.await?;
|
||||
let [part] = listed.parts() else {
|
||||
panic!("the original part must be the only listed part");
|
||||
};
|
||||
assert_eq!((part.part_number(), part.size(), part.e_tag()), (Some(1), Some(3), Some(etag)));
|
||||
let part = aws_sdk_s3::types::CompletedPart::builder().part_number(1).e_tag(etag).build();
|
||||
client
|
||||
.complete_multipart_upload()
|
||||
.bucket(BUCKET)
|
||||
.key(key)
|
||||
.upload_id(upload_id)
|
||||
.multipart_upload(aws_sdk_s3::types::CompletedMultipartUpload::builder().parts(part).build())
|
||||
.send()
|
||||
.await?;
|
||||
let object = client.get_object().bucket(BUCKET).key(key).send().await?;
|
||||
assert_eq!(object.body.collect().await?.into_bytes().as_ref(), original);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Exercise decoder failures through both storage publication boundaries.
|
||||
#[tokio::test]
|
||||
async fn aws_chunked_named_errors_reject_put_and_upload_part() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
@@ -419,10 +371,11 @@ async fn aws_chunked_named_errors_reject_put_and_upload_part() -> Result<(), Box
|
||||
for (name, value) in extra {
|
||||
request = request.header(name, value);
|
||||
}
|
||||
let request = request.body(encoded).timeout(std::time::Duration::from_secs(20));
|
||||
let overwrite = (multipart && matches!(case, "signature" | "final-signature"))
|
||||
.then(|| request.try_clone().expect("the request body is held in memory"));
|
||||
let response = request.send().await?;
|
||||
let response = request
|
||||
.body(encoded)
|
||||
.timeout(std::time::Duration::from_secs(20))
|
||||
.send()
|
||||
.await?;
|
||||
let status = response.status().as_u16();
|
||||
let body = response.text().await?;
|
||||
eprintln!("aws-chunked {case} multipart={multipart}: HTTP {status}, {body}");
|
||||
@@ -441,21 +394,9 @@ async fn aws_chunked_named_errors_reject_put_and_upload_part() -> Result<(), Box
|
||||
failures.push(format!("{case}: response exposed {private}"));
|
||||
}
|
||||
}
|
||||
let absent = client
|
||||
.get_object()
|
||||
.bucket(BUCKET)
|
||||
.key(&key)
|
||||
.send()
|
||||
.await
|
||||
.expect_err("a rejected body must not publish an object");
|
||||
assert_eq!(absent.as_service_error().and_then(ProvideErrorMetadata::code), Some("NoSuchKey"));
|
||||
if let Some(id) = upload_id {
|
||||
let parts = client.list_parts().bucket(BUCKET).key(&key).upload_id(&id).send().await?;
|
||||
assert!(parts.parts().is_empty(), "{case}: rejected UploadPart published a part");
|
||||
if let Some(overwrite) = overwrite {
|
||||
assert_signature_refusal_preserves_part(&client, &key, &id, overwrite).await?;
|
||||
continue;
|
||||
}
|
||||
client
|
||||
.abort_multipart_upload()
|
||||
.bucket(BUCKET)
|
||||
@@ -464,6 +405,14 @@ async fn aws_chunked_named_errors_reject_put_and_upload_part() -> Result<(), Box
|
||||
.send()
|
||||
.await?;
|
||||
}
|
||||
let absent = client
|
||||
.get_object()
|
||||
.bucket(BUCKET)
|
||||
.key(&key)
|
||||
.send()
|
||||
.await
|
||||
.expect_err("a rejected body must not publish an object");
|
||||
assert_eq!(absent.as_service_error().and_then(ProvideErrorMetadata::code), Some("NoSuchKey"));
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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(), ¤t),
|
||||
(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(¤t), 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(), ¤t_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);
|
||||
}
|
||||
}
|
||||
@@ -1631,8 +1631,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 +1784,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(),
|
||||
};
|
||||
@@ -1876,9 +1873,28 @@ 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.as_ref()
|
||||
&& permit.is_for(&self.io_admission)
|
||||
{
|
||||
return Ok(Some(permit.clone()));
|
||||
}
|
||||
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 context
|
||||
.background_permit(&self.io_admission)
|
||||
.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 +1991,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 +2466,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 +2482,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 +2490,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 +2504,6 @@ impl LocalDiskWrapper {
|
||||
journal,
|
||||
namespace_owner,
|
||||
work_budget,
|
||||
published_state,
|
||||
)
|
||||
.await
|
||||
})
|
||||
@@ -2987,7 +2988,6 @@ impl DiskAPI for LocalDiskWrapper {
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<()> {
|
||||
self.retired.cancel();
|
||||
self.stop_monitoring().await;
|
||||
self.disk.close().await
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,21 +294,6 @@ 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
|
||||
@@ -316,23 +301,19 @@ fn clone_context_with_current_resource_unit(context: &DiskIoContext) -> DiskIoCo
|
||||
/// 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
|
||||
.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
|
||||
})
|
||||
})
|
||||
.ok()
|
||||
.flatten();
|
||||
let context = current_disk_io_context()
|
||||
.filter(|context| context.admission.is_none() && context.permit.is_none())
|
||||
.map(|mut 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
|
||||
});
|
||||
async move {
|
||||
match context {
|
||||
Some(context) => with_disk_io_context(context, future).await,
|
||||
@@ -342,74 +323,34 @@ pub(crate) fn with_detached_disk_io_context<F: Future>(future: F) -> impl Future
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
DISK_IO_CONTEXT
|
||||
.try_with(|context| {
|
||||
let mut context = context.clone();
|
||||
if let Ok(unit) = RESOURCE_IO_UNIT.try_with(Clone::clone) {
|
||||
context.resource_unit = Some(unit);
|
||||
}
|
||||
context
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// 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.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(permit) = context.permit.as_ref()
|
||||
&& permit.is_for(admission)
|
||||
{
|
||||
return Ok(Some(permit.clone()));
|
||||
}
|
||||
match context.class {
|
||||
DiskIoClass::Foreground => Ok(Some(admission.foreground())),
|
||||
DiskIoClass::Background => Ok(Some(context.background_permit(admission).await?)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1332,124 +1273,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;
|
||||
}
|
||||
}
|
||||
|
||||
+164
-846
File diff suppressed because it is too large
Load Diff
@@ -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
@@ -121,7 +121,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 +241,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 +347,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 +451,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 +461,6 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn try_finish_and_finalize_prepared_delete_local(
|
||||
&self,
|
||||
volume: &str,
|
||||
@@ -494,7 +469,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 +479,6 @@ impl Disk {
|
||||
journal,
|
||||
namespace_owner,
|
||||
work_budget,
|
||||
published_state,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -1489,15 +1462,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 +1585,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,
|
||||
|
||||
+23
-110
@@ -428,24 +428,6 @@ pub(crate) mod prepared_publication_test_hooks {
|
||||
}
|
||||
}
|
||||
|
||||
#[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
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
type RenameDestinationHook = Box<dyn FnOnce(&Path) + Send>;
|
||||
#[cfg(test)]
|
||||
@@ -2689,7 +2671,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 +2869,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 +2971,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 +3271,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 +3283,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 +3322,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 +5308,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 +5670,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 +5686,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 +12583,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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -8339,70 +8339,6 @@ mod tests {
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn rename_fanout_falls_back_once_per_slot_when_old_peer_rejects_batch() {
|
||||
use crate::cluster::rpc::remote_disk::RenameBatchFallbackPeer;
|
||||
|
||||
crate::runtime::sources::ensure_test_rpc_secret();
|
||||
let peer = RenameBatchFallbackPeer::spawn().await;
|
||||
|
||||
temp_env::async_with_vars([("RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH", Some("true"))], async {
|
||||
let mut disks = Vec::new();
|
||||
for slot in 0..4 {
|
||||
let mut endpoint =
|
||||
Endpoint::try_from(format!("{}/data/rustfs{slot}", peer.addr()).as_str()).expect("rename fallback endpoint");
|
||||
endpoint.is_local = false;
|
||||
disks.push(Some(
|
||||
new_disk(
|
||||
&endpoint,
|
||||
&DiskOption {
|
||||
cleanup: false,
|
||||
health_check: false,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("rename fallback remote disk"),
|
||||
));
|
||||
}
|
||||
assert_eq!(peer.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
|
||||
let mut file_info = metadata_test_fileinfo("object");
|
||||
file_info.erasure.index = 0;
|
||||
let commit = SetDisks::rename_data_owned(
|
||||
&disks,
|
||||
(RUSTFS_META_TMP_BUCKET, "source"),
|
||||
vec![file_info; disks.len()],
|
||||
("bucket", "object"),
|
||||
disks.len(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.expect("unary fallback must satisfy every rename slot");
|
||||
|
||||
assert_eq!(peer.batch_calls(), 1, "one peer group makes one batch attempt");
|
||||
let mut expected_disks = disks
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|disk| disk.endpoint().to_string())
|
||||
.collect::<Vec<_>>();
|
||||
expected_disks.sort();
|
||||
let mut batch_disks = peer.batch_disks();
|
||||
batch_disks.sort();
|
||||
assert_eq!(batch_disks, expected_disks, "the rejected batch must cover every planned slot");
|
||||
let mut unary_disks = peer.unary_disks();
|
||||
unary_disks.sort();
|
||||
assert_eq!(unary_disks, expected_disks, "each slot falls back to unary exactly once");
|
||||
assert_eq!(commit.online_disks.iter().filter(|disk| disk.is_some()).count(), disks.len());
|
||||
assert_eq!(commit.convergence, RenameConvergence::AllSuccessIdentical);
|
||||
assert_eq!(peer.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
})
|
||||
.await;
|
||||
|
||||
rustfs_protos::evict_failed_connection(peer.addr()).await;
|
||||
peer.stop().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn rename_fanout_plan_batches_only_multi_slot_ordinary_peers() {
|
||||
|
||||
@@ -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,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user