mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-24 01:06:15 +00:00
Compare commits
250 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 371c20015e | |||
| e9834f1ff4 | |||
| 9b751a463c | |||
| 17946efa94 | |||
| 15ea736b85 | |||
| f0df8fbce5 | |||
| 006243f514 | |||
| bca8a1034f | |||
| d4997b00bc | |||
| ac5f274a71 | |||
| a1af0a9a48 | |||
| 60ad730526 | |||
| 3b5bd38d89 | |||
| 4d7c7d163d | |||
| 8dd39fc967 | |||
| 818c0dab99 | |||
| 54a6a1ac60 | |||
| 98610aa386 | |||
| 9b865db756 | |||
| 86c5014ba9 | |||
| c099a043f0 | |||
| 63cb0b904a | |||
| 8efefba4ba | |||
| 88a5d624d0 | |||
| af96a01862 | |||
| 5add21b1b1 | |||
| 933ff7c080 | |||
| 1bffaf2858 | |||
| b48b6fce8d | |||
| 02741e8451 | |||
| 3b67cbf0a9 | |||
| ae4f41658e | |||
| b85c7a7ba0 | |||
| d1cdfe6560 | |||
| a73a3db6f6 | |||
| c85ecca8ba | |||
| 1bdd6d9439 | |||
| 0635762266 | |||
| 936734f0f9 | |||
| f6fcb40b25 | |||
| b2a60aa9b6 | |||
| a8645d6541 | |||
| 133324a388 | |||
| 7b646119ea | |||
| 721e54744a | |||
| fee0240c39 | |||
| 6cfee51762 | |||
| 4e04393c31 | |||
| c437bcd1bd | |||
| c965d7dfff | |||
| cbaa8e1de1 | |||
| ccb9ace687 | |||
| 33a4015401 | |||
| 02858d861e | |||
| 55c1c35d66 | |||
| efa0cac5dd | |||
| dc12dbb259 | |||
| 5d846ca6d4 | |||
| 22d4359e07 | |||
| 8398f17035 | |||
| 25df27a41b | |||
| dec467da27 | |||
| 4b23847a75 | |||
| 23405ff83a | |||
| 77107f62f3 | |||
| 63e58d3c18 | |||
| 6a7761cdb6 | |||
| 929582bc43 | |||
| a1b4f29cc8 | |||
| 5e6f57c118 | |||
| 391e239711 | |||
| db721d9bb1 | |||
| 7125b37129 | |||
| 6cb0e6971b | |||
| 41f11d030d | |||
| 69514b18de | |||
| c25d41a798 | |||
| c66b0b4870 | |||
| c0795fa4e8 | |||
| 95ea979811 | |||
| 00a3abd6ef | |||
| 0ebd1f14ca | |||
| 18f5090671 | |||
| cd94ed59c5 | |||
| c58890f199 | |||
| 526dd58f6d | |||
| 35a6de6eb5 | |||
| 0649e80b62 | |||
| f413a76f54 | |||
| 65d0a9118c | |||
| 963e68ed30 | |||
| 5532994cf7 | |||
| 93bda3c9fc | |||
| 23ebd00068 | |||
| 7d0f38462d | |||
| 90443cf3cb | |||
| 9d5f34304b | |||
| 5b0b0d4fa7 | |||
| 18c4d007a6 | |||
| d67bdb83b3 | |||
| 918d6819fa | |||
| 1352dc81d8 | |||
| 6c507ca600 | |||
| fe6497bd76 | |||
| 5913301e45 | |||
| 9120a28da1 | |||
| 32c762420f | |||
| 2c00909e91 | |||
| e80f64cac2 | |||
| e7248f2801 | |||
| 45e7c91cd4 | |||
| 4a3088d752 | |||
| 2fa5ead608 | |||
| 393b847e21 | |||
| 49358e8829 | |||
| 5f56f9d5de | |||
| 4bd570a40e | |||
| e7f831a26e | |||
| dfe4a0506e | |||
| c4cab97dde | |||
| 82988adc7d | |||
| e48b3a4e0c | |||
| c02ac79a68 | |||
| 2fbb1f7585 | |||
| ac83905ebb | |||
| 49db44d177 | |||
| 58b6b7285c | |||
| cc4aee70a0 | |||
| 2cc25bcb25 | |||
| b19c06f4de | |||
| 6d115aaec9 | |||
| 1df7c9bd15 | |||
| 964afcb0df | |||
| 8c9fc97ae6 | |||
| ec8f72b1cf | |||
| 7a294eff86 | |||
| 1b2615cdb5 | |||
| 05446be442 | |||
| 3beac86c02 | |||
| 8c3cf46acc | |||
| 6988310d21 | |||
| 163051a3ba | |||
| f75453e123 | |||
| 2f9c531e59 | |||
| a05a735e36 | |||
| 6632490a32 | |||
| 6256ea500e | |||
| 40eea75614 | |||
| 357c308ee1 | |||
| 680f2f9356 | |||
| 7347770cdf | |||
| 7a0bec3985 | |||
| a2e0d6c997 | |||
| d4a5f8aeb6 | |||
| f1e2b52344 | |||
| 36d81605ec | |||
| 7a13629e37 | |||
| a0895971cd | |||
| 3ac7d5cf4c | |||
| 38d1714eda | |||
| c700b33bfc | |||
| 3b6591a286 | |||
| e5035df7a1 | |||
| 9b6d60e934 | |||
| bb94ec983b | |||
| 6a1b92b783 | |||
| e6435510f8 | |||
| 818a6b6a14 | |||
| 67d306b0de | |||
| a6f881b42d | |||
| dba23c4f55 | |||
| 5696c6f759 | |||
| 0d17f5f713 | |||
| e09df1f7cd | |||
| c5c65e112e | |||
| dfa3d7a2cd | |||
| 578025149b | |||
| bfc51cf3da | |||
| 7c3732799e | |||
| adad36dc3b | |||
| 83afcf52f7 | |||
| bb044df449 | |||
| 3565ae1ddf | |||
| cce3b0873d | |||
| 6bb25182c9 | |||
| ceb8f49aae | |||
| 78b35c3ea8 | |||
| 33aae31cb7 | |||
| f8924deb68 | |||
| 9e8c426e6f | |||
| 9815b67c51 | |||
| 496a34a6a7 | |||
| 7c9ebadffe | |||
| e376e7d774 | |||
| d211df88d5 | |||
| 21caf8bf34 | |||
| d3eaaa21a6 | |||
| ad457a2d1c | |||
| fa3ea5b4e5 | |||
| f3396952b6 | |||
| 8736b49d08 | |||
| eec468e488 | |||
| f2af45ee68 | |||
| 25b55febc5 | |||
| c2e50b3b10 | |||
| 6fde592da1 | |||
| 98259d7c46 | |||
| b5a35fc2c7 | |||
| 11a7572bba | |||
| 4c4dc84671 | |||
| 52986eefd5 | |||
| 7a5ffcfee7 | |||
| 334d615a67 | |||
| 0c813e1a9e | |||
| 0de0b85374 | |||
| 78f78ce5ee | |||
| 82ad3f0007 | |||
| 82f094f4d5 | |||
| e1df1d569b | |||
| 19487a6e34 | |||
| 6177fc280f | |||
| 14db51bba7 | |||
| 353de54fcc | |||
| 6a4f93bbaf | |||
| 74fab85ba0 | |||
| 44db2be5f9 | |||
| 3e41233589 | |||
| f36a771389 | |||
| 0447e68073 | |||
| 94dbca3840 | |||
| d2939fb43b | |||
| 9f7d1aa706 | |||
| 98675ddcbd | |||
| 357e78c523 | |||
| 411caa97d7 | |||
| 317e895096 | |||
| 7c55e265dd | |||
| f858a65f41 | |||
| f96c324734 | |||
| 7e5b3e4137 | |||
| c749351780 | |||
| 2381096448 | |||
| 99a1803773 | |||
| 5132be9c01 | |||
| 13399d98fa | |||
| ee3880ee84 | |||
| af48bb8539 | |||
| 850d7a2beb | |||
| 1acf30910f | |||
| 26757d5d5e |
@@ -1,2 +1,2 @@
|
||||
sha256-linux=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
|
||||
sha256-darwin=348fa5eed9ae58962c06b33283ff4f15122cff97bce9b4eb1e3ffcb227264b0b
|
||||
sha256-linux=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
|
||||
sha256-darwin=983efba6508e684db29bbdb923485fcc1c4fb312fc47fe101f7f27620906978b
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
sha256-darwin=9ccb03f4139e99ec11a63810523d504df39191b86e74b28a72dd9a075682293b
|
||||
sha256-linux=5ef052b03a03afbd00ebfcbbdcb754bbde414b7e6151aae3e2ee78024ce1d0b6
|
||||
sha256-darwin=d5f2a266740f695cf6734965a4d25b390e669aaaa2fc87805c45e42de83f13ca
|
||||
sha256-linux=448ac2ebd537def9f2a63b8961d80a6521f7ef05f952834ec997faed52bfb901
|
||||
|
||||
@@ -1 +1 @@
|
||||
sha256=fd5683273bba1eae3b4402a4e854a5d168ace845bd0e5fc801f8e336485a4394
|
||||
sha256=a304838fe8ded98a781d7e2e1cf5b22a5cbc11ddfdc4fbaeea91149e5f88d699
|
||||
|
||||
@@ -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_/)'
|
||||
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
|
||||
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_/)'
|
||||
filter = 'package(rustfs) & test(/^admin::handlers::site_replication::(tests::durable_iam_state_|removal_tests::decommission_durable_)/)'
|
||||
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(/^(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(/^(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(/^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,10 +960,11 @@ 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::/)
|
||||
& !test(/^(protocols|access_request_validation_test)::/)
|
||||
& !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=33
|
||||
s3_error_lines=89
|
||||
files=6
|
||||
s3_error_lines=16
|
||||
ecstore_files=0
|
||||
|
||||
@@ -57,6 +57,7 @@ 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,8 +6,9 @@ runs:
|
||||
- name: Install runtime tools
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libssl-dev ripgrep
|
||||
# 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
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 # stable
|
||||
- name: Install cargo-nextest
|
||||
|
||||
@@ -22,6 +22,8 @@ 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,6 +523,30 @@
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
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 --all-targets --features rio-v2
|
||||
cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --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 --all-targets --features rio-v2 -- -D warnings
|
||||
run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --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 --features rio-v2 \
|
||||
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \
|
||||
2>&1 | tee artifacts/workspace/nextest.log
|
||||
cargo test -p rustfs --doc --features rio-v2
|
||||
|
||||
@@ -1370,15 +1370,6 @@ 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
|
||||
@@ -1420,7 +1411,6 @@ 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,10 +1,7 @@
|
||||
name: S3-over-RDMA feature check
|
||||
|
||||
# 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.
|
||||
# Compile the optional RDMA features independently. The cuObject tests link
|
||||
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
|
||||
# Not a required check and not part of the `Test and Lint` aggregate.
|
||||
|
||||
on:
|
||||
@@ -12,6 +9,7 @@ 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"
|
||||
@@ -70,9 +68,42 @@ 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]
|
||||
needs: [nixl-check, cuobject-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,6 +80,18 @@ 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`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, TLS, and security contracts. |
|
||||
| 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. |
|
||||
| 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,6 +46,8 @@ 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.
|
||||
@@ -116,6 +118,7 @@ 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
+330
-219
File diff suppressed because it is too large
Load Diff
+35
-36
@@ -23,6 +23,7 @@ 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
|
||||
@@ -60,6 +61,7 @@ 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
|
||||
@@ -108,6 +110,7 @@ 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" }
|
||||
@@ -140,6 +143,7 @@ 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" }
|
||||
@@ -148,20 +152,17 @@ 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" }
|
||||
|
||||
# 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 }
|
||||
# Pin the gateway and its protocol crates to the same revision.
|
||||
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "c0291e66ebd98be38e5addb3a32195d8aac1fe63", version = "0.42.0", default-features = false }
|
||||
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "c0291e66ebd98be38e5addb3a32195d8aac1fe63", 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 = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.66.0", default-features = false }
|
||||
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "c0291e66ebd98be38e5addb3a32195d8aac1fe63", 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 = "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 }
|
||||
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "c0291e66ebd98be38e5addb3a32195d8aac1fe63", default-features = false }
|
||||
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "c0291e66ebd98be38e5addb3a32195d8aac1fe63", version = "0.63.0", default-features = false }
|
||||
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "c0291e66ebd98be38e5addb3a32195d8aac1fe63", version = "0.13.0", default-features = false }
|
||||
|
||||
# Async Runtime and Networking
|
||||
async-channel = "2.5.0"
|
||||
@@ -175,9 +176,9 @@ futures = "0.3.34"
|
||||
futures-core = "0.3.34"
|
||||
futures-lite = "2.6.1"
|
||||
futures-util = "0.3.34"
|
||||
pollster = "1.0.2"
|
||||
pollster = "1.0.3"
|
||||
pulsar = { default-features = false, version = "=6.9.0" }
|
||||
lapin = { default-features = false, version = "4.12.3" }
|
||||
lapin = { default-features = false, version = "4.13.0" }
|
||||
hyper = { version = "1.12.0" }
|
||||
h2 = { version = "0.4.20" }
|
||||
hyper-rustls = { default-features = false, version = "0.27.10" }
|
||||
@@ -216,7 +217,7 @@ csv-core = "0.1.13"
|
||||
bytesize = "2.7.0"
|
||||
byteorder = "1.5.0"
|
||||
flatbuffers = "25.12.19"
|
||||
form_urlencoded = "1.2.2"
|
||||
form_urlencoded = "1.2.3"
|
||||
prost = "0.14.6"
|
||||
quick-xml = "0.42.0"
|
||||
rmp = { version = "0.8.15" }
|
||||
@@ -258,7 +259,7 @@ proptest = "1"
|
||||
# Time and Date
|
||||
chrono = { version = "0.4.45" }
|
||||
humantime = "2.4.0"
|
||||
jiff = { version = "1.0.1" }
|
||||
jiff = { version = "1.0.2" }
|
||||
time = { version = "0.3.55" }
|
||||
|
||||
# Database
|
||||
@@ -278,15 +279,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.160.0" }
|
||||
aws-sdk-sts = { default-features = false, version = "1.127.0" }
|
||||
aws-sdk-s3 = { default-features = false, version = "1.161.0" }
|
||||
aws-sdk-sts = { default-features = false, version = "1.128.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.8" }
|
||||
clap = { version = "4.6.9" }
|
||||
const-str = { version = "1.1.0" }
|
||||
convert_case = "0.12.0"
|
||||
criterion = { version = "0.8" }
|
||||
@@ -298,12 +299,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 = "1.0.0"
|
||||
faster-hex = "2.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.1" }
|
||||
hashbrown = { version = "0.17.2" }
|
||||
# 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"
|
||||
@@ -313,7 +314,8 @@ hostname = "0.4.2"
|
||||
ipnetwork = { version = "0.21.1" }
|
||||
lazy_static = "1.5.1"
|
||||
libc = "0.2.191"
|
||||
cuobject = { version = "0.1.0", default-features = false }
|
||||
cxx = "1"
|
||||
cxx-build = "1"
|
||||
libsystemd = "0.7.2"
|
||||
local-ip-address = "0.6.13"
|
||||
log = "0.4"
|
||||
@@ -337,7 +339,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.17"
|
||||
pin-project-lite = "0.2.18"
|
||||
pretty_assertions = "1.4.1"
|
||||
rand = { version = "0.10.4" }
|
||||
ratelimit = "2.0.0"
|
||||
@@ -351,16 +353,10 @@ 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.5" }
|
||||
smallvec = { version = "1.16.6" }
|
||||
compact_str = "0.10.0"
|
||||
snap = "1.1.2"
|
||||
starshard = { version = "2.4.1" }
|
||||
@@ -378,23 +374,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.8"
|
||||
url = "2.5.9"
|
||||
urlencoding = "2.1.3"
|
||||
uuid = { version = "1.29.3" }
|
||||
vaultrs = { version = "0.8.0" }
|
||||
tar = "0.4.46"
|
||||
walkdir = "2.5.0"
|
||||
walkdir = "2.5.1"
|
||||
winapi-util = "0.1.11"
|
||||
windows = { version = "0.62.2" }
|
||||
windows-sys = "0.61.2"
|
||||
xxhash-rust = { version = "0.8.21" }
|
||||
zip = "9.7.0"
|
||||
zip = "9.8.1"
|
||||
zstd = "0.14.4"
|
||||
|
||||
# Observability and Metrics
|
||||
metrics = "0.24.6"
|
||||
metrics-util = "0.20"
|
||||
dial9 = { version = "0.5.8", default-features = false }
|
||||
dial9 = { version = "0.5.9", default-features = false }
|
||||
opentelemetry = { version = "0.33.1" }
|
||||
opentelemetry-appender-tracing = { version = "0.33.1" }
|
||||
opentelemetry-otlp = { version = "0.33.1" }
|
||||
@@ -405,12 +401,12 @@ opentelemetry-stdout = { version = "0.33.1" }
|
||||
pyroscope = { version = "2.1.5" }
|
||||
|
||||
# FTP and SFTP
|
||||
libunftp = { version = "0.25.0" }
|
||||
libunftp = { version = "0.25.1" }
|
||||
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.2" }
|
||||
russh-sftp = "3.0.1"
|
||||
russh = { version = "0.65.4" }
|
||||
russh-sftp = "4.0.0"
|
||||
|
||||
# WebDAV
|
||||
dav-server = "0.12.0"
|
||||
@@ -423,7 +419,10 @@ hotpath = { version = "0.32.1", default-features = false }
|
||||
insta = { version = "1.49" }
|
||||
|
||||
[workspace.metadata.cargo-shear]
|
||||
ignored = ["hotpath", "rustfs"]
|
||||
# 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"]
|
||||
|
||||
[profile.dev]
|
||||
# Full debuginfo roughly doubles compile+link time and produces multi-GB
|
||||
|
||||
@@ -15,12 +15,11 @@ workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
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"]
|
||||
hotpath = ["rustfs-io-core/hotpath"]
|
||||
hotpath-alloc = ["hotpath", "rustfs-io-core/hotpath-alloc"]
|
||||
hotpath-cpu = ["hotpath", "rustfs-io-core/hotpath-cpu"]
|
||||
|
||||
[dependencies]
|
||||
hotpath.workspace = true
|
||||
# Internal crates
|
||||
rustfs-io-core = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
|
||||
@@ -129,6 +129,12 @@ when restoring `/rustfs/console` for a custom OEM build.
|
||||
- `RUSTFS_SCANNER_MAX_CONCURRENT_SET_SCANS` (canonical)
|
||||
- `RUSTFS_SCANNER_MAX_CONCURRENT_DISK_SCANS` (canonical)
|
||||
- `RUSTFS_SCANNER_WALKERS_PER_DISK` (canonical)
|
||||
- `RUSTFS_SCANNER_READ_ONLY_HANDOFF` (canonical, default `false`)
|
||||
|
||||
Read-only restart continuity:
|
||||
|
||||
- `RUSTFS_SCANNER_READ_ONLY_HANDOFF=true` enables reuse of unpublished scanner progress across verified read-only process restarts. Unset, false or invalid values disable both identity restoration and receipt creation. Existing receipts are still durably consumed before recovery starts, even when the feature is disabled.
|
||||
- Deploy receipt-aware readers to every possible writer before enabling this flag. Before rolling back to an older binary, disable it on every node, start each node with all its drives present, wait for readiness, and shut down cleanly. Do not start the older binary until every node completes this preparation. Direct rollback after enabling receipt writes is unsupported: older startup/recovery paths can write without durably invalidating the receipt. See [the receipt and rollback contract](../../docs/architecture/scanner-usage-publication.md#read-only-restart-continuity).
|
||||
|
||||
Scanner cycle budget controls:
|
||||
|
||||
|
||||
@@ -21,6 +21,11 @@ pub const APP_NAME: &str = "RustFS";
|
||||
/// Cargo package version for this workspace member.
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
|
||||
/// Defaults to false. Enable only after all possible writers support receipt
|
||||
/// consumption; disable and restart before rolling back to an older writer.
|
||||
pub const ENV_SCANNER_READ_ONLY_HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
|
||||
|
||||
/// Default configuration logger level
|
||||
/// Default value: error
|
||||
/// Environment variable: RUSTFS_OBS_LOGGER_LEVEL
|
||||
|
||||
@@ -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).
|
||||
/// Used for: the s3s streaming-body limit and the request-header admission check.
|
||||
/// Enforced on the upload body and at request-header admission.
|
||||
/// 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,6 +32,9 @@ 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,10 +349,8 @@ 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";
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
pub const INTERNODE_DATA_TRANSPORT_NIXL: &str = "nixl";
|
||||
|
||||
/// Known internode transport backend names accepted by the config parser.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
[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"]
|
||||
@@ -0,0 +1,41 @@
|
||||
// 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");
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// 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}; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// 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::*;
|
||||
@@ -0,0 +1,149 @@
|
||||
// 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 }
|
||||
cuobject = { workspace = true, default-features = false, optional = true }
|
||||
rustfs-cuobject-sys = { workspace = true, features = ["server"], 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:cuobject", "cuobject/server", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
|
||||
server = ["dep:bytes", "dep:rustfs-cuobject-sys", "dep:parking_lot", "dep:thiserror", "dep:tokio"]
|
||||
|
||||
+652
-226
File diff suppressed because it is too large
Load Diff
@@ -1235,23 +1235,66 @@ 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", &self.children)?;
|
||||
state.serialize_entry("children", 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", &self.replication_stats)?;
|
||||
state.serialize_entry("replication_stats", replication)?;
|
||||
state.serialize_entry("compacted", &self.compacted)?;
|
||||
state.serialize_entry("failed_objects", &self.failed_objects)?;
|
||||
state.serialize_entry("all_tier_stats", &self.all_tier_stats)?;
|
||||
state.serialize_entry("all_tier_stats", tiers)?;
|
||||
// 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() {
|
||||
@@ -2534,6 +2577,32 @@ 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(
|
||||
|
||||
@@ -13,7 +13,9 @@
|
||||
// limitations under the License.
|
||||
|
||||
pub mod data_usage;
|
||||
pub mod scan_progress;
|
||||
pub mod usage_observation;
|
||||
|
||||
pub use data_usage::*;
|
||||
pub use scan_progress::*;
|
||||
pub use usage_observation::*;
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
//! Display-only scanner progress. These values never authorize quota admission,
|
||||
//! cache reuse, or publication of a certified usage snapshot.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub const BUCKET_SCAN_PROGRESS_VERSION: u16 = 1;
|
||||
pub const BUCKET_SCAN_PROGRESS_MAX_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// The object lives on its contributing erasure set, alongside its bucket cache.
|
||||
pub fn bucket_scan_progress_path(bucket: &str) -> String {
|
||||
format!("buckets/{bucket}/.usage-progress.json")
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum BucketScanStage {
|
||||
Enumerating,
|
||||
Scanning,
|
||||
AwaitingSources,
|
||||
Completed,
|
||||
}
|
||||
|
||||
/// One replaceable sample from a logical erasure set, never a per-disk delta.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct BucketScanProgressSource {
|
||||
pub version: u16,
|
||||
pub bucket: String,
|
||||
pub bucket_incarnation: String,
|
||||
pub pool_index: u64,
|
||||
pub set_index: u64,
|
||||
pub set_layout: [u8; 32],
|
||||
pub publication_epoch: u64,
|
||||
/// Shared durable movement scope. A writer's local admission epoch is not
|
||||
/// comparable to another node's counter, including after restart.
|
||||
#[serde(default)]
|
||||
pub movement_generation: Option<u64>,
|
||||
pub scanner_epoch: u64,
|
||||
pub scanner_cycle: u64,
|
||||
/// Unix milliseconds of the sample, preserved when an older sample is carried.
|
||||
pub updated_at: u64,
|
||||
pub stage: BucketScanStage,
|
||||
/// Accepted logical object usage; enumeration alone leaves both absent.
|
||||
pub objects: Option<u64>,
|
||||
pub size: Option<u64>,
|
||||
}
|
||||
|
||||
/// Response-only progress, deliberately separate from a bucket's total usage.
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub struct BucketScanProgress {
|
||||
pub stage: BucketScanStage,
|
||||
pub updated_at: u64,
|
||||
pub objects: Option<u64>,
|
||||
pub size: Option<u64>,
|
||||
pub sources_observed: u64,
|
||||
pub sources_total: u64,
|
||||
}
|
||||
|
||||
impl BucketScanProgressSource {
|
||||
/// Bind a sample to shared storage scope, independently of reader-local epochs.
|
||||
pub fn matches(&self, bucket: &str, incarnation: &str, source: (u64, u64), movement_generation: u64) -> bool {
|
||||
self.version == BUCKET_SCAN_PROGRESS_VERSION
|
||||
&& self.bucket == bucket
|
||||
&& !incarnation.is_empty()
|
||||
&& incarnation != "00000000-0000-0000-0000-000000000000"
|
||||
&& self.bucket_incarnation == incarnation
|
||||
&& (self.pool_index, self.set_index) == source
|
||||
&& self.movement_generation == Some(movement_generation)
|
||||
&& self.updated_at > 0
|
||||
&& self.objects.is_some() == self.size.is_some()
|
||||
&& (self.stage != BucketScanStage::Completed || self.objects.is_some())
|
||||
&& self.stage != BucketScanStage::AwaitingSources
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold each logical source exactly once. Retries replace samples; replicas do
|
||||
/// not add to them. Missing sources remain explicit, including on first startup.
|
||||
/// Overflow or conflicting copies of a source make the view unavailable.
|
||||
/// Callers first bind each sample to the same current bucket and movement
|
||||
/// scope with [`BucketScanProgressSource::matches`].
|
||||
pub fn aggregate_bucket_scan_progress(
|
||||
sources: impl IntoIterator<Item = BucketScanProgressSource>,
|
||||
expected: &[(u64, u64)],
|
||||
) -> Option<BucketScanProgress> {
|
||||
if expected.is_empty() || expected.windows(2).any(|pair| pair[0] >= pair[1]) {
|
||||
return None;
|
||||
}
|
||||
let mut selected = BTreeMap::new();
|
||||
for sample in sources {
|
||||
let key = (sample.pool_index, sample.set_index);
|
||||
if expected.binary_search(&key).is_err() {
|
||||
return None;
|
||||
}
|
||||
if let Some(previous) = selected.insert(key, sample.clone())
|
||||
&& previous != sample
|
||||
{
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let updated_at = selected.values().map(|sample| sample.updated_at).min()?;
|
||||
let mut objects = None;
|
||||
let mut size = None;
|
||||
for sample in selected.values() {
|
||||
match (sample.objects, sample.size) {
|
||||
(Some(count), Some(bytes)) => {
|
||||
objects = Some(objects.unwrap_or(0_u64).checked_add(count)?);
|
||||
size = Some(size.unwrap_or(0_u64).checked_add(bytes)?);
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
let complete = selected.len() == expected.len() && selected.values().all(|s| s.stage == BucketScanStage::Completed);
|
||||
Some(BucketScanProgress {
|
||||
stage: if complete {
|
||||
BucketScanStage::Completed
|
||||
} else if selected.len() < expected.len() {
|
||||
BucketScanStage::AwaitingSources
|
||||
} else if objects.is_some() {
|
||||
BucketScanStage::Scanning
|
||||
} else {
|
||||
BucketScanStage::Enumerating
|
||||
},
|
||||
updated_at,
|
||||
objects,
|
||||
size,
|
||||
sources_observed: u64::try_from(selected.len()).ok()?,
|
||||
sources_total: u64::try_from(expected.len()).ok()?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample(set: u64) -> BucketScanProgressSource {
|
||||
BucketScanProgressSource {
|
||||
version: BUCKET_SCAN_PROGRESS_VERSION,
|
||||
bucket: "bucket".into(),
|
||||
bucket_incarnation: "identity".into(),
|
||||
pool_index: 0,
|
||||
set_index: set,
|
||||
set_layout: [1; 32],
|
||||
publication_epoch: 0,
|
||||
movement_generation: Some(0),
|
||||
scanner_epoch: 3,
|
||||
scanner_cycle: 4,
|
||||
updated_at: 1000,
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(77),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_source_samples_never_double_count() {
|
||||
let one = sample(0);
|
||||
let progress = aggregate_bucket_scan_progress([one.clone(), one], &[(0, 0), (0, 1)]).expect("partial progress");
|
||||
assert_eq!(progress.objects, Some(7));
|
||||
assert_eq!(progress.size, Some(77));
|
||||
assert_eq!(progress.stage, BucketScanStage::AwaitingSources);
|
||||
assert_eq!(progress.sources_observed, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enumeration_does_not_invent_empty_usage() {
|
||||
let mut one = sample(0);
|
||||
one.stage = BucketScanStage::Enumerating;
|
||||
one.objects = None;
|
||||
one.size = None;
|
||||
let progress = aggregate_bucket_scan_progress([one], &[(0, 0)]).expect("enumeration progress");
|
||||
assert_eq!(progress.objects, None);
|
||||
assert_eq!(progress.size, None);
|
||||
assert_eq!(progress.stage, BucketScanStage::Enumerating);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_requires_every_source_and_keeps_oldest_timestamp() {
|
||||
let mut one = sample(0);
|
||||
one.stage = BucketScanStage::Completed;
|
||||
let mut two = sample(1);
|
||||
two.updated_at = 2000;
|
||||
let pending = aggregate_bucket_scan_progress([one.clone(), two.clone()], &[(0, 0), (0, 1)]).expect("pending");
|
||||
assert_eq!(pending.stage, BucketScanStage::Scanning);
|
||||
two.stage = BucketScanStage::Completed;
|
||||
let done = aggregate_bucket_scan_progress([one, two], &[(0, 0), (0, 1)]).expect("completed");
|
||||
assert_eq!((done.objects, done.size, done.updated_at), (Some(14), Some(154), 1000));
|
||||
assert_eq!(done.stage, BucketScanStage::Completed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_replicas_overflow_and_foreign_sources_are_rejected() {
|
||||
let mut other = sample(0);
|
||||
other.objects = Some(8);
|
||||
assert!(aggregate_bucket_scan_progress([sample(0), other], &[(0, 0)]).is_none());
|
||||
assert!(aggregate_bucket_scan_progress([sample(1)], &[(0, 0)]).is_none());
|
||||
let mut huge = sample(1);
|
||||
huge.size = Some(u64::MAX);
|
||||
assert!(aggregate_bucket_scan_progress([sample(0), huge], &[(0, 0), (0, 1)]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_cannot_cross_bucket_incarnation_or_movement_generation() {
|
||||
let one = sample(0);
|
||||
assert!(one.matches("bucket", "identity", (0, 0), 0));
|
||||
assert!(!one.matches("bucket", "recreated", (0, 0), 0));
|
||||
assert!(!one.matches("bucket", "identity", (0, 1), 0));
|
||||
assert!(!one.matches("bucket", "identity", (0, 0), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_reader_local_epoch_does_not_hide_shared_sample() {
|
||||
let mut one = sample(0);
|
||||
one.publication_epoch = 7;
|
||||
assert!(one.matches("bucket", "identity", (0, 0), 0));
|
||||
one.movement_generation = None;
|
||||
assert!(!one.matches("bucket", "identity", (0, 0), 0), "missing shared scope stays unknown");
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,70 @@ 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,3 +321,110 @@ 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,8 +138,13 @@ 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 = { workspace = true, features = ["minio"] }
|
||||
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
|
||||
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"] }
|
||||
|
||||
@@ -0,0 +1,587 @@
|
||||
// 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,7 +34,10 @@
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
|
||||
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 hmac::{Hmac, KeyInit as _, Mac};
|
||||
use http::header::HOST;
|
||||
use rustfs_s3_types::Body;
|
||||
@@ -396,6 +399,54 @@ 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,8 +1035,7 @@ pub async fn execute_awscurl(
|
||||
|
||||
/// `POST` with SigV4 `--service sts` and explicit `Content-Type: application/x-www-form-urlencoded`.
|
||||
///
|
||||
/// 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`.
|
||||
/// RustFS uses this content type to recognize an STS query on `POST /`.
|
||||
pub async fn awscurl_post_sts_form_urlencoded(
|
||||
url: &str,
|
||||
body: &str,
|
||||
|
||||
@@ -21,23 +21,8 @@
|
||||
//! when it fails to parse (`amztime.ParseHeader` error is swallowed), so the copy
|
||||
//! proceeds.
|
||||
//!
|
||||
//! 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.
|
||||
//! 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.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -101,7 +86,7 @@ mod tests {
|
||||
|
||||
let copy_source = format!("/{bucket}/src.txt");
|
||||
|
||||
// A valid future HTTP-date is accepted by s3s and the copy succeeds.
|
||||
// A valid future HTTP-date allows the copy.
|
||||
let (status, body) = signed_copy(
|
||||
&env.url,
|
||||
&format!("/{bucket}/dst-valid.txt"),
|
||||
@@ -114,10 +99,7 @@ mod tests {
|
||||
assert_eq!(status, reqwest::StatusCode::OK, "valid copy-source date must succeed: {body}");
|
||||
assert!(body.contains("CopyObjectResult"), "expected CopyObjectResult XML: {body}");
|
||||
|
||||
// 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.
|
||||
// The signed header reaches the RustFS profile's conditional-date check unchanged.
|
||||
let (status, body) = signed_copy(
|
||||
&env.url,
|
||||
&format!("/{bucket}/dst-invalid.txt"),
|
||||
@@ -130,7 +112,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::BAD_REQUEST,
|
||||
"invalid copy-source date currently rejected by s3s (backlog#618): {body}"
|
||||
"expected the signed invalid date to be rejected (backlog#618): {body}"
|
||||
);
|
||||
assert!(body.contains("InvalidArgument"), "expected InvalidArgument for invalid date: {body}");
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ 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,6 +159,7 @@ 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}"))?;
|
||||
@@ -200,6 +201,24 @@ 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?;
|
||||
@@ -234,6 +253,38 @@ 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
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// 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 backed by `s3s`; no production crate depends on it.
|
||||
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.
|
||||
|
||||
`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.
|
||||
`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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// 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
@@ -0,0 +1,327 @@
|
||||
// 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(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
// 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(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
// 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", "s3s=debug,rustfs=info")])
|
||||
.start_rustfs_server_with_env(Vec::new(), &[("RUST_LOG", "rustfs_gateway=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,6 +12,8 @@
|
||||
// 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;
|
||||
|
||||
@@ -105,6 +107,9 @@ 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,6 +269,54 @@ 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>> {
|
||||
@@ -371,11 +419,10 @@ async fn aws_chunked_named_errors_reject_put_and_upload_part() -> Result<(), Box
|
||||
for (name, value) in extra {
|
||||
request = request.header(name, value);
|
||||
}
|
||||
let response = request
|
||||
.body(encoded)
|
||||
.timeout(std::time::Duration::from_secs(20))
|
||||
.send()
|
||||
.await?;
|
||||
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 status = response.status().as_u16();
|
||||
let body = response.text().await?;
|
||||
eprintln!("aws-chunked {case} multipart={multipart}: HTTP {status}, {body}");
|
||||
@@ -394,17 +441,6 @@ async fn aws_chunked_named_errors_reject_put_and_upload_part() -> Result<(), Box
|
||||
failures.push(format!("{case}: response exposed {private}"));
|
||||
}
|
||||
}
|
||||
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");
|
||||
client
|
||||
.abort_multipart_upload()
|
||||
.bucket(BUCKET)
|
||||
.key(&key)
|
||||
.upload_id(id)
|
||||
.send()
|
||||
.await?;
|
||||
}
|
||||
let absent = client
|
||||
.get_object()
|
||||
.bucket(BUCKET)
|
||||
@@ -413,6 +449,21 @@ async fn aws_chunked_named_errors_reject_put_and_upload_part() -> Result<(), Box
|
||||
.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)
|
||||
.key(&key)
|
||||
.upload_id(id)
|
||||
.send()
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||||
|
||||
@@ -864,6 +864,70 @@ 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]
|
||||
@@ -962,3 +1026,101 @@ 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};
|
||||
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment, admin_request, init_logging, local_http_client};
|
||||
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("--ignored")
|
||||
.arg("--include-ignored")
|
||||
.arg("--nocapture")
|
||||
.env(NAMESPACE_ENV, "1")
|
||||
.status()?;
|
||||
@@ -1524,6 +1524,110 @@ 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,12 +2075,18 @@ 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 replication_enabled: watch::Receiver<bool>,
|
||||
mut gate: ReplicationProxyGate,
|
||||
mut held_tagging: watch::Receiver<Option<String>>,
|
||||
mut response_hold: ReplicationResponseHoldRuntime,
|
||||
) -> Response<Full<bytes::Bytes>> {
|
||||
@@ -2091,8 +2097,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 !*replication_enabled.borrow() {
|
||||
if replication_enabled.changed().await.is_err() {
|
||||
while !*gate.enabled.borrow() {
|
||||
if gate.enabled.changed().await.is_err() {
|
||||
return proxy_error_response("replication gate closed");
|
||||
}
|
||||
}
|
||||
@@ -2117,6 +2123,12 @@ 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);
|
||||
@@ -2153,7 +2165,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).await?;
|
||||
start_replication_counting_proxy_with_tag_hold(backend_url, tasks, None).await?;
|
||||
Ok((proxy_url, request_count, replication_enabled))
|
||||
}
|
||||
|
||||
@@ -2161,9 +2173,11 @@ 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,
|
||||
@@ -2180,6 +2194,10 @@ 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 {
|
||||
@@ -2192,7 +2210,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 replication_enabled = task_replication_enabled.clone();
|
||||
let gate = gate.clone();
|
||||
let held_tagging = task_held_tagging.clone();
|
||||
let response_hold = response_hold_runtime.clone();
|
||||
connections.spawn(async move {
|
||||
@@ -2200,7 +2218,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 replication_enabled = replication_enabled.clone();
|
||||
let gate = gate.clone();
|
||||
let held_tagging = held_tagging.clone();
|
||||
let response_hold = response_hold.clone();
|
||||
async move {
|
||||
@@ -2210,7 +2228,7 @@ async fn start_replication_counting_proxy_with_tag_hold(
|
||||
&backend_url,
|
||||
&client,
|
||||
&request_count,
|
||||
replication_enabled,
|
||||
gate,
|
||||
held_tagging,
|
||||
response_hold,
|
||||
)
|
||||
@@ -2252,6 +2270,309 @@ 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,
|
||||
@@ -8222,7 +8543,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).await?;
|
||||
) = start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
|
||||
|
||||
let add_status = site_replication_add(
|
||||
&site_a_env,
|
||||
@@ -8479,9 +8800,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).await?;
|
||||
start_replication_counting_proxy_with_tag_hold(&site_a_env.url, &mut proxy_tasks, None).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).await?;
|
||||
start_replication_counting_proxy_with_tag_hold(&site_b_env.url, &mut proxy_tasks, None).await?;
|
||||
|
||||
let site_a_client = site_a_env.create_s3_client();
|
||||
let site_b_client = site_b_env.create_s3_client();
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use aws_sdk_s3::{Client, primitives::ByteStream};
|
||||
use futures::{StreamExt, TryStreamExt, stream};
|
||||
use rustfs_data_usage::{BucketUsageValueState, DataUsageInfo};
|
||||
use serde::{Deserialize, de::DeserializeOwned};
|
||||
use tokio::time::{Instant, sleep, timeout};
|
||||
|
||||
use crate::common::{RustFSTestEnvironment, signed_request};
|
||||
use crate::storage_api::scanner_peer_bucket::{BUCKET_META_PREFIX, RUSTFS_META_BUCKET};
|
||||
|
||||
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||
|
||||
const BUCKET: &str = "wide-directory-usage";
|
||||
const WIDTH: usize = 512;
|
||||
// The per-disk token bucket allows an initial burst of one second. Even the
|
||||
// first pass can read at most (1 + 3) * 96 = 384 of these 512 root entries.
|
||||
const SCAN_ENV: &[(&str, &str)] = &[
|
||||
("RUST_LOG", "warn,rustfs::scanner::io=debug,rustfs::scanner::data_usage=debug"),
|
||||
("RUSTFS_SCANNER_ENABLED", "true"),
|
||||
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
|
||||
("RUSTFS_SCANNER_CYCLE", "1"),
|
||||
("RUSTFS_SCANNER_CYCLE_MAX_DURATION_SECS", "3"),
|
||||
("RUSTFS_SCANNER_SPEED", "fastest"),
|
||||
("RUSTFS_SCANNER_DISK_IO_BUDGET_IOPS", "96"),
|
||||
("RUSTFS_SCANNER_DISK_IO_BUDGET_BYTES_PER_SEC", "off"),
|
||||
];
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Status {
|
||||
metrics: Metrics,
|
||||
disk_io_budget: Vec<DiskBudget>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Metrics {
|
||||
current_cycle_active: bool,
|
||||
active_paths: Vec<String>,
|
||||
cycle_max_duration_seconds: f64,
|
||||
partial_cycles_runtime: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct DiskBudget {
|
||||
iops: Option<u64>,
|
||||
}
|
||||
|
||||
async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str) -> TestResult<T> {
|
||||
let url = format!("{}/rustfs/admin/v3/{resource}", env.url);
|
||||
let response = signed_request(http::Method::GET, &url, &env.access_key, &env.secret_key, None, None).await?;
|
||||
Ok(response.error_for_status()?.json().await?)
|
||||
}
|
||||
|
||||
async fn inventory(client: &Client) -> TestResult<BTreeMap<String, u64>> {
|
||||
let mut pages = client.list_objects_v2().bucket(BUCKET).max_keys(37).into_paginator().send();
|
||||
let mut sizes = BTreeMap::new();
|
||||
while let Some(page) = pages.next().await {
|
||||
for object in page?.contents() {
|
||||
let key = object.key().ok_or("S3 inventory omitted object key")?;
|
||||
let size = u64::try_from(object.size().ok_or("S3 inventory omitted object size")?)?;
|
||||
assert!(sizes.insert(key.to_owned(), size).is_none(), "duplicate inventory key {key}");
|
||||
}
|
||||
}
|
||||
Ok(sizes)
|
||||
}
|
||||
|
||||
async fn scan_status(env: &RustFSTestEnvironment) -> TestResult<Status> {
|
||||
let status: Status = admin(env, "scanner/status").await?;
|
||||
assert_eq!(status.metrics.cycle_max_duration_seconds, 3.0, "effective cycle budget");
|
||||
assert!(status.disk_io_budget.iter().all(|disk| disk.iops == Some(96)), "effective disk budget");
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult {
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
let temporary_log = tempfile::NamedTempFile::new()?;
|
||||
let server_log = env
|
||||
.capture_log_path
|
||||
.get_or_insert_with(|| temporary_log.path().display().to_string())
|
||||
.clone();
|
||||
let bucket_metadata = Path::new(&env.temp_dir)
|
||||
.join(RUSTFS_META_BUCKET)
|
||||
.join(BUCKET_META_PREFIX)
|
||||
.join(BUCKET);
|
||||
// Seed a cold bucket without allowing any earlier, larger-budget sweep to count it.
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[("RUSTFS_SCANNER_ENABLED", "false")])
|
||||
.await?;
|
||||
let client = env.create_s3_client();
|
||||
client.create_bucket().bucket(BUCKET).send().await?;
|
||||
stream::iter(0..WIDTH)
|
||||
.map(Ok)
|
||||
.try_for_each_concurrent(12, |i| {
|
||||
let client = &client;
|
||||
async move {
|
||||
client
|
||||
.put_object()
|
||||
.bucket(BUCKET)
|
||||
.key(format!("object-{i:064x}"))
|
||||
.body(ByteStream::from(vec![42; 1 + i % 67]))
|
||||
.send()
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
let expected = inventory(&client).await?;
|
||||
assert_eq!(expected.len(), WIDTH);
|
||||
|
||||
env.restart_server_preserving_data(vec![], SCAN_ENV).await?;
|
||||
let first_pid = env.process.as_ref().ok_or("missing scanner process")?.id();
|
||||
timeout(Duration::from_secs(60), async {
|
||||
loop {
|
||||
let status = scan_status(&env).await?;
|
||||
if status.metrics.partial_cycles_runtime >= 1
|
||||
&& bucket_metadata.join(".usage-cache.bin").join("xl.meta").is_file()
|
||||
&& bucket_metadata.join(".usage-cache.bin.pages").is_dir()
|
||||
&& status.metrics.current_cycle_active
|
||||
&& status
|
||||
.metrics
|
||||
.active_paths
|
||||
.iter()
|
||||
.any(|path| path.split('/').any(|part| part == BUCKET))
|
||||
{
|
||||
let log = tokio::fs::read_to_string(&server_log).await?;
|
||||
if !log
|
||||
.lines()
|
||||
.any(|line| line.contains("partial_saved_not_published") && line.contains(BUCKET))
|
||||
{
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
|
||||
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
|
||||
}
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
|
||||
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
|
||||
assert!(
|
||||
partial
|
||||
.buckets_usage
|
||||
.get(BUCKET)
|
||||
.is_none_or(|value| value.usage_certification.is_none()),
|
||||
"the first process certified the bucket before the injected crash"
|
||||
);
|
||||
|
||||
env.stop_server();
|
||||
// The terminal save has returned and the old process can no longer write.
|
||||
assert!(
|
||||
bucket_metadata.join(".usage-cache.bin").join("xl.meta").is_file()
|
||||
&& bucket_metadata.join(".usage-cache.bin.pages").is_dir(),
|
||||
"the interrupted process must have committed a paged checkpoint"
|
||||
);
|
||||
let restart_log_offset = usize::try_from(tokio::fs::metadata(&server_log).await?.len())?;
|
||||
let restarted_at = SystemTime::now();
|
||||
env.start_rustfs_server_without_cleanup_with_env(SCAN_ENV).await?;
|
||||
let second_pid = env.process.as_ref().ok_or("missing restarted scanner process")?.id();
|
||||
assert_ne!(first_pid, second_pid);
|
||||
let deadline = Instant::now() + Duration::from_secs(180);
|
||||
loop {
|
||||
let usage: DataUsageInfo = admin(&env, "datausageinfo").await?;
|
||||
let status = scan_status(&env).await?;
|
||||
if let Some(bucket) = usage.buckets_usage.get(BUCKET)
|
||||
&& bucket.usage_value_state == Some(BucketUsageValueState::Certified)
|
||||
{
|
||||
let log = tokio::fs::read_to_string(&server_log).await?;
|
||||
let first_admission = log
|
||||
.get(restart_log_offset..)
|
||||
.ok_or("server log truncated across restart")?
|
||||
.lines()
|
||||
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
|
||||
.find(|record| record["state"] == "bucket_checkpoint_prepared" && record["bucket"] == BUCKET)
|
||||
.ok_or("no checkpoint admission in the restarted process")?;
|
||||
assert_eq!(first_admission["resume_position"], true, "restarted scanner discarded the checkpoint");
|
||||
assert!(usage.is_complete_bucket_usage_snapshot());
|
||||
let certificate = bucket
|
||||
.usage_certification
|
||||
.ok_or("missing certificate for the measured bucket")?;
|
||||
assert!(certificate.certified_at >= restarted_at, "stale pre-restart certificate");
|
||||
assert!(status.metrics.partial_cycles_runtime > 0, "new process must cross a cycle deadline");
|
||||
assert!(!status.disk_io_budget.is_empty(), "restarted scanner never admitted disk I/O");
|
||||
assert_eq!(inventory(&client).await?, expected, "durable S3 inventory changed across restart");
|
||||
let count = u64::try_from(expected.len())?;
|
||||
let bytes = expected.values().sum::<u64>();
|
||||
assert_eq!((bucket.objects_count, bucket.size), (count, bytes));
|
||||
assert_eq!((usage.objects_total_count, usage.objects_total_size), (count, bytes));
|
||||
eprintln!(
|
||||
"PIDs {first_pid}/{second_pid}, runtime-limited cycles since restart {}, certificate epoch {} cycle {}, S3 and admin {} objects/{} bytes",
|
||||
status.metrics.partial_cycles_runtime, certificate.epoch, certificate.cycle, count, bytes
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"no certified bucket after restart: {status:?}, value={:?}",
|
||||
usage.buckets_usage.get(BUCKET)
|
||||
);
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
@@ -1758,6 +1758,129 @@ mod upgrade_write_readiness_tests {
|
||||
}
|
||||
}
|
||||
|
||||
async fn stop_scanner_handoff_server(env: &mut RustFSTestEnvironment) -> TestResult {
|
||||
let process = env.process.as_mut().ok_or("handoff server is not running")?;
|
||||
signal_process(process.id(), "TERM")?;
|
||||
tokio::time::timeout(Duration::from_secs(90), async {
|
||||
loop {
|
||||
if let Some(status) = process.try_wait()? {
|
||||
assert!(status.success(), "handoff shutdown failed: {status}");
|
||||
return Ok::<(), BoxError>(());
|
||||
}
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
env.process.take();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scanner_handoff_identity(env: &RustFSTestEnvironment) -> Result<String, BoxError> {
|
||||
let receipt: Value = serde_json::from_slice(&std::fs::read(Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown"))?)?;
|
||||
assert_eq!(receipt["schema"], 1);
|
||||
assert_eq!(receipt["owner"], env.address);
|
||||
Ok(receipt["checkpoint_instance_id"]
|
||||
.as_str()
|
||||
.ok_or("handoff receipt omitted checkpoint identity")?
|
||||
.to_owned())
|
||||
}
|
||||
|
||||
async fn assert_scanner_handoff_consumed(marker: &Path) -> TestResult {
|
||||
let marker = tokio::fs::read_to_string(marker).await?;
|
||||
// Heal may replace the startup marker with its ordinary timestamp before
|
||||
// readiness. Neither form carries the prior checkpoint identity.
|
||||
assert!(
|
||||
marker == "running" || marker.parse::<u64>().is_ok(),
|
||||
"readiness must expose an ordinary unclean marker, never a handoff receipt"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scanner_read_only_handoff_requires_explicit_opt_in() -> TestResult {
|
||||
const HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
|
||||
assert!(std::env::var_os(HANDOFF).is_none(), "this scenario tests the unset default");
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
let marker = Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown");
|
||||
env.start_rustfs_server_without_cleanup(vec![]).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert!(!marker.exists(), "the default must not create a receipt");
|
||||
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
let previous = scanner_handoff_identity(&env)?;
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
assert_scanner_handoff_consumed(&marker).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert_eq!(scanner_handoff_identity(&env)?, previous, "opted-in read-only boots retain identity");
|
||||
|
||||
for disabled in ["invalid", "false"] {
|
||||
let before_disabled = scanner_handoff_identity(&env)?;
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, disabled)])
|
||||
.await?;
|
||||
assert_scanner_handoff_consumed(&marker).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert!(!marker.exists(), "disabled shutdown must not recreate the receipt");
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert_ne!(scanner_handoff_identity(&env)?, before_disabled, "opt-out breaks the prior lineage");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Exercise the receipt protocol in the existing pinned-release rollback lane.
|
||||
async fn assert_scanner_handoff_prepares_legacy_rollback(previous_binary: &Path) -> TestResult {
|
||||
const HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
let marker = Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown");
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
let previous = scanner_handoff_identity(&env)?;
|
||||
|
||||
// Complete the current reader's rollback preparation before any old writer
|
||||
// opens storage, including an old writer with all background services off.
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "false")])
|
||||
.await?;
|
||||
assert_scanner_handoff_consumed(&marker).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert!(!marker.exists());
|
||||
env.start_rustfs_server_from_binary_without_cleanup(
|
||||
previous_binary,
|
||||
vec![],
|
||||
&[
|
||||
("RUSTFS_SCANNER_ENABLED", "false"),
|
||||
("RUSTFS_HEAL_ENABLED", "false"),
|
||||
("RUSTFS_HEAL_AUTO_HEAL_ENABLE", "false"),
|
||||
("RUSTFS_HEAL_MRF_ENABLE", "false"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
let client = env.create_s3_client();
|
||||
env.create_test_bucket("handoff-rollback").await?;
|
||||
client
|
||||
.put_object()
|
||||
.bucket("handoff-rollback")
|
||||
.key("legacy-write")
|
||||
.body(ByteStream::from_static(b"legacy writer survived rollback preparation"))
|
||||
.send()
|
||||
.await?;
|
||||
env.stop_server();
|
||||
assert!(!marker.exists(), "the legacy crash cannot resurrect a consumed receipt");
|
||||
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
assert_eq!(
|
||||
read_object(&client, "handoff-rollback", "legacy-write", None).await?.1,
|
||||
b"legacy writer survived rollback preparation"
|
||||
);
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert_ne!(
|
||||
scanner_handoff_identity(&env)?,
|
||||
previous,
|
||||
"a legacy write must not retain the old lineage"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pins the published old writer's limitation and the supported recovery
|
||||
/// procedure. This is not a promise that mixed-version ODM is supported.
|
||||
/// Replace the loss assertion when ODM gains independent persistence;
|
||||
@@ -3462,6 +3585,7 @@ async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestRes
|
||||
init_logging();
|
||||
let previous_binary = source_binary()?;
|
||||
let evidence_context = g09_evidence_context(&previous_binary).await?;
|
||||
assert_scanner_handoff_prepares_legacy_rollback(&previous_binary).await?;
|
||||
|
||||
let replication_target = FakeS3Target::start().await?;
|
||||
replication_target.create_bucket(ROLLBACK_REPLICA_BUCKET);
|
||||
|
||||
@@ -183,7 +183,6 @@ 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};
|
||||
pub use crate::diagnostics::admin_server_info::{get_local_server_property, get_server_info, get_server_info_with_inventory};
|
||||
}
|
||||
|
||||
pub mod bitrot {
|
||||
@@ -72,10 +72,11 @@ pub mod bucket {
|
||||
ExpiryState, LifecycleOps, ManualTransitionCancelCheck, ManualTransitionProgressSink,
|
||||
ManualTransitionQueueSnapshot, ManualTransitionRunExecution, ManualTransitionRunOptions,
|
||||
ManualTransitionRunReport, RestoreRequestOps, TransitionState, TransitionedObject, apply_expiry_rule,
|
||||
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,
|
||||
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,
|
||||
run_stale_multipart_upload_cleanup_once, validate_transition_tier,
|
||||
};
|
||||
}
|
||||
@@ -348,7 +349,7 @@ pub mod bucket {
|
||||
|
||||
pub mod utils {
|
||||
pub use crate::bucket::utils::{
|
||||
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args,
|
||||
BucketConfigXml, BucketConfigXmlError, check_bucket_and_object_names, check_list_objs_args, check_object_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,
|
||||
};
|
||||
@@ -454,13 +455,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_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,
|
||||
load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin, 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,
|
||||
store_data_usage_in_backend, verified_account_bucket_usage,
|
||||
};
|
||||
pub use crate::data_usage::{get_bucket_usage_memory, lookup_degraded_bucket_usage_baseline};
|
||||
}
|
||||
@@ -469,6 +470,7 @@ 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")]
|
||||
@@ -503,7 +505,7 @@ pub mod disk {
|
||||
PoolMetaNativeInspection, PoolMetaNativeObject, PoolMetaNativeRecoveryRequest, PoolMetaNativeRecoveryResponse,
|
||||
QUOTA_MUTATION_FENCE_METADATA_SUFFIX, RUSTFS_META_BUCKET, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET,
|
||||
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp, STORAGE_FORMAT_FILE, SnapshotLeaseToken,
|
||||
UpdateMetadataOpts, VolumeInfo, WalkDirOptions, is_quota_mutation_fence_path, new_disk,
|
||||
UNCLEAN_SHUTDOWN_MARKER_PATH, UpdateMetadataOpts, VolumeInfo, WalkDirOptions, is_quota_mutation_fence_path, new_disk,
|
||||
validate_batch_read_version_item_count, validate_format_control_path,
|
||||
};
|
||||
pub use crate::disk::{
|
||||
@@ -769,8 +771,8 @@ pub mod storage {
|
||||
pub use crate::store::external_rpc_disk;
|
||||
pub use crate::store::{
|
||||
BootstrapLocalTarget, ECStore, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, all_local_disk,
|
||||
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, init_local_disks,
|
||||
init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
|
||||
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc,
|
||||
init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
|
||||
prewarm_local_disk_id_map_with_instance_ctx,
|
||||
};
|
||||
pub use crate::store::{HealObjectAbsenceProof, HealObjectStorageResult};
|
||||
|
||||
@@ -5082,7 +5082,14 @@ mod tests {
|
||||
let cert = generate_simple_self_signed(vec!["localhost".to_string()]).expect("certificate should generate");
|
||||
let (port, server) = spawn_https_server(&cert, 2);
|
||||
let endpoint = format!("https://localhost:{port}");
|
||||
let strict = target_client_for_test("arn:strict", endpoint.clone(), s3_client_for_test(port, None));
|
||||
let strict_client = s3_client_for_test(port, None);
|
||||
// A failed trust check must consume just one of the two fixture connections.
|
||||
let strict_config = strict_client
|
||||
.config()
|
||||
.to_builder()
|
||||
.retry_config(aws_sdk_s3::config::retry::RetryConfig::disabled())
|
||||
.build();
|
||||
let strict = target_client_for_test("arn:strict", endpoint.clone(), S3Client::from_conf(strict_config));
|
||||
let insecure = target_client_for_test(
|
||||
"arn:insecure",
|
||||
endpoint,
|
||||
|
||||
@@ -51,15 +51,20 @@ impl LcAuditEvent {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn emit_transition_failed_event(object: ObjectInfo) {
|
||||
emit_lifecycle_event(EventName::ObjectTransitionFailed, object, LIFECYCLE_TRANSITION_USER_AGENT);
|
||||
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_complete_event(object: ObjectInfo) {
|
||||
emit_lifecycle_event(EventName::ObjectTransitionComplete, 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_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo) {
|
||||
pub(crate) fn emit_transitioned_expiration_event(source: &ObjectInfo, deleted: &ObjectInfo, incarnation_id: uuid::Uuid) {
|
||||
let event_name = transitioned_expiration_event_name(source.delete_marker, deleted.delete_marker);
|
||||
let object = ObjectInfo {
|
||||
bucket: source.bucket.clone(),
|
||||
@@ -69,12 +74,17 @@ 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);
|
||||
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
|
||||
}
|
||||
|
||||
pub(crate) fn emit_non_transitioned_expiration_event(action: IlmAction, source: &ObjectInfo, deleted: ObjectInfo) {
|
||||
pub(crate) fn emit_non_transitioned_expiration_event(
|
||||
action: IlmAction,
|
||||
source: &ObjectInfo,
|
||||
deleted: ObjectInfo,
|
||||
incarnation_id: uuid::Uuid,
|
||||
) {
|
||||
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);
|
||||
emit_lifecycle_event(event_name, deleted, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
|
||||
}
|
||||
|
||||
/// Emit the lifecycle expiration event for one version removed by the batch
|
||||
@@ -83,9 +93,15 @@ pub(crate) fn emit_non_transitioned_expiration_event(action: IlmAction, source:
|
||||
/// 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) {
|
||||
pub(crate) fn emit_noncurrent_expiration_event(
|
||||
bucket: &str,
|
||||
target: &ObjectToDelete,
|
||||
deleted: &DeletedObject,
|
||||
failed: bool,
|
||||
incarnation_id: uuid::Uuid,
|
||||
) {
|
||||
if let Some((event_name, object)) = noncurrent_expiration_event(bucket, target, deleted, failed) {
|
||||
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT);
|
||||
emit_lifecycle_event(event_name, object, LIFECYCLE_EXPIRY_USER_AGENT, Some(incarnation_id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,9 +147,10 @@ fn noncurrent_expiration_event(
|
||||
Some((event_name, object))
|
||||
}
|
||||
|
||||
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str) {
|
||||
fn emit_lifecycle_event(event_name: EventName, object: ObjectInfo, user_agent: &str, incarnation_id: Option<uuid::Uuid>) {
|
||||
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;
|
||||
|
||||
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
|
||||
const LOG_SUBSYSTEM_LIFECYCLE: &str = "lifecycle";
|
||||
const EVENT_LIFECYCLE_WORKER_STATE: &str = "lifecycle_worker_state";
|
||||
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 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,7 +1566,12 @@ 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,
|
||||
@@ -1606,12 +1611,12 @@ pub struct TransitionState {
|
||||
compensation_scheduled_tasks: AtomicI64,
|
||||
compensation_running_tasks: AtomicI64,
|
||||
compensation_buckets: Arc<Mutex<HashSet<String>>>,
|
||||
// (bucket, object, version) currently queued or being transitioned. A single
|
||||
// (incarnation, 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<(String, String, String)>>>,
|
||||
in_flight_transitions: Arc<Mutex<HashSet<TransitionKey>>>,
|
||||
last_day_stats: Arc<Mutex<HashMap<String, LastDayTierStats>>>,
|
||||
}
|
||||
|
||||
@@ -1677,28 +1682,29 @@ impl TransitionState {
|
||||
})
|
||||
}
|
||||
|
||||
fn transition_key(oi: &ObjectInfo) -> (String, String, String) {
|
||||
fn transition_key(oi: &ObjectInfo, incarnation: Option<Uuid>) -> TransitionKey {
|
||||
(
|
||||
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 (bucket, object, version). Returns
|
||||
/// Try to claim a transition for this exact (incarnation, 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) -> bool {
|
||||
let key = Self::transition_key(oi);
|
||||
fn reserve_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) -> bool {
|
||||
let key = Self::transition_key(oi, incarnation);
|
||||
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) {
|
||||
let key = Self::transition_key(oi);
|
||||
fn release_transition(&self, oi: &ObjectInfo, incarnation: Option<Uuid>) {
|
||||
let key = Self::transition_key(oi, incarnation);
|
||||
match self.in_flight_transitions.lock() {
|
||||
Ok(mut set) => set.remove(&key),
|
||||
Err(poisoned) => poisoned.into_inner().remove(&key),
|
||||
@@ -1902,6 +1908,7 @@ 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);
|
||||
@@ -1914,7 +1921,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) {
|
||||
if !self.reserve_transition(oi, notification_bucket_incarnation) {
|
||||
self.record_scanner_transition_state();
|
||||
return TransitionEnqueueOutcome::AlreadyInFlight;
|
||||
}
|
||||
@@ -1923,7 +1930,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);
|
||||
self.release_transition(oi, notification_bucket_incarnation);
|
||||
warn!(
|
||||
event = EVENT_LIFECYCLE_WORKER_STATE,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
@@ -1948,7 +1955,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);
|
||||
self.release_transition(oi, notification_bucket_incarnation);
|
||||
warn!(
|
||||
event = EVENT_LIFECYCLE_WORKER_STATE,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
@@ -1967,6 +1974,7 @@ impl TransitionState {
|
||||
}
|
||||
|
||||
let task = TransitionTask {
|
||||
notification_bucket_incarnation,
|
||||
obj_info: oi.clone(),
|
||||
src: src.clone(),
|
||||
event: event.clone(),
|
||||
@@ -2010,7 +2018,7 @@ impl TransitionState {
|
||||
};
|
||||
let queued = outcome == TransitionEnqueueOutcome::Queued;
|
||||
if !queued {
|
||||
self.release_transition(oi);
|
||||
self.release_transition(oi, notification_bucket_incarnation);
|
||||
}
|
||||
record_scanner_transition_enqueue_result(src, 1, queued);
|
||||
self.record_scanner_transition_state();
|
||||
@@ -2063,7 +2071,7 @@ impl TransitionState {
|
||||
};
|
||||
let queued = outcome == TransitionEnqueueOutcome::Queued;
|
||||
if !queued {
|
||||
self.release_transition(oi);
|
||||
self.release_transition(oi, notification_bucket_incarnation);
|
||||
}
|
||||
record_scanner_transition_enqueue_result(src, 1, queued);
|
||||
self.record_scanner_transition_state();
|
||||
@@ -2071,7 +2079,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)
|
||||
self.queue_transition_task_outcome(None, oi, event, src, None, None)
|
||||
.await
|
||||
.is_handled()
|
||||
}
|
||||
@@ -2166,9 +2174,10 @@ impl TransitionState {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Err(err) =
|
||||
transition_object(api.clone(), &task.obj_info, LcAuditEvent::new(task.event.clone(), task.src.clone()))
|
||||
.await
|
||||
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 (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(
|
||||
@@ -2195,7 +2204,7 @@ impl TransitionState {
|
||||
"Lifecycle tier operation failed"
|
||||
);
|
||||
}
|
||||
emit_transition_failed_event(obj_info_for_event);
|
||||
emit_transition_failed_event(obj_info_for_event, incarnation_id);
|
||||
} 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(
|
||||
@@ -2217,11 +2226,11 @@ impl TransitionState {
|
||||
}
|
||||
transition_state.add_lastday_stats(&task.event.storage_class, ts);
|
||||
|
||||
emit_transition_complete_event(obj_info_for_event);
|
||||
emit_transition_complete_event(obj_info_for_event, incarnation_id);
|
||||
}
|
||||
// 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);
|
||||
transition_state.release_transition(&task.obj_info, task.notification_bucket_incarnation);
|
||||
TransitionState::add_counter(&transition_state.active_tasks, -1);
|
||||
transition_state.record_scanner_transition_state();
|
||||
}
|
||||
@@ -2826,7 +2835,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))
|
||||
.queue_transition_task_outcome(Some(api.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
|
||||
.await
|
||||
{
|
||||
TransitionEnqueueOutcome::Queued | TransitionEnqueueOutcome::AlreadyInFlight => {
|
||||
@@ -3084,6 +3093,7 @@ async fn recover_configured_tier_free_versions(
|
||||
next_object_marker: None,
|
||||
scanned_entries: 0,
|
||||
buckets_scanned: 0,
|
||||
unreadable_objects: 0,
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
@@ -3223,6 +3233,7 @@ 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,
|
||||
@@ -4059,9 +4070,11 @@ fn transitioned_cleanup_tuple(oi: &ObjectInfo) -> Result<(&str, &str, &str), std
|
||||
Ok((&transitioned.name, &transitioned.version_id, &transitioned.tier))
|
||||
}
|
||||
|
||||
pub async fn enqueue_transition_immediate(oi: &ObjectInfo, src: LcEventSrc) {
|
||||
/// 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>) {
|
||||
if let Some(lc) = runtime_sources::bucket_lifecycle_config(&oi.bucket).await {
|
||||
enqueue_transition_with_lifecycle(oi, &lc, &src).await;
|
||||
enqueue_transition_with_lifecycle(oi, &lc, &src, notification_bucket_incarnation).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4534,10 +4547,20 @@ pub async fn enqueue_transition_for_existing_objects_scoped(
|
||||
let deadline = options.max_duration.map(|duration| tokio::time::Instant::now() + duration);
|
||||
|
||||
loop {
|
||||
let page = api
|
||||
.clone()
|
||||
.list_object_versions(bucket, &options.prefix, marker.clone(), version_marker.clone(), None, LIST_PAGE_SIZE)
|
||||
.await?;
|
||||
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)
|
||||
};
|
||||
|
||||
for (index, object) in page.objects.iter().enumerate() {
|
||||
if manual_transition_cancel_requested(&options).await {
|
||||
@@ -4559,7 +4582,16 @@ 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).await;
|
||||
enqueue_transition_with_lifecycle_report(
|
||||
Some(api.clone()),
|
||||
object,
|
||||
&lc,
|
||||
&src,
|
||||
&options,
|
||||
&mut report,
|
||||
Some(bucket_incarnation_id),
|
||||
)
|
||||
.await;
|
||||
if report.has_enqueue_backpressure() {
|
||||
report.next_marker.clone_from(&previous_marker);
|
||||
report.next_version_idmarker.clone_from(&previous_version_marker);
|
||||
@@ -4865,6 +4897,7 @@ 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
|
||||
@@ -4917,7 +4950,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)
|
||||
.queue_transition_task_outcome(api.clone(), oi, &event, src, options.job_id, notification_bucket_incarnation)
|
||||
.await;
|
||||
report.record_enqueue_outcome(outcome);
|
||||
return outcome.is_handled();
|
||||
@@ -4927,7 +4960,12 @@ async fn enqueue_transition_with_lifecycle_report(
|
||||
false
|
||||
}
|
||||
|
||||
async fn enqueue_transition_with_lifecycle(oi: &ObjectInfo, lc: &PersistedLifecycleConfiguration, src: &LcEventSrc) -> bool {
|
||||
async fn enqueue_transition_with_lifecycle(
|
||||
oi: &ObjectInfo,
|
||||
lc: &PersistedLifecycleConfiguration,
|
||||
src: &LcEventSrc,
|
||||
notification_bucket_incarnation: Option<Uuid>,
|
||||
) -> bool {
|
||||
let event = lc.eval(&oi.to_lifecycle_opts()).await;
|
||||
match event.action {
|
||||
IlmAction::TransitionAction | IlmAction::TransitionVersionAction => {
|
||||
@@ -4938,8 +4976,9 @@ async fn enqueue_transition_with_lifecycle(oi: &ObjectInfo, lc: &PersistedLifecy
|
||||
return false;
|
||||
}
|
||||
runtime_sources::transition_state_handle()
|
||||
.queue_transition_task(oi, &event, src)
|
||||
.queue_transition_task_outcome(None, oi, &event, src, None, notification_bucket_incarnation)
|
||||
.await
|
||||
.is_handled()
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
@@ -5121,7 +5160,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
|
||||
}
|
||||
};
|
||||
|
||||
schedule_lifecycle_replication_delete_if_needed(oi, &dobj).await;
|
||||
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).await;
|
||||
|
||||
// The transitioned version is gone; evict any cached body for this object
|
||||
// so it does not linger until TTL (ODC-26).
|
||||
@@ -5134,7 +5173,7 @@ async fn expire_transitioned_object_with_lock_lost_signal(
|
||||
|
||||
//audit_log_lifecycle(oi, ILMExpiry, tags);
|
||||
|
||||
emit_transitioned_expiration_event(oi, &dobj);
|
||||
emit_transitioned_expiration_event(oi, &dobj, bucket_incarnation_id);
|
||||
|
||||
Ok(dobj)
|
||||
}
|
||||
@@ -5152,12 +5191,22 @@ pub fn gen_transition_objname(bucket: &str) -> Result<String, Error> {
|
||||
Ok(obj)
|
||||
}
|
||||
|
||||
pub async fn transition_object(api: Arc<ECStore>, oi: &ObjectInfo, lae: LcAuditEvent) -> Result<(), Error> {
|
||||
async fn transition_object(
|
||||
api: Arc<ECStore>,
|
||||
oi: &ObjectInfo,
|
||||
lae: LcAuditEvent,
|
||||
notification_bucket_incarnation: Option<Uuid>,
|
||||
) -> (Option<Uuid>, Result<(), Error>) {
|
||||
let time_ilm = Metrics::time_ilm(lae.event.action);
|
||||
|
||||
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 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 etag = if let Some(etag) = &oi.etag { etag } else { "" };
|
||||
let etag = etag.to_string();
|
||||
@@ -5175,12 +5224,13 @@ pub async fn transition_object(api: Arc<ECStore>, oi: &ObjectInfo, lae: LcAuditE
|
||||
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)();
|
||||
result
|
||||
(notification_bucket_incarnation, result)
|
||||
}
|
||||
|
||||
#[allow(
|
||||
@@ -5791,12 +5841,22 @@ 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(oi, event, src)
|
||||
.queue_transition_task_outcome(None, oi, event, src, None, notification_bucket_incarnation)
|
||||
.await
|
||||
.is_handled()
|
||||
}
|
||||
|
||||
async fn acquire_lifecycle_publication_guard(api: &ECStore, bucket: &str) -> Result<rustfs_lock::NamespaceLockGuard, Error> {
|
||||
@@ -5845,10 +5905,14 @@ 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;
|
||||
@@ -6034,7 +6098,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).await;
|
||||
schedule_lifecycle_replication_delete_if_needed(oi, &dobj, bucket_incarnation_id).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
|
||||
@@ -6050,7 +6114,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);
|
||||
emit_non_transitioned_expiration_event(lc_event.action, oi, dobj, bucket_incarnation_id);
|
||||
|
||||
if lc_event.action != IlmAction::NoneAction {
|
||||
let mut num_versions = 1_u64;
|
||||
@@ -6202,12 +6266,12 @@ fn lifecycle_deleted_object(oi: &ObjectInfo, dobj: &ObjectInfo) -> DeletedObject
|
||||
}
|
||||
}
|
||||
|
||||
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo) {
|
||||
async fn schedule_lifecycle_replication_delete_if_needed(oi: &ObjectInfo, dobj: &ObjectInfo, bucket_incarnation_id: Uuid) {
|
||||
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).await;
|
||||
replication_sink::schedule_delete(oi.bucket.clone(), delete_object, Some(bucket_incarnation_id)).await;
|
||||
}
|
||||
|
||||
async fn lifecycle_delete_config_snapshot(api: &ECStore, oi: &ObjectInfo) -> Result<DeleteReplicationConfigSnapshot, Error> {
|
||||
@@ -6597,6 +6661,7 @@ mod tests {
|
||||
next_object_marker: truncated.then(|| "object".to_string()),
|
||||
scanned_entries: 1,
|
||||
buckets_scanned: 1,
|
||||
unreadable_objects: 0,
|
||||
truncated,
|
||||
}
|
||||
}
|
||||
@@ -9114,6 +9179,160 @@ 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() {
|
||||
@@ -9181,7 +9400,7 @@ mod tests {
|
||||
.await
|
||||
.expect("queue should remain open")
|
||||
.expect("first queued transition task should be present");
|
||||
state.release_transition(&first_task.obj_info);
|
||||
state.release_transition(&first_task.obj_info, first_task.notification_bucket_incarnation);
|
||||
|
||||
assert!(
|
||||
deferred.await,
|
||||
@@ -9940,8 +10159,8 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(state.reserve_transition(&oi), "first claim must succeed");
|
||||
assert!(!state.reserve_transition(&oi), "duplicate claim must be rejected");
|
||||
assert!(state.reserve_transition(&oi, None), "first claim must succeed");
|
||||
assert!(!state.reserve_transition(&oi, None), "duplicate claim must be rejected");
|
||||
|
||||
// A different object is independent.
|
||||
let other = ObjectInfo {
|
||||
@@ -9950,11 +10169,11 @@ mod tests {
|
||||
version_id: None,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(state.reserve_transition(&other), "distinct object must claim independently");
|
||||
assert!(state.reserve_transition(&other, None), "distinct object must claim independently");
|
||||
|
||||
// After release, the same object can be re-claimed (later lifecycle pass).
|
||||
state.release_transition(&oi);
|
||||
assert!(state.reserve_transition(&oi), "re-claim after release must succeed");
|
||||
state.release_transition(&oi, None);
|
||||
assert!(state.reserve_transition(&oi, None), "re-claim after release must succeed");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -9996,10 +10215,10 @@ mod tests {
|
||||
};
|
||||
|
||||
let first = state
|
||||
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
|
||||
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
|
||||
.await;
|
||||
let second = state
|
||||
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None)
|
||||
.queue_transition_task_outcome(None, &object, &event, &LcEventSrc::Scanner, None, None)
|
||||
.await;
|
||||
|
||||
assert_eq!(first, TransitionEnqueueOutcome::Queued);
|
||||
@@ -10027,10 +10246,10 @@ mod tests {
|
||||
};
|
||||
|
||||
let first = state
|
||||
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None)
|
||||
.queue_transition_task_outcome(None, &first_object, &event, &LcEventSrc::Scanner, None, None)
|
||||
.await;
|
||||
let second = state
|
||||
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None)
|
||||
.queue_transition_task_outcome(None, &second_object, &event, &LcEventSrc::Scanner, None, None)
|
||||
.await;
|
||||
|
||||
assert_eq!(first, TransitionEnqueueOutcome::Queued);
|
||||
@@ -10063,7 +10282,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))
|
||||
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(job_id), None)
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome, TransitionEnqueueOutcome::Queued);
|
||||
@@ -10100,14 +10319,14 @@ mod tests {
|
||||
};
|
||||
|
||||
let failed = state
|
||||
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()))
|
||||
.queue_transition_task_outcome(Some(ecstore.clone()), &object, &event, &LcEventSrc::Scanner, Some(Uuid::nil()), None)
|
||||
.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()))
|
||||
.queue_transition_task_outcome(Some(ecstore), &object, &event, &LcEventSrc::Scanner, Some(Uuid::new_v4()), None)
|
||||
.await;
|
||||
assert_eq!(retried, TransitionEnqueueOutcome::Queued);
|
||||
assert_eq!(state.transition_rx.len(), 1);
|
||||
@@ -10608,7 +10827,7 @@ mod tests {
|
||||
let lc = latest_transition_lifecycle();
|
||||
let object = current_object(ReplicationStatusType::Pending);
|
||||
|
||||
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner).await;
|
||||
let queued = enqueue_transition_with_lifecycle(&object, &lc, &LcEventSrc::Scanner, None).await;
|
||||
|
||||
assert!(!queued);
|
||||
}
|
||||
@@ -10624,7 +10843,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).await;
|
||||
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
|
||||
|
||||
assert!(handled);
|
||||
assert_eq!(report.eligible, 1);
|
||||
@@ -10646,7 +10865,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).await;
|
||||
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
|
||||
|
||||
assert!(!handled);
|
||||
assert_eq!(report.eligible, 0);
|
||||
@@ -10665,7 +10884,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).await;
|
||||
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
|
||||
|
||||
assert!(!handled);
|
||||
assert_eq!(report.eligible, 0);
|
||||
@@ -10680,7 +10899,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).await;
|
||||
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
|
||||
|
||||
assert!(!handled);
|
||||
assert_eq!(report.eligible, 0);
|
||||
@@ -10793,7 +11012,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).await;
|
||||
enqueue_transition_with_lifecycle_report(None, &object, &lc, &LcEventSrc::Scanner, &options, &mut report, None).await;
|
||||
|
||||
assert!(!handled);
|
||||
assert_eq!(report.eligible, 0);
|
||||
@@ -14138,7 +14357,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).await });
|
||||
tokio::spawn(async move { lifecycle_transition_publication_guard(&admission_store, &admission_object, None).await });
|
||||
assert!(
|
||||
tokio::time::timeout(StdDuration::from_millis(100), &mut admission)
|
||||
.await
|
||||
@@ -14957,6 +15176,37 @@ 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))
|
||||
@@ -15029,6 +15279,7 @@ mod tests {
|
||||
next_object_marker: None,
|
||||
scanned_entries: 0,
|
||||
buckets_scanned: 0,
|
||||
unreadable_objects: 0,
|
||||
truncated: false,
|
||||
}
|
||||
);
|
||||
@@ -15225,12 +15476,14 @@ 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
|
||||
@@ -15250,21 +15503,27 @@ 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());
|
||||
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!(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");
|
||||
remove_seeded_free_version(&disks, &bucket, "owned").await;
|
||||
api.tier_config_mgr()
|
||||
.write()
|
||||
@@ -15484,6 +15743,121 @@ 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,6 +124,9 @@ 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);
|
||||
emit_noncurrent_expiration_event(bucket, target, deleted_obj, false, bucket_incarnation_id);
|
||||
}
|
||||
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()).await;
|
||||
replication_sink::schedule_delete(bucket.to_string(), deleted_obj.clone(), Some(bucket_incarnation_id)).await;
|
||||
}
|
||||
|
||||
for (i, err) in errors.iter().enumerate() {
|
||||
|
||||
@@ -66,8 +66,12 @@ pub(crate) fn lifecycle_action_waits_for_replication(action: IlmAction) -> bool
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
|
||||
ReplicationLifecycleBridge::schedule_delete(bucket, delete_object).await;
|
||||
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;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -20,7 +20,9 @@ use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::bucket::lifecycle::bucket_lifecycle_ops::enqueue_recovered_free_version_with_cancel;
|
||||
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::disk::RUSTFS_META_BUCKET;
|
||||
use crate::error::Result;
|
||||
use crate::object_api::ObjectInfo;
|
||||
@@ -28,9 +30,10 @@ 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::{ListOperations as _, StorageObjectInfoOrErr, StorageWalkOptions},
|
||||
list::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;
|
||||
@@ -45,7 +48,6 @@ 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)]
|
||||
@@ -143,6 +145,8 @@ 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,
|
||||
}
|
||||
|
||||
@@ -161,6 +165,7 @@ impl TierCleanupRetryReport {
|
||||
scanned: 0,
|
||||
enqueued: 0,
|
||||
failed: 0,
|
||||
unreadable_objects: 0,
|
||||
scan_truncated: false,
|
||||
}
|
||||
}
|
||||
@@ -267,6 +272,7 @@ 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() {
|
||||
@@ -290,6 +296,7 @@ pub struct FreeVersionRecoveryStats {
|
||||
pub next_object_marker: Option<String>,
|
||||
pub scanned_entries: usize,
|
||||
pub buckets_scanned: usize,
|
||||
pub unreadable_objects: usize,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
@@ -300,6 +307,7 @@ pub struct FreeVersionRecoveryPage {
|
||||
pub next_object_marker: Option<String>,
|
||||
pub scanned_entries: usize,
|
||||
pub buckets_scanned: usize,
|
||||
pub unreadable_objects: usize,
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
@@ -343,6 +351,7 @@ 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,
|
||||
};
|
||||
|
||||
@@ -472,6 +481,7 @@ async fn list_tier_free_versions_for_tier(
|
||||
next_object_marker: None,
|
||||
scanned_entries: 0,
|
||||
buckets_scanned: 0,
|
||||
unreadable_objects: 0,
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
@@ -505,6 +515,7 @@ 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() {
|
||||
@@ -535,7 +546,7 @@ async fn list_tier_free_versions_for_tier(
|
||||
};
|
||||
let bucket_walk_limit = remaining_scan_objects;
|
||||
|
||||
let (tx, mut rx) = mpsc::channel::<ObjectInfoOrErr>(100);
|
||||
let (tx, mut rx) = mpsc::channel::<Result<TierRecoveryEntry>>(100);
|
||||
let cancel = cancel_token.child_token();
|
||||
let mut draining_after_truncation = false;
|
||||
let mut drain_deadline = None;
|
||||
@@ -559,14 +570,7 @@ async fn list_tier_free_versions_for_tier(
|
||||
match action {
|
||||
RecoveryWalkTestAction::SendItems(items) => {
|
||||
for item in items {
|
||||
if tx
|
||||
.send(ObjectInfoOrErr {
|
||||
item: Some(item),
|
||||
err: None,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -574,35 +578,16 @@ async fn list_tier_free_versions_for_tier(
|
||||
}
|
||||
RecoveryWalkTestAction::SendItemsThenError(items, err) => {
|
||||
for item in items {
|
||||
if tx
|
||||
.send(ObjectInfoOrErr {
|
||||
item: Some(item),
|
||||
err: None,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
let _ = tx
|
||||
.send(ObjectInfoOrErr {
|
||||
item: None,
|
||||
err: Some(err),
|
||||
})
|
||||
.await;
|
||||
let _ = tx.send(Err(err)).await;
|
||||
return Ok(());
|
||||
}
|
||||
RecoveryWalkTestAction::SendItemsThenHang(items, started) => {
|
||||
for item in items {
|
||||
if tx
|
||||
.send(ObjectInfoOrErr {
|
||||
item: Some(item),
|
||||
err: None,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
if tx.send(Ok(TierRecoveryEntry::Version(Box::new(item)))).await.is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
@@ -614,14 +599,11 @@ async fn list_tier_free_versions_for_tier(
|
||||
let mut index = 0usize;
|
||||
loop {
|
||||
if tx
|
||||
.send(ObjectInfoOrErr {
|
||||
item: Some(ObjectInfo {
|
||||
bucket: bucket_name.clone(),
|
||||
name: format!("nonrecoverable-{index:08}"),
|
||||
..Default::default()
|
||||
}),
|
||||
err: None,
|
||||
})
|
||||
.send(Ok(TierRecoveryEntry::Version(Box::new(ObjectInfo {
|
||||
bucket: bucket_name.clone(),
|
||||
name: format!("nonrecoverable-{index:08}"),
|
||||
..Default::default()
|
||||
}))))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
@@ -639,7 +621,7 @@ async fn list_tier_free_versions_for_tier(
|
||||
}
|
||||
}
|
||||
|
||||
api.walk(cancel, &bucket_name, "", tx, recovery_walk_options(bucket_walk_limit, object_marker))
|
||||
api.walk_for_tier_recovery(cancel, &bucket_name, tx, recovery_walk_options(bucket_walk_limit, object_marker))
|
||||
.await
|
||||
}
|
||||
});
|
||||
@@ -669,21 +651,25 @@ async fn list_tier_free_versions_for_tier(
|
||||
},
|
||||
};
|
||||
page.scanned_entries += 1;
|
||||
if let Some(err) = item.err {
|
||||
cancel.cancel();
|
||||
receive_error = Some(err);
|
||||
break;
|
||||
}
|
||||
let entry = match item {
|
||||
Ok(entry) => entry,
|
||||
Err(err) => {
|
||||
cancel.cancel();
|
||||
receive_error = Some(err);
|
||||
break;
|
||||
}
|
||||
};
|
||||
if draining_after_truncation {
|
||||
continue;
|
||||
}
|
||||
let Some(oi) = item.item else {
|
||||
continue;
|
||||
let name = match &entry {
|
||||
TierRecoveryEntry::Version(oi) => oi.name.as_str(),
|
||||
TierRecoveryEntry::Unreadable { object } => object.as_str(),
|
||||
};
|
||||
if last_seen_object.as_deref() != Some(oi.name.as_str()) && scanned_objects >= bucket_walk_limit {
|
||||
if last_seen_object.as_deref() != Some(name) && scanned_objects >= bucket_walk_limit {
|
||||
// The disk listing limit follows S3-visible counting rules and
|
||||
// does not charge metadata containing only hidden/free versions.
|
||||
// Enforce the repair budget again at the decoded-object boundary.
|
||||
// Charge the recovery budget by key, including unreadable metadata.
|
||||
page.truncated = true;
|
||||
page.next_bucket_marker = Some(bucket.name.clone());
|
||||
page.next_object_marker = last_seen_object.clone();
|
||||
@@ -692,9 +678,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, &oi.name);
|
||||
record_scanned_object(&mut last_seen_object, &mut scanned_objects, name);
|
||||
if let Some(cursor) = &truncated_after
|
||||
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != oi.name.as_str())
|
||||
&& (cursor.bucket.as_str() != bucket.name.as_str() || cursor.object.as_str() != name)
|
||||
{
|
||||
page.truncated = true;
|
||||
cancel.cancel();
|
||||
@@ -702,6 +688,14 @@ 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(),
|
||||
@@ -756,6 +750,18 @@ 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)
|
||||
}
|
||||
|
||||
@@ -823,6 +829,7 @@ mod tests {
|
||||
next_object_marker: None,
|
||||
scanned_entries: 1,
|
||||
buckets_scanned: 1,
|
||||
unreadable_objects: 0,
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
@@ -843,6 +850,7 @@ mod tests {
|
||||
next_object_marker: Some("object".to_string()),
|
||||
scanned_entries: 1,
|
||||
buckets_scanned: 1,
|
||||
unreadable_objects: 0,
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
@@ -863,6 +871,7 @@ 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());
|
||||
@@ -973,6 +982,7 @@ mod tests {
|
||||
next_object_marker: None,
|
||||
scanned_entries: DEFAULT_FREE_VERSION_RECOVERY_SCAN_LIMIT,
|
||||
buckets_scanned: 1,
|
||||
unreadable_objects: 0,
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -2090,6 +2090,74 @@ 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)
|
||||
}
|
||||
@@ -2135,6 +2203,20 @@ 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
|
||||
@@ -2169,6 +2251,11 @@ 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)]
|
||||
@@ -2253,6 +2340,7 @@ impl BucketMetadataSys {
|
||||
.await?;
|
||||
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, persisted, &guard)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2291,6 +2379,12 @@ 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(|| {
|
||||
@@ -2550,7 +2644,7 @@ impl BucketMetadataSys {
|
||||
metadata: BucketMetadata,
|
||||
persisted: bool,
|
||||
namespace_guard: &rustfs_lock::NamespaceLockGuard,
|
||||
) -> Result<()> {
|
||||
) -> Result<bool> {
|
||||
self.revoke_pending_bucket_creation(bucket).await;
|
||||
if !persisted {
|
||||
let _publish_guard = self
|
||||
@@ -2563,7 +2657,7 @@ impl BucketMetadataSys {
|
||||
_ => false,
|
||||
};
|
||||
if !unchanged {
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
let removed = map.remove(bucket).is_some();
|
||||
drop(map);
|
||||
@@ -2574,7 +2668,7 @@ impl BucketMetadataSys {
|
||||
clear_bucket_overrides(bucket);
|
||||
clear_on_demand_migration(bucket);
|
||||
}
|
||||
return Ok(());
|
||||
return Ok(true);
|
||||
}
|
||||
let _publish_guard = self
|
||||
.lock_metadata_publish(bucket, namespace_guard, "refreshed bucket metadata publish")
|
||||
@@ -2587,7 +2681,7 @@ impl BucketMetadataSys {
|
||||
_ => false,
|
||||
};
|
||||
if !unchanged {
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
map.insert(bucket.to_string(), Arc::clone(&metadata));
|
||||
drop(map);
|
||||
@@ -2596,7 +2690,7 @@ impl BucketMetadataSys {
|
||||
sync_bucket_target_sys(bucket, &metadata).await;
|
||||
sync_bucket_overrides(bucket, &metadata);
|
||||
sync_on_demand_migration(bucket, &metadata);
|
||||
Ok(())
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub async fn get(&self, bucket: &str) -> Result<Arc<BucketMetadata>> {
|
||||
@@ -2880,25 +2974,35 @@ 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));
|
||||
}
|
||||
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));
|
||||
// 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(());
|
||||
}
|
||||
}
|
||||
self.publish_if_unchanged(bucket, expected.as_ref(), metadata, true, namespace_guard)
|
||||
.await
|
||||
Err(Error::other("bucket metadata changed repeatedly during peer reload"))
|
||||
}
|
||||
|
||||
pub async fn get_config(&self, bucket: &str) -> Result<(Arc<BucketMetadata>, bool)> {
|
||||
@@ -3475,7 +3579,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 gen_before = current_local_meta_mutation_gen();
|
||||
let mut gen_before = current_local_meta_mutation_gen();
|
||||
let cached_authority = can_use_local_authority_cache
|
||||
.then(|| {
|
||||
self.local_authority_cache
|
||||
@@ -3499,6 +3603,43 @@ 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),
|
||||
@@ -6981,4 +7122,165 @@ 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,6 +13,8 @@
|
||||
// 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,7 +89,11 @@ impl ReplicationLifecycleBridge {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn schedule_delete(bucket: String, delete_object: DeletedObject) {
|
||||
pub(crate) async fn schedule_delete(
|
||||
bucket: String,
|
||||
delete_object: DeletedObject,
|
||||
notification_bucket_incarnation: Option<uuid::Uuid>,
|
||||
) {
|
||||
#[cfg(test)]
|
||||
{
|
||||
SCHEDULED_DELETE_OBJECTS
|
||||
@@ -98,6 +102,7 @@ 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,6 +22,10 @@ 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,13 +110,16 @@ 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).await;
|
||||
schedule_replication(object, storage, decision, op_type, notification_bucket_incarnation).await;
|
||||
}
|
||||
|
||||
pub async fn schedule_delete(delete_object: DeletedObjectReplicationInfo) {
|
||||
@@ -148,8 +151,16 @@ impl ReplicationObjectBridge {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn schedule_storage_delete(delete_object: DeletedObject, bucket: String, event_type: String) {
|
||||
/// 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>,
|
||||
) {
|
||||
Self::schedule_delete(DeletedObjectReplicationInfo {
|
||||
notification_bucket_incarnation,
|
||||
delete_object: deleted_object_for_replication(delete_object),
|
||||
bucket,
|
||||
event_type,
|
||||
@@ -158,10 +169,18 @@ impl ReplicationObjectBridge {
|
||||
.await;
|
||||
}
|
||||
|
||||
pub async fn schedule_storage_deletes(delete_objects: Vec<DeletedObject>, bucket: String, event_type: String) {
|
||||
/// 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>,
|
||||
) {
|
||||
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,7 +1016,9 @@ 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);
|
||||
let mut roi = replicate_object_info_from_object_info(oi, dsc, op_type);
|
||||
// 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);
|
||||
roi.retry_count = entry.retry_count.max(0) as u32;
|
||||
roi
|
||||
}
|
||||
@@ -3171,12 +3173,13 @@ 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);
|
||||
let ri = replicate_object_info_from_object_info(async_oi.clone(), synchronous, op_type, notification_bucket_incarnation);
|
||||
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;
|
||||
@@ -3185,7 +3188,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);
|
||||
let ri = replicate_object_info_from_object_info(async_oi, asynchronous, op_type, notification_bucket_incarnation);
|
||||
let _ = pool.queue_replica_task(ri).await;
|
||||
}
|
||||
}
|
||||
@@ -3194,6 +3197,7 @@ 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());
|
||||
@@ -3209,6 +3213,7 @@ 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,
|
||||
@@ -3350,7 +3355,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);
|
||||
let mut roi = replicate_object_info_from_object_info(oi, dsc, ReplicationType::Metadata, None);
|
||||
roi.retry_count = retry_count;
|
||||
if let Some(pool) = runtime_sources::replication_pool() {
|
||||
pool.queue_replica_task(roi).await
|
||||
@@ -5205,6 +5210,117 @@ 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");
|
||||
@@ -5219,7 +5335,7 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object);
|
||||
let ri = replicate_object_info_from_object_info(oi, ReplicateDecision::default(), ReplicationType::Object, None);
|
||||
|
||||
assert!(ri.ssec);
|
||||
assert_eq!(ri.checksum, Some(checksum));
|
||||
@@ -5235,8 +5351,12 @@ 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);
|
||||
let live = replicate_object_info_from_object_info(
|
||||
object.clone(),
|
||||
test_replicate_decision(&[target]),
|
||||
ReplicationType::Metadata,
|
||||
None,
|
||||
);
|
||||
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,6 +2274,7 @@ 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,
|
||||
@@ -2448,6 +2449,7 @@ 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 {
|
||||
@@ -2529,6 +2531,7 @@ 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 {
|
||||
@@ -2563,6 +2566,7 @@ 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 {
|
||||
@@ -2593,6 +2597,7 @@ 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 {
|
||||
@@ -2692,6 +2697,7 @@ 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 {
|
||||
@@ -2800,6 +2806,7 @@ 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,
|
||||
@@ -2825,6 +2832,7 @@ 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 {
|
||||
@@ -3156,6 +3164,7 @@ 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();
|
||||
@@ -3176,6 +3185,7 @@ 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 {
|
||||
@@ -3199,6 +3209,7 @@ 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 {
|
||||
@@ -3233,6 +3244,7 @@ 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 {
|
||||
@@ -3261,6 +3273,7 @@ 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 {
|
||||
@@ -3308,6 +3321,7 @@ 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 {
|
||||
@@ -3338,6 +3352,7 @@ 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 {
|
||||
@@ -3374,6 +3389,7 @@ 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 {
|
||||
@@ -4237,6 +4253,7 @@ 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(),
|
||||
@@ -4260,6 +4277,7 @@ 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(),
|
||||
@@ -4326,6 +4344,7 @@ 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(),
|
||||
@@ -4470,6 +4489,7 @@ 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,
|
||||
@@ -4612,6 +4632,7 @@ 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(),
|
||||
@@ -4627,6 +4648,7 @@ 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(),
|
||||
@@ -4670,6 +4692,7 @@ 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(),
|
||||
@@ -4701,6 +4724,7 @@ 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,
|
||||
@@ -4726,6 +4750,7 @@ 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,
|
||||
@@ -4857,6 +4882,7 @@ 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,
|
||||
@@ -4885,6 +4911,7 @@ 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,
|
||||
@@ -4982,6 +5009,7 @@ 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(),
|
||||
@@ -5015,7 +5043,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);
|
||||
note_replicate_all_size_unavailable(&bucket, &tgt_client, object_info, &e, self.notification_bucket_incarnation);
|
||||
return rinfo;
|
||||
}
|
||||
};
|
||||
@@ -5024,7 +5052,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);
|
||||
note_replicate_all_target_bucket_empty(&bucket, &tgt_client, object_info, self.notification_bucket_incarnation);
|
||||
return rinfo;
|
||||
}
|
||||
|
||||
@@ -5070,7 +5098,15 @@ 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);
|
||||
fail_replicate_all_put_options(
|
||||
&mut rinfo,
|
||||
&tgt_client,
|
||||
&bucket,
|
||||
object_info,
|
||||
&e,
|
||||
start_time,
|
||||
self.notification_bucket_incarnation,
|
||||
);
|
||||
return rinfo;
|
||||
}
|
||||
};
|
||||
@@ -5174,6 +5210,7 @@ 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(),
|
||||
@@ -5212,6 +5249,7 @@ 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(),
|
||||
@@ -5223,7 +5261,13 @@ 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) {
|
||||
fn note_replicate_all_size_unavailable(
|
||||
bucket: &str,
|
||||
tgt_client: &TargetClient,
|
||||
object_info: ObjectInfo,
|
||||
e: &std::io::Error,
|
||||
incarnation_id: Option<uuid::Uuid>,
|
||||
) {
|
||||
debug!(
|
||||
event = EVENT_RESYNC_RUNTIME_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
@@ -5236,6 +5280,7 @@ fn note_replicate_all_size_unavailable(bucket: &str, tgt_client: &TargetClient,
|
||||
"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,
|
||||
@@ -5246,7 +5291,12 @@ fn note_replicate_all_size_unavailable(bucket: &str, tgt_client: &TargetClient,
|
||||
|
||||
/// 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) {
|
||||
fn note_replicate_all_target_bucket_empty(
|
||||
bucket: &str,
|
||||
tgt_client: &TargetClient,
|
||||
object_info: ObjectInfo,
|
||||
incarnation_id: Option<uuid::Uuid>,
|
||||
) {
|
||||
debug!(
|
||||
event = EVENT_RESYNC_RUNTIME_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
@@ -5258,6 +5308,7 @@ fn note_replicate_all_target_bucket_empty(bucket: &str, tgt_client: &TargetClien
|
||||
"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,
|
||||
@@ -5371,6 +5422,7 @@ 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(),
|
||||
@@ -5494,6 +5546,7 @@ 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,
|
||||
@@ -5526,6 +5579,7 @@ 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,
|
||||
@@ -5554,6 +5608,7 @@ 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());
|
||||
@@ -5569,6 +5624,7 @@ 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,6 +24,8 @@ 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,6 +18,8 @@ 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,6 +145,22 @@ 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());
|
||||
|
||||
@@ -154,9 +170,9 @@ pub async fn node_service_time_out_client_for_class(
|
||||
interceptor.replay_scope_audience(),
|
||||
connection_state,
|
||||
);
|
||||
Ok(NodeServiceClient::with_interceptor(channel, interceptor)
|
||||
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,6 +294,11 @@ 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
|
||||
@@ -2744,8 +2749,6 @@ 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. Writes, walks and any stream whose first chunk cannot
|
||||
//! be served this way use the TCP/HTTP transport.
|
||||
//! have no IP addresses. Shard reads and writes require NIXL. Directory walks
|
||||
//! and scanner requests use the control 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,7 +83,6 @@ 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";
|
||||
|
||||
@@ -125,8 +124,7 @@ fn recv_pool() -> Option<Arc<dyn NixlRecvPool>> {
|
||||
RECV_POOL.get().cloned()
|
||||
}
|
||||
|
||||
/// Internode transport that reads shard streams over NIXL and delegates
|
||||
/// everything else to TCP/HTTP.
|
||||
/// Internode transport for NIXL shard data and TCP/HTTP control requests.
|
||||
#[derive(Debug)]
|
||||
pub struct NixlInternodeDataTransport {
|
||||
tcp: TcpHttpInternodeDataTransport,
|
||||
@@ -141,72 +139,36 @@ impl NixlInternodeDataTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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()?;
|
||||
async fn open_nixl(&self, request: ReadStreamRequest) -> Result<NixlChunkReader> {
|
||||
if request.length == 0 {
|
||||
// Unbounded reads need the file size; TCP/HTTP streams them.
|
||||
return None;
|
||||
return Err(io::Error::new(io::ErrorKind::Unsupported, "NIXL shard reads require a bounded range").into());
|
||||
}
|
||||
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
|
||||
}
|
||||
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;
|
||||
}
|
||||
Ok(reader)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl InternodeDataTransport for NixlInternodeDataTransport {
|
||||
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,
|
||||
}
|
||||
fn requires_bounded_reads(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
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(&self, request: ReadStreamRequest) -> Result<FileReader> {
|
||||
Ok(Box::new(self.open_nixl(request).await?))
|
||||
}
|
||||
|
||||
async fn open_read_chunks(&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(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,
|
||||
}
|
||||
Ok(Some(Box::new(self.open_nixl(request).await?)))
|
||||
}
|
||||
|
||||
async fn open_write(&self, request: WriteStreamRequest) -> Result<FileWriter> {
|
||||
match recv_pool() {
|
||||
Some(pool) => Ok(Box::new(NixlFileWriter::new(pool, request))),
|
||||
None => self.tcp.open_write(request).await,
|
||||
}
|
||||
let pool = recv_pool().ok_or_else(|| io::Error::other("NIXL receive pool unavailable"))?;
|
||||
Ok(Box::new(NixlFileWriter::new(pool, request)))
|
||||
}
|
||||
|
||||
async fn open_walk_dir(&self, request: WalkDirStreamRequest) -> Result<FileReader> {
|
||||
@@ -230,7 +192,10 @@ impl InternodeDataTransport for NixlInternodeDataTransport {
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> InternodeDataTransportCapabilities {
|
||||
InternodeDataTransportCapabilities::tcp_http()
|
||||
InternodeDataTransportCapabilities {
|
||||
fallback_supported: false,
|
||||
..InternodeDataTransportCapabilities::tcp_http()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,7 +255,17 @@ 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, _) = rustfs_rio::internode_http_request(&url, Method::GET, headers, Some(timeout)).await?;
|
||||
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)> {
|
||||
if !status.is_success() {
|
||||
debug!(
|
||||
component = LOG_COMPONENT_INTERNODE,
|
||||
@@ -299,6 +274,18 @@ async fn fetch_chunk(pool: Arc<dyn NixlRecvPool>, request: ReadStreamRequest, ti
|
||||
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
|
||||
@@ -306,10 +293,10 @@ async fn fetch_chunk(pool: Arc<dyn NixlRecvPool>, request: ReadStreamRequest, ti
|
||||
.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 > request.length {
|
||||
if landed > requested {
|
||||
return Err(io::Error::other("nixl internode read reports more bytes than requested"));
|
||||
}
|
||||
Ok((request.length, buffer.complete(landed)?))
|
||||
Ok((requested, buffer.complete(landed)?))
|
||||
}
|
||||
|
||||
type ChunkFuture = BoxFuture<'static, io::Result<(usize, Bytes)>>;
|
||||
@@ -662,11 +649,35 @@ 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>,
|
||||
}
|
||||
@@ -716,7 +727,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
struct VecPool;
|
||||
pub(super) struct VecPool;
|
||||
|
||||
impl NixlRecvPool for VecPool {
|
||||
fn agent_name(&self) -> &str {
|
||||
@@ -897,6 +908,38 @@ 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));
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use super::{NixlChunkReader, ReadStreamRequest, tests::VecPool};
|
||||
use crate::cluster::rpc::{internode_data_transport::InternodeDataTransport, remote_disk::RemoteDisk};
|
||||
use crate::disk::{Disk, DiskOption, DiskStore, endpoint::Endpoint};
|
||||
use rustfs_rio::ChunkReaderBox;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::task::JoinHandle;
|
||||
use url::Url;
|
||||
|
||||
/// Serve a single response over HTTP/1.1 and return the request URI for assertions.
|
||||
pub(crate) async fn read_peer(response: Vec<u8>) -> (Endpoint, JoinHandle<Url>) {
|
||||
crate::runtime::sources::ensure_test_rpc_secret();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind loopback peer");
|
||||
let address = listener.local_addr().expect("peer address");
|
||||
let url = Url::parse(&format!("http://{address}/disk")).expect("disk URL");
|
||||
let endpoint = Endpoint {
|
||||
url: url.clone(),
|
||||
is_local: false,
|
||||
pool_idx: 0,
|
||||
set_idx: 0,
|
||||
disk_idx: 0,
|
||||
};
|
||||
let peer = tokio::spawn(async move {
|
||||
let (mut socket, _) = tokio::time::timeout(std::time::Duration::from_secs(10), listener.accept())
|
||||
.await
|
||||
.expect("peer received a request")
|
||||
.expect("accept read");
|
||||
let mut lines = BufReader::new(&mut socket).lines();
|
||||
let request = lines.next_line().await.expect("request line").expect("request");
|
||||
let target = request.split_whitespace().nth(1).expect("request target");
|
||||
while !lines
|
||||
.next_line()
|
||||
.await
|
||||
.expect("read headers")
|
||||
.expect("header terminator")
|
||||
.is_empty()
|
||||
{}
|
||||
socket.write_all(&response).await.expect("send response");
|
||||
url.join(target).expect("request URI")
|
||||
});
|
||||
(endpoint, peer)
|
||||
}
|
||||
|
||||
pub(crate) async fn remote_disk(endpoint: &Endpoint, transport: Arc<dyn InternodeDataTransport>) -> DiskStore {
|
||||
let disk = RemoteDisk::new(
|
||||
endpoint,
|
||||
&DiskOption {
|
||||
cleanup: false,
|
||||
health_check: false,
|
||||
},
|
||||
transport,
|
||||
)
|
||||
.await
|
||||
.expect("create remote disk");
|
||||
Arc::new(Disk::Remote(Box::new(disk)))
|
||||
}
|
||||
|
||||
pub(crate) fn nixl_reader(endpoint: &Endpoint, length: usize) -> ChunkReaderBox {
|
||||
let request = ReadStreamRequest {
|
||||
endpoint: endpoint.grid_host(),
|
||||
disk: "disk".to_owned(),
|
||||
volume: "bucket".to_owned(),
|
||||
path: "part.1".to_owned(),
|
||||
offset: 0,
|
||||
length,
|
||||
stall_timeout: None,
|
||||
};
|
||||
Box::new(NixlChunkReader::new(Arc::new(VecPool), request, 1))
|
||||
}
|
||||
@@ -21,7 +21,7 @@ use crate::cluster::rpc::{set_tonic_canonical_body_digest, set_tonic_mutation_bo
|
||||
use crate::error::{Error, Result};
|
||||
use crate::storage_api_contracts::internode::{
|
||||
SCANNER_ACTIVITY_LEGACY_PROTOCOL_VERSION, SCANNER_ACTIVITY_PREVIOUS_PROTOCOL_VERSION, SCANNER_ACTIVITY_PROTOCOL_VERSION,
|
||||
SCANNER_ACTIVITY_V6_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES,
|
||||
SCANNER_ACTIVITY_V6_PROTOCOL_VERSION, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES,
|
||||
SCANNER_DIRTY_USAGE_SNAPSHOT_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_RPC_MAX_MESSAGE_SIZE,
|
||||
};
|
||||
use crate::{
|
||||
@@ -192,6 +192,7 @@ fn validate_signal_service_protocol(sig: u64, sub_sys: &str, protocol_version: u
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ScannerPeerActivity {
|
||||
pub instance_id: String,
|
||||
pub checkpoint_instance_id: Option<String>,
|
||||
pub namespace_generation: u64,
|
||||
pub maintenance_generation: u64,
|
||||
pub protocol_version: u32,
|
||||
@@ -354,6 +355,9 @@ fn decode_scanner_activity_with_verifier(
|
||||
challenge: &[u8; 16],
|
||||
verify_proof: impl FnOnce(&[u8], &[u8]) -> Result<()>,
|
||||
) -> Result<ScannerPeerActivity> {
|
||||
if response.protocol_version != SCANNER_ACTIVITY_PROTOCOL_VERSION && response.checkpoint_instance_id.is_some() {
|
||||
return Err(Error::other("legacy scanner activity peer returned unauthenticated checkpoint identity"));
|
||||
}
|
||||
let instance_id = &response.instance_id;
|
||||
if !scanner_instance_id_is_valid(instance_id) {
|
||||
return Err(Error::other("peer returned an invalid scanner activity instance ID"));
|
||||
@@ -423,7 +427,7 @@ fn decode_scanner_activity_with_verifier(
|
||||
None,
|
||||
)
|
||||
}
|
||||
SCANNER_ACTIVITY_PROTOCOL_VERSION => {
|
||||
SCANNER_ACTIVITY_V7_PROTOCOL_VERSION | SCANNER_ACTIVITY_PROTOCOL_VERSION => {
|
||||
if response.dirty_usage_pending && response.dirty_usage_generation == 0 {
|
||||
return Err(Error::other("scanner activity peer returned pending dirty usage without a generation"));
|
||||
}
|
||||
@@ -436,8 +440,20 @@ fn decode_scanner_activity_with_verifier(
|
||||
if movement_generation == u64::MAX {
|
||||
return Err(Error::other("scanner activity peer exhausted its movement generation"));
|
||||
}
|
||||
let canonical = rustfs_protos::canonical_scanner_activity_v7_response_body(challenge, &response)
|
||||
.map_err(|_| Error::other("scanner activity peer response is too large to authenticate"))?;
|
||||
let canonical = if response.protocol_version == SCANNER_ACTIVITY_PROTOCOL_VERSION {
|
||||
let instance = response
|
||||
.checkpoint_instance_id
|
||||
.as_deref()
|
||||
.filter(|instance| scanner_instance_id_is_valid(instance))
|
||||
.ok_or_else(|| Error::other("scanner activity peer omitted its checkpoint identity"))?;
|
||||
if instance.bytes().all(|byte| byte == b'0') {
|
||||
return Err(Error::other("scanner activity peer returned an empty checkpoint identity"));
|
||||
}
|
||||
rustfs_protos::canonical_scanner_activity_v8_response_body(challenge, &response)
|
||||
} else {
|
||||
rustfs_protos::canonical_scanner_activity_v7_response_body(challenge, &response)
|
||||
}
|
||||
.map_err(|_| Error::other("scanner activity peer response is too large to authenticate"))?;
|
||||
verify_proof(&canonical, &response.response_proof)?;
|
||||
(
|
||||
Some(
|
||||
@@ -458,6 +474,7 @@ fn decode_scanner_activity_with_verifier(
|
||||
};
|
||||
Ok(ScannerPeerActivity {
|
||||
instance_id: response.instance_id,
|
||||
checkpoint_instance_id: response.checkpoint_instance_id,
|
||||
namespace_generation: response.namespace_generation,
|
||||
maintenance_generation: response.maintenance_generation,
|
||||
protocol_version: response.protocol_version,
|
||||
@@ -2452,11 +2469,15 @@ impl PeerRestClient {
|
||||
.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_PROTOCOL_VERSION)
|
||||
.await;
|
||||
if result.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
|
||||
// A v6 peer cannot parse the v7 marker. Its authenticated
|
||||
// response is still decoded as untrusted terminal state, so the
|
||||
// scanner will defer publication until every peer is v7.
|
||||
self.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
|
||||
.await
|
||||
let previous = self
|
||||
.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION)
|
||||
.await;
|
||||
if previous.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
|
||||
self.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
|
||||
.await
|
||||
} else {
|
||||
previous
|
||||
}
|
||||
} else {
|
||||
result
|
||||
}
|
||||
@@ -2723,8 +2744,15 @@ impl PeerRestClient {
|
||||
.scanner_activity_request_with_protocol(instance_id.clone(), generation, SCANNER_ACTIVITY_PROTOCOL_VERSION)
|
||||
.await;
|
||||
if result.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
|
||||
self.scanner_activity_request_with_protocol(instance_id, generation, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
|
||||
.await
|
||||
let previous = self
|
||||
.scanner_activity_request_with_protocol(instance_id.clone(), generation, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION)
|
||||
.await;
|
||||
if previous.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
|
||||
self.scanner_activity_request_with_protocol(instance_id, generation, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
|
||||
.await
|
||||
} else {
|
||||
previous
|
||||
}
|
||||
} else {
|
||||
result
|
||||
}
|
||||
@@ -3680,6 +3708,7 @@ mod tests {
|
||||
#[test]
|
||||
fn scanner_scoped_dirty_usage_ack_reconciliation_requires_same_clean_instance() {
|
||||
let activity = |instance_id: &str, generation, pending| ScannerPeerActivity {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: instance_id.to_string(),
|
||||
namespace_generation: 1,
|
||||
maintenance_generation: 1,
|
||||
@@ -3961,9 +3990,44 @@ mod tests {
|
||||
.await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_checkpoint_identity_requires_v8_proof_and_preserves_rpc_epoch() {
|
||||
let response = ScannerActivityResponse {
|
||||
protocol_version: SCANNER_ACTIVITY_PROTOCOL_VERSION,
|
||||
instance_id: "1".repeat(32),
|
||||
checkpoint_instance_id: Some("2".repeat(32)),
|
||||
topology_digest: vec![7; 32].into(),
|
||||
movement_generation: Some(0),
|
||||
publication_blocked: Some(false),
|
||||
response_proof: b"proof".to_vec().into(),
|
||||
..Default::default()
|
||||
};
|
||||
let decoded = decode_test_scanner_activity(response.clone()).expect("authenticated v8");
|
||||
assert_eq!(decoded.instance_id, "1".repeat(32));
|
||||
assert_eq!(decoded.checkpoint_instance_id, Some("2".repeat(32)));
|
||||
for checkpoint_instance_id in [None, Some(String::new()), Some("0".repeat(32)), Some("A".repeat(32))] {
|
||||
let malformed = ScannerActivityResponse {
|
||||
checkpoint_instance_id,
|
||||
..response.clone()
|
||||
};
|
||||
assert!(decode_test_scanner_activity(malformed).is_err(), "invalid continuity must fail closed");
|
||||
}
|
||||
let v7 = ScannerActivityResponse {
|
||||
protocol_version: SCANNER_ACTIVITY_V7_PROTOCOL_VERSION,
|
||||
..response
|
||||
};
|
||||
assert!(decode_test_scanner_activity(v7.clone()).is_err(), "legacy proof does not bind continuity");
|
||||
let v7 = ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
..v7
|
||||
};
|
||||
assert!(decode_test_scanner_activity(v7).is_ok(), "v7 without continuity remains supported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_activity_requires_restart_safe_peer_identity() {
|
||||
let legacy = decode_test_scanner_activity(ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -3980,6 +4044,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
legacy,
|
||||
ScannerPeerActivity {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -3994,6 +4059,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let previous = decode_test_scanner_activity(ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4010,6 +4076,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
previous,
|
||||
ScannerPeerActivity {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4024,6 +4091,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let v6 = decode_test_scanner_activity(ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4042,6 +4110,7 @@ mod tests {
|
||||
assert_eq!(v6.dirty_usage_generation, Some(11));
|
||||
|
||||
let malformed_topology = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4062,6 +4131,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let missing_instance = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: String::new(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4082,6 +4152,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let malformed_instance = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "ABCDEF0123456789ABCDEF0123456789".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4102,6 +4173,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let activity = decode_test_scanner_activity(ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4118,6 +4190,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
activity,
|
||||
ScannerPeerActivity {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4132,6 +4205,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let missing_movement_generation = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4152,6 +4226,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let pending_without_generation = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4172,6 +4247,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let previous_with_dirty_usage = ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4192,6 +4268,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let legacy_with_topology = ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4212,6 +4289,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let unsupported_protocol = ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4232,6 +4310,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let missing_proof = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3507,6 +3507,7 @@ 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);
|
||||
assert!(
|
||||
repair(&fixture.store, &mut state, &fence).await.is_err(),
|
||||
"reconstruction alone must never authorize a COMMIT"
|
||||
);
|
||||
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_eq!(
|
||||
snapshots(&fixture.store).await,
|
||||
before,
|
||||
@@ -222,6 +222,24 @@ 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,6 +19,7 @@ use crate::disk::{
|
||||
PoolMetaNativeRecoveryResponse as Response,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures::TryStreamExt as _;
|
||||
|
||||
#[cfg(test)]
|
||||
#[derive(Default)]
|
||||
@@ -38,8 +39,16 @@ 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 {
|
||||
Error::other("native pool metadata recovery requires one proven V3 transaction and complete matching disk evidence")
|
||||
missing_evidence("inconsistent_evidence")
|
||||
}
|
||||
|
||||
fn known_validation(source: Error, phase: &'static str) -> Error {
|
||||
@@ -71,13 +80,19 @@ 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(invalid))
|
||||
.map(|snapshot| {
|
||||
snapshot
|
||||
.current
|
||||
.clone()
|
||||
.ok_or_else(|| missing_evidence("missing_pool_metadata_head"))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> Result<Vec<InspectedPool>> {
|
||||
let mut inspected = Vec::with_capacity(pools.len());
|
||||
// Pool -> disk order is stable; all capability probes precede every mutation.
|
||||
// Check every slot before starting I/O. The authenticated, read-only
|
||||
// Inspect RPC proves both protocol support and the disk's evidence.
|
||||
for pool in pools {
|
||||
fence.ensure_held()?;
|
||||
let set = pool.get_disks_by_key(POOL_META_NAME);
|
||||
@@ -87,20 +102,8 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
|
||||
.await
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|disk| disk.ok_or_else(invalid))
|
||||
.map(|disk| disk.ok_or_else(|| missing_evidence("missing_pool_metadata_slot")))
|
||||
.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(),
|
||||
@@ -108,7 +111,7 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
|
||||
}
|
||||
for pool in &mut inspected {
|
||||
fence.ensure_held()?;
|
||||
let results = futures::stream::iter(pool.disks.iter().cloned().map(|disk| async move {
|
||||
pool.snapshots = futures::stream::iter(pool.disks.iter().cloned().map(|disk| async move {
|
||||
match disk
|
||||
.pool_meta_native_recovery(Request::Inspect {
|
||||
object: PoolMetaNativeObject::PoolBin,
|
||||
@@ -116,15 +119,12 @@ async fn inspect(pools: &[Arc<Sets>], fence: &PoolMetaPersistenceFence<'_>) -> R
|
||||
.await?
|
||||
{
|
||||
Response::Inspected(snapshot) if !snapshot.disk_id.is_nil() => Ok(snapshot),
|
||||
_ => Err(invalid()),
|
||||
_ => Err(missing_evidence("invalid_disk_identity_evidence")),
|
||||
}
|
||||
}))
|
||||
.buffered(4)
|
||||
.collect::<Vec<Result<PoolMetaNativeInspection>>>()
|
||||
.await;
|
||||
for result in results {
|
||||
pool.snapshots.push(result?);
|
||||
}
|
||||
.try_collect()
|
||||
.await?;
|
||||
}
|
||||
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(invalid))
|
||||
.map(|disk| disk.ok_or_else(|| missing_evidence("missing_pool_identity_slot")))
|
||||
.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(invalid()),
|
||||
_ => Err(missing_evidence("invalid_disk_identity_evidence")),
|
||||
}
|
||||
}))
|
||||
.buffered(4)
|
||||
@@ -479,7 +479,7 @@ pub(super) async fn repair(
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if ordinary_commits.is_empty() && ordinary_prepares.is_empty() {
|
||||
return Err(invalid());
|
||||
return Err(missing_evidence("no_ordinary_v3_authority"));
|
||||
}
|
||||
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(invalid());
|
||||
return Err(missing_evidence("pool_identity_unavailable"));
|
||||
}
|
||||
let identity = select_pool_meta_identity(identities, cluster_id)
|
||||
.map_err(|error| latch_validation(state, known_validation(error, "native_identity_validation")))?;
|
||||
@@ -847,7 +847,10 @@ 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();
|
||||
assert!(plan(&f.pools, &f.commit, f.revision, &f.identity, None).await.is_err());
|
||||
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}");
|
||||
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());
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// 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,7 +14,12 @@
|
||||
|
||||
// #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;
|
||||
mod scan_progress;
|
||||
pub use scan_progress::load_bucket_scan_progress_for_admin;
|
||||
|
||||
use crate::storage_api_contracts::{
|
||||
bucket::{BucketOperations as _, BucketOptions},
|
||||
@@ -57,7 +62,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;
|
||||
const ADMIN_USAGE_INCARNATION_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
pub(crate) 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
|
||||
@@ -1463,45 +1468,43 @@ 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);
|
||||
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 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());
|
||||
}
|
||||
}
|
||||
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 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 incarnations = current_admin_bucket_incarnations(store, buckets.into_iter().collect(), deadline).await;
|
||||
response.project_bucket_observations_for_admin(&incarnations);
|
||||
Ok(response)
|
||||
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
|
||||
}
|
||||
|
||||
fn discard_incomplete_bucket_usage(data_usage_info: &mut DataUsageInfo) {
|
||||
@@ -1690,11 +1693,7 @@ async fn project_data_usage_from_backend_cached<T>(
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<DataUsageInfo, Error> {
|
||||
let ttl = Duration::from_secs(DATA_USAGE_CACHE_TTL_SECS);
|
||||
|
||||
loop {
|
||||
@@ -1743,6 +1742,38 @@ pub async fn load_admin_data_usage_from_backend_cached(store: Arc<ECStore>) -> R
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
@@ -2805,16 +2836,17 @@ 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) {
|
||||
async fn apply_bucket_usage_memory_overlay_if_authoritative(data_usage_info: &mut DataUsageInfo, authoritative: bool) -> bool {
|
||||
if !authoritative {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
let cache = memory_cache().read().await;
|
||||
if cache.is_empty() {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -2851,6 +2883,7 @@ 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) {
|
||||
@@ -3744,6 +3777,23 @@ 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),
|
||||
@@ -4279,7 +4329,11 @@ mod tests {
|
||||
use crate::config::com::save_config;
|
||||
|
||||
let (_dirs, store) = isolated_store_over_temp_disks().await;
|
||||
let (authoritative, observed) = usage_snapshots_with_missing_observed_set();
|
||||
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 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())
|
||||
@@ -4328,6 +4382,11 @@ 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(),
|
||||
@@ -4849,6 +4908,12 @@ 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),
|
||||
@@ -4871,6 +4936,11 @@ 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);
|
||||
@@ -4932,6 +5002,7 @@ 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(),
|
||||
@@ -4946,6 +5017,10 @@ 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);
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
use super::*;
|
||||
use crate::set_disk::SetDisks;
|
||||
use futures::{StreamExt, stream::BoxStream};
|
||||
use rustfs_data_usage::{
|
||||
BUCKET_SCAN_PROGRESS_MAX_BYTES, BucketScanProgress, BucketScanProgressSource, aggregate_bucket_scan_progress,
|
||||
bucket_scan_progress_path,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
type ProgressEvent = (String, BucketScanProgressSource);
|
||||
|
||||
async fn collect_progress_until<S: futures::Stream + Unpin>(deadline: tokio::time::Instant, mut stream: S) -> Vec<S::Item> {
|
||||
let mut collected = Vec::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = tokio::time::sleep_until(deadline) => break,
|
||||
item = stream.next() => match item {
|
||||
Some(item) => collected.push(item),
|
||||
None => break,
|
||||
},
|
||||
}
|
||||
}
|
||||
collected
|
||||
}
|
||||
|
||||
/// Read compact checkpoint companions only for the caller's authorized buckets.
|
||||
///
|
||||
/// These diagnostics cannot seed usage caches or authorize quotas. The request
|
||||
/// has a two-second deadline, reserving its last quarter for final movement-scope
|
||||
/// validation. Completed source reads survive stalled peers or buckets. Dropping
|
||||
/// the request cancels reads; it never lists objects or loads full scanner caches.
|
||||
pub async fn load_bucket_scan_progress_for_admin(
|
||||
store: Arc<ECStore>,
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
|
||||
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
async fn bucket_progress_sources(
|
||||
store: Arc<ECStore>,
|
||||
bucket: String,
|
||||
sets: Arc<Vec<Arc<SetDisks>>>,
|
||||
movement_generation: u64,
|
||||
) -> BoxStream<'static, ProgressEvent> {
|
||||
let Some(incarnation) = store
|
||||
.bucket_incarnation_id_from_disk(&bucket)
|
||||
.await
|
||||
.ok()
|
||||
.filter(|id| !id.is_nil())
|
||||
else {
|
||||
return futures::stream::empty().boxed();
|
||||
};
|
||||
let incarnation = incarnation.to_string();
|
||||
let path = bucket_scan_progress_path(&bucket);
|
||||
futures::stream::iter(0..sets.len())
|
||||
.map(move |index| {
|
||||
let set = sets[index].clone();
|
||||
let bucket = bucket.clone();
|
||||
let incarnation = incarnation.clone();
|
||||
let path = path.clone();
|
||||
async move {
|
||||
let bytes = crate::config::com::read_config_limited(set.clone(), &path, BUCKET_SCAN_PROGRESS_MAX_BYTES)
|
||||
.await
|
||||
.ok()?;
|
||||
let sample: BucketScanProgressSource = serde_json::from_slice(&bytes).ok()?;
|
||||
let source = (u64::try_from(set.pool_index).ok()?, u64::try_from(set.set_index).ok()?);
|
||||
let disks = set.format.erasure.sets.get(set.set_index).filter(|disks| !disks.is_empty())?;
|
||||
if set.format.id.is_nil() || disks.iter().any(uuid::Uuid::is_nil) {
|
||||
return None;
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(set.format.id.as_bytes());
|
||||
for disk in disks {
|
||||
digest.update(disk.as_bytes());
|
||||
}
|
||||
let layout: [u8; 32] = digest.finalize().into();
|
||||
(sample.matches(&bucket, &incarnation, source, movement_generation) && sample.set_layout == layout)
|
||||
.then_some((bucket, sample))
|
||||
}
|
||||
})
|
||||
.buffer_unordered(4)
|
||||
.filter_map(futures::future::ready)
|
||||
.boxed()
|
||||
}
|
||||
|
||||
fn project_progress_samples(
|
||||
samples: Vec<ProgressEvent>,
|
||||
expected: &[(u64, u64)],
|
||||
baseline: &DataUsageInfo,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let mut buckets = HashMap::<String, Vec<BucketScanProgressSource>>::new();
|
||||
for (bucket, sample) in samples {
|
||||
buckets.entry(bucket).or_default().push(sample);
|
||||
}
|
||||
buckets
|
||||
.into_iter()
|
||||
.filter_map(|(bucket, samples)| {
|
||||
if let Some(certification) = baseline
|
||||
.buckets_usage
|
||||
.get(&bucket)
|
||||
.and_then(|usage| usage.usage_certification)
|
||||
&& samples
|
||||
.iter()
|
||||
.all(|sample| (sample.scanner_epoch, sample.scanner_cycle) <= (certification.epoch, certification.cycle))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((bucket, aggregate_bucket_scan_progress(samples, expected)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn load_progress(
|
||||
store: Arc<ECStore>,
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
read_deadline: tokio::time::Instant,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let Some(epoch) = store.scanner_data_usage_publication_epoch().await else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let Some(movement_generation) = store.scanner_durable_data_movement_generation().await else {
|
||||
return HashMap::new();
|
||||
};
|
||||
let sets = Arc::new(store.all_set_disks());
|
||||
let mut expected = Vec::with_capacity(sets.len());
|
||||
for set in sets.iter() {
|
||||
let (Ok(pool), Ok(index)) = (u64::try_from(set.pool_index), u64::try_from(set.set_index)) else {
|
||||
return HashMap::new();
|
||||
};
|
||||
expected.push((pool, index));
|
||||
}
|
||||
expected.sort_unstable();
|
||||
if expected.windows(2).any(|pair| pair[0] >= pair[1]) {
|
||||
return HashMap::new();
|
||||
}
|
||||
// Emit each validated source immediately. A bucket waiting for another
|
||||
// source must not hide its healthy sample behind a whole-bucket future.
|
||||
let work = futures::stream::iter(buckets.iter().cloned())
|
||||
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
|
||||
.buffer_unordered(4)
|
||||
.flatten_unordered(4);
|
||||
let samples = collect_progress_until(read_deadline, work).await;
|
||||
let progress = project_progress_samples(samples, &expected, baseline);
|
||||
if store.scanner_data_usage_publication_epoch().await != Some(epoch)
|
||||
|| store.scanner_durable_data_movement_generation().await != Some(movement_generation)
|
||||
{
|
||||
return HashMap::new();
|
||||
}
|
||||
progress
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
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;
|
||||
use rustfs_data_usage::{BUCKET_SCAN_PROGRESS_VERSION, BucketScanStage};
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn display_progress_deadline_preserves_successes_beside_a_stalled_source() {
|
||||
use futures::FutureExt;
|
||||
let stream = futures::stream::iter([
|
||||
futures::future::ready(("partial", 7)).boxed(),
|
||||
futures::future::pending().boxed(),
|
||||
futures::future::ready(("healthy", 9)).boxed(),
|
||||
])
|
||||
.buffer_unordered(3);
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
let collected = collect_progress_until(deadline, stream).await;
|
||||
assert_eq!(collected.len(), 2, "a slow source must not erase completed samples or buckets");
|
||||
assert!(collected.contains(&("partial", 7)));
|
||||
assert!(collected.contains(&("healthy", 9)));
|
||||
assert_eq!(tokio::time::Instant::now(), deadline);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn display_progress_deadline_keeps_partial_sources_and_complete_buckets() {
|
||||
use futures::FutureExt;
|
||||
let sample = |bucket: &str, set_index, objects, complete| BucketScanProgressSource {
|
||||
version: BUCKET_SCAN_PROGRESS_VERSION,
|
||||
bucket: bucket.into(),
|
||||
bucket_incarnation: uuid::Uuid::from_u128(1).to_string(),
|
||||
pool_index: 0,
|
||||
set_index,
|
||||
set_layout: [1; 32],
|
||||
publication_epoch: 0,
|
||||
movement_generation: Some(0),
|
||||
scanner_epoch: 9,
|
||||
scanner_cycle: 11,
|
||||
updated_at: 1000,
|
||||
stage: if complete {
|
||||
BucketScanStage::Completed
|
||||
} else {
|
||||
BucketScanStage::Scanning
|
||||
},
|
||||
objects: Some(objects),
|
||||
size: Some(objects * 11),
|
||||
};
|
||||
let partial: BoxStream<'static, ProgressEvent> = futures::stream::iter([
|
||||
futures::future::ready(("partial".into(), sample("partial", 0, 7, false))).boxed(),
|
||||
futures::future::pending().boxed(),
|
||||
])
|
||||
.buffer_unordered(2)
|
||||
.boxed();
|
||||
let healthy: BoxStream<'static, ProgressEvent> = futures::stream::iter([
|
||||
("healthy".into(), sample("healthy", 0, 2, true)),
|
||||
("healthy".into(), sample("healthy", 1, 3, true)),
|
||||
])
|
||||
.boxed();
|
||||
// The third bucket never resolves its identity; one source of the
|
||||
// first bucket stalls. Neither may hide the other ready events.
|
||||
let events = futures::stream::iter([
|
||||
futures::future::ready(partial).boxed(),
|
||||
futures::future::ready(healthy).boxed(),
|
||||
futures::future::pending().boxed(),
|
||||
])
|
||||
.buffer_unordered(3)
|
||||
.flatten_unordered(3);
|
||||
let baseline = DataUsageInfo::default();
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
let progress = project_progress_samples(collect_progress_until(deadline, events).await, &[(0, 0), (0, 1)], &baseline);
|
||||
assert_eq!(progress.len(), 2);
|
||||
assert_eq!(progress["partial"].stage, BucketScanStage::AwaitingSources);
|
||||
assert_eq!((progress["partial"].objects, progress["partial"].size), (Some(7), Some(77)));
|
||||
assert_eq!((progress["partial"].sources_observed, progress["partial"].sources_total), (1, 2));
|
||||
assert_eq!(progress["healthy"].stage, BucketScanStage::Completed);
|
||||
assert_eq!((progress["healthy"].objects, progress["healthy"].size), (Some(5), Some(55)));
|
||||
assert!(baseline.buckets_usage.is_empty(), "partial diagnostics never seed certified totals");
|
||||
}
|
||||
|
||||
async fn fixture() -> (Vec<tempfile::TempDir>, Arc<ECStore>, BucketScanProgressSource) {
|
||||
let (dirs, store) = isolated_store_over_temp_disks().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
store
|
||||
.make_bucket("progress", &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create progress bucket");
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk("progress")
|
||||
.await
|
||||
.expect("current incarnation");
|
||||
let set = &store.pools[0].disk_set[0];
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(set.format.id.as_bytes());
|
||||
for disk in &set.format.erasure.sets[set.set_index] {
|
||||
digest.update(disk.as_bytes());
|
||||
}
|
||||
let sample = BucketScanProgressSource {
|
||||
version: BUCKET_SCAN_PROGRESS_VERSION,
|
||||
bucket: "progress".into(),
|
||||
bucket_incarnation: incarnation.to_string(),
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
set_layout: digest.finalize().into(),
|
||||
publication_epoch: store.scanner_data_usage_publication_epoch().await.expect("publication epoch"),
|
||||
movement_generation: store.scanner_durable_data_movement_generation().await,
|
||||
scanner_epoch: 9,
|
||||
scanner_cycle: 11,
|
||||
updated_at: 1000,
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(71),
|
||||
};
|
||||
(dirs, store, sample)
|
||||
}
|
||||
|
||||
async fn save(store: &ECStore, sample: &BucketScanProgressSource) {
|
||||
save_config(
|
||||
store.pools[0].disk_set[0].clone(),
|
||||
&bucket_scan_progress_path("progress"),
|
||||
serde_json::to_vec(sample).expect("encode display sample"),
|
||||
)
|
||||
.await
|
||||
.expect("persist display sample on its source set");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn display_progress_reloads_from_shared_storage_without_promoting_usage() {
|
||||
fn assert_send<T: Send>(value: T) -> T {
|
||||
value
|
||||
}
|
||||
let (_dirs, store, mut sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let baseline = DataUsageInfo::default();
|
||||
for _ in 0..3 {
|
||||
let progress = assert_send(load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &baseline)).await;
|
||||
assert_eq!((progress["progress"].objects, progress["progress"].size), (Some(7), Some(71)));
|
||||
assert_eq!(progress["progress"].sources_observed, 1);
|
||||
assert!(baseline.buckets_usage.is_empty(), "display samples never seed exact usage");
|
||||
assert!(!baseline.is_complete_bucket_usage_snapshot());
|
||||
}
|
||||
// Another node/restarted reader may have a different admission epoch
|
||||
// and wakeup count without any persisted movement-state change.
|
||||
let gate = store.ctx.data_movement_operation_gate();
|
||||
let permit = gate.write().await;
|
||||
store.ctx.advance_data_movement_operation_epoch();
|
||||
drop(permit);
|
||||
assert_ne!(store.scanner_data_usage_publication_epoch().await, Some(sample.publication_epoch));
|
||||
assert_ne!(Some(store.scanner_data_movement_generation()), sample.movement_generation);
|
||||
let other_reader = load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &baseline).await;
|
||||
assert_eq!(
|
||||
other_reader["progress"].objects,
|
||||
Some(7),
|
||||
"local reader counters cannot hide shared progress"
|
||||
);
|
||||
sample.scanner_epoch += 1;
|
||||
sample.scanner_cycle += 1;
|
||||
sample.objects = Some(9);
|
||||
sample.size = Some(91);
|
||||
save(&store, &sample).await;
|
||||
let after_handoff = load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &baseline).await;
|
||||
assert_eq!((after_handoff["progress"].objects, after_handoff["progress"].size), (Some(9), Some(91)));
|
||||
assert!(
|
||||
load_bucket_scan_progress_for_admin(store, &[], &baseline).await.is_empty(),
|
||||
"no unauthorized bucket probes"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn display_progress_rejects_retired_identity_layout_epoch_and_corrupt_samples() {
|
||||
let (_dirs, store, sample) = fixture().await;
|
||||
for invalid in 0..6 {
|
||||
let mut stale = sample.clone();
|
||||
match invalid {
|
||||
0 => stale.bucket_incarnation = uuid::Uuid::new_v4().to_string(),
|
||||
1 => stale.set_layout = [0; 32],
|
||||
2 => stale.movement_generation = Some(stale.movement_generation.expect("shared generation") + 1),
|
||||
3 => stale.version += 1,
|
||||
4 => stale.movement_generation = None,
|
||||
_ => stale.size = None,
|
||||
}
|
||||
save(&store, &stale).await;
|
||||
assert!(
|
||||
load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &DataUsageInfo::default())
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
let path = bucket_scan_progress_path("progress");
|
||||
for bytes in [b"invalid json".to_vec(), vec![b' '; BUCKET_SCAN_PROGRESS_MAX_BYTES + 1]] {
|
||||
save_config(store.pools[0].disk_set[0].clone(), &path, bytes)
|
||||
.await
|
||||
.expect("persist malformed diagnostic fixture");
|
||||
assert!(
|
||||
load_bucket_scan_progress_for_admin(store.clone(), &["progress".into()], &DataUsageInfo::default())
|
||||
.await
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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_keeps_canonical_without_delaying_healthy_buckets() {
|
||||
async fn blocked_companion_identity_stays_unknown_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,8 +280,11 @@ async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buc
|
||||
.await
|
||||
.expect("optional projection must return before the blocked metadata lock's long timeout")
|
||||
.expect("canonical admin response stays available");
|
||||
assert_eq!(response.buckets_usage[blocked].size, 100);
|
||||
assert_eq!(response.buckets_usage[blocked].usage_value_state, Some(BucketUsageValueState::Carried));
|
||||
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[healthy].size, 250);
|
||||
assert_eq!(response.buckets_usage[healthy].usage_value_state, Some(BucketUsageValueState::Observed));
|
||||
assert!(response.usage_snapshot_admin_projection);
|
||||
@@ -293,13 +296,12 @@ async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buc
|
||||
.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 the next refresh"
|
||||
"unavailable identity can recover on a cache hit"
|
||||
);
|
||||
assert_eq!(recovered.buckets_usage[healthy].size, 250);
|
||||
let quota = load_data_usage_from_backend_cached(store)
|
||||
@@ -308,3 +310,331 @@ async fn blocked_companion_identity_keeps_canonical_without_delaying_healthy_buc
|
||||
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,6 +50,8 @@ 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);
|
||||
@@ -276,6 +278,14 @@ 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;
|
||||
@@ -301,25 +311,24 @@ pub async fn get_server_info(get_pools: bool) -> InfoMessage {
|
||||
|
||||
if let Some(store) = runtime_sources::object_store_handle() {
|
||||
mode = ITEM_ONLINE;
|
||||
apply_data_usage_result(
|
||||
load_server_info_usage_snapshot(store.clone()).await,
|
||||
&mut buckets,
|
||||
&mut objects,
|
||||
&mut versions,
|
||||
&mut delete_markers,
|
||||
&mut usage,
|
||||
);
|
||||
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);
|
||||
if buckets.error.is_some() {
|
||||
apply_bucket_namespace_count(
|
||||
store
|
||||
.list_bucket_for_scanner(&BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await,
|
||||
&mut buckets,
|
||||
);
|
||||
let listing = inventory::namespace_or_fallback(namespace, store.list_bucket_for_scanner(&namespace_options)).await;
|
||||
apply_bucket_namespace_count(listing, &mut buckets);
|
||||
}
|
||||
|
||||
let backend_info = StorageAdminApi::backend_info(store.as_ref()).await;
|
||||
@@ -375,7 +384,7 @@ pub async fn get_server_info(get_pools: bool) -> InfoMessage {
|
||||
);
|
||||
}
|
||||
|
||||
InfoMessage {
|
||||
let info = InfoMessage {
|
||||
mode: Some(mode.to_string()),
|
||||
domain: None,
|
||||
region: None,
|
||||
@@ -390,7 +399,8 @@ pub async fn get_server_info(get_pools: bool) -> InfoMessage {
|
||||
services: Some(services),
|
||||
servers: Some(servers),
|
||||
pools: Some(pools),
|
||||
}
|
||||
};
|
||||
(info, inventory)
|
||||
}
|
||||
|
||||
fn is_online_drive_state(state: &str) -> bool {
|
||||
@@ -1033,16 +1043,26 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn server_info_reads_complete_observation_without_promoting_authority() {
|
||||
use crate::bucket::metadata_sys::test_support::isolated_store_over_temp_disks;
|
||||
use crate::bucket::metadata_sys::{init_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),
|
||||
@@ -1066,6 +1086,7 @@ mod tests {
|
||||
versions_count: 4,
|
||||
delete_markers_count: 1,
|
||||
size: 6,
|
||||
bucket_incarnation: Some(incarnation.to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
@@ -1117,6 +1138,46 @@ 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();
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@
|
||||
use crate::disk::cleanup_runtime;
|
||||
use crate::disk::io_admission::{
|
||||
AdmissionReader, BoxedChunkReader, DiskIoAdmission, DiskIoClass, DiskIoContext, current_disk_io_context,
|
||||
current_resource_unit, with_disk_io_context, with_disk_io_permit, with_optional_resource_unit,
|
||||
current_resource_unit, with_detached_disk_io_context, with_disk_io_context, with_disk_io_permit, with_optional_resource_unit,
|
||||
};
|
||||
use crate::disk::{
|
||||
CheckPartsResp, DataDirDeleteStatus, DeleteOptions, DiskAPI, DiskError, DiskInfo, DiskInfoOptions, DiskLocation, Endpoint,
|
||||
@@ -479,10 +479,13 @@ where
|
||||
if external_guard.is_none() {
|
||||
return operation().await;
|
||||
}
|
||||
tokio::spawn(with_optional_resource_unit(current_resource_unit(), async move {
|
||||
let _external_guard = external_guard;
|
||||
operation().await
|
||||
}))
|
||||
tokio::spawn(with_optional_resource_unit(
|
||||
current_resource_unit(),
|
||||
with_detached_disk_io_context(async move {
|
||||
let _external_guard = external_guard;
|
||||
operation().await
|
||||
}),
|
||||
))
|
||||
.await
|
||||
.map_err(|_| Error::other("owned mutation task failed"))?
|
||||
}
|
||||
@@ -1628,6 +1631,8 @@ 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.
|
||||
@@ -1781,6 +1786,7 @@ 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(),
|
||||
};
|
||||
@@ -1828,6 +1834,7 @@ impl LocalDiskWrapper {
|
||||
current_disk_io_context().unwrap_or_else(|| DiskIoContext {
|
||||
class: DiskIoClass::Foreground,
|
||||
cancellation: CancellationToken::new(),
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: current_resource_unit(),
|
||||
@@ -1869,29 +1876,9 @@ impl LocalDiskWrapper {
|
||||
}
|
||||
|
||||
async fn acquire_disk_io_permit(&self) -> Result<Option<crate::disk::io_admission::DiskIoPermit>> {
|
||||
if let Some(context) = current_disk_io_context() {
|
||||
if let Some(permit) = context.permit
|
||||
&& permit.is_for(&self.io_admission)
|
||||
{
|
||||
return Ok(Some(permit));
|
||||
}
|
||||
if context
|
||||
.admission
|
||||
.as_ref()
|
||||
.is_some_and(|admission| Arc::ptr_eq(admission, &self.io_admission))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
if context.class == DiskIoClass::Background {
|
||||
return self
|
||||
.io_admission
|
||||
.background(&context.cancellation)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(DiskError::Io);
|
||||
}
|
||||
}
|
||||
Ok(Some(self.io_admission.foreground()))
|
||||
crate::disk::io_admission::acquire_wrapper_disk_io_permit(&self.io_admission)
|
||||
.await
|
||||
.map_err(DiskError::Io)
|
||||
}
|
||||
|
||||
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
|
||||
@@ -1988,6 +1975,11 @@ 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;
|
||||
@@ -2463,7 +2455,14 @@ 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)>> {
|
||||
) -> Result<
|
||||
Option<(
|
||||
crate::disk::DeleteRecoveryJournal,
|
||||
bool,
|
||||
bool,
|
||||
Option<super::local::delete_recovery::LocalPublishedDeleteState>,
|
||||
)>,
|
||||
> {
|
||||
self.track_disk_health_mutation(
|
||||
"settle_delete_transaction",
|
||||
DiskMetricMutation::Delete,
|
||||
@@ -2479,6 +2478,7 @@ impl LocalDiskWrapper {
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn try_finish_and_finalize_prepared_delete_local(
|
||||
&self,
|
||||
volume: &str,
|
||||
@@ -2487,6 +2487,7 @@ 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",
|
||||
@@ -2501,6 +2502,7 @@ impl LocalDiskWrapper {
|
||||
journal,
|
||||
namespace_owner,
|
||||
work_budget,
|
||||
published_state,
|
||||
)
|
||||
.await
|
||||
})
|
||||
@@ -2985,6 +2987,7 @@ impl DiskAPI for LocalDiskWrapper {
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<()> {
|
||||
self.retired.cancel();
|
||||
self.stop_monitoring().await;
|
||||
self.disk.close().await
|
||||
}
|
||||
@@ -4409,6 +4412,29 @@ mod tests {
|
||||
assert!(matches!(wrapper.read_all(volume, &body_path).await, Err(DiskError::FileNotFound)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owned_mutation_retains_background_class_without_waiter_cancellation() {
|
||||
let cancellation = CancellationToken::new();
|
||||
let caller = cancellation.clone();
|
||||
let guard: Arc<dyn Send + Sync> = Arc::new(());
|
||||
crate::disk::with_background_disk_io(
|
||||
cancellation,
|
||||
run_owned_mutation(Some(guard), move || async move {
|
||||
caller.cancel();
|
||||
let context = current_disk_io_context().expect("publication owner retains background class");
|
||||
assert_eq!(context.class, DiskIoClass::Background);
|
||||
assert!(!context.cancellation.is_cancelled(), "waiter cancellation must not interrupt publication");
|
||||
assert!(
|
||||
context.admission_deadline.is_some(),
|
||||
"queued publication must retain a bounded admission lifetime"
|
||||
);
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("owned publication completes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owned_mutation_keeps_publication_guard_after_waiter_cancellation() {
|
||||
use rustfs_concurrency::adaptive::AdaptiveAdmission;
|
||||
|
||||
@@ -139,7 +139,17 @@ 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 => std::fs::create_dir_all(path),
|
||||
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) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,11 +161,24 @@ pub(crate) enum DiskIoClass {
|
||||
pub(crate) struct DiskIoContext {
|
||||
pub(crate) class: DiskIoClass,
|
||||
pub(crate) cancellation: CancellationToken,
|
||||
pub(crate) admission_deadline: Option<Instant>,
|
||||
pub(crate) admission: Option<Arc<DiskIoAdmission>>,
|
||||
pub(crate) permit: Option<DiskIoPermit>,
|
||||
pub(crate) resource_unit: Option<ResourceIoUnit>,
|
||||
}
|
||||
|
||||
impl DiskIoContext {
|
||||
pub(crate) async fn background_permit(&self, admission: &Arc<DiskIoAdmission>) -> io::Result<DiskIoPermit> {
|
||||
let acquire = admission.background_with_resource(&self.cancellation, self.resource_unit.clone());
|
||||
match self.admission_deadline {
|
||||
Some(deadline) => tokio::time::timeout_at(deadline, acquire)
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "owned background disk admission timed out"))?,
|
||||
None => acquire.await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark disk I/O issued by `future` as background work for local-disk admission.
|
||||
#[doc(hidden)]
|
||||
pub async fn with_background_disk_io<F: Future>(cancellation: CancellationToken, future: F) -> F::Output {
|
||||
@@ -173,6 +186,7 @@ pub async fn with_background_disk_io<F: Future>(cancellation: CancellationToken,
|
||||
DiskIoContext {
|
||||
class: DiskIoClass::Background,
|
||||
cancellation,
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: current_resource_unit(),
|
||||
@@ -245,6 +259,7 @@ pub(crate) async fn with_disk_io_permit<F: Future>(permit: Option<DiskIoPermit>,
|
||||
let mut context = current_disk_io_context().unwrap_or_else(|| DiskIoContext {
|
||||
class: DiskIoClass::Foreground,
|
||||
cancellation: CancellationToken::new(),
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: None,
|
||||
@@ -279,35 +294,122 @@ pub(crate) fn with_optional_disk_io_context<F: Future>(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_disk_io_context() -> Option<DiskIoContext> {
|
||||
DISK_IO_CONTEXT
|
||||
#[cfg(test)]
|
||||
tokio::task_local! {
|
||||
static TEST_CONTEXT_CLONES: std::sync::atomic::AtomicUsize;
|
||||
}
|
||||
|
||||
fn clone_context_with_current_resource_unit(context: &DiskIoContext) -> DiskIoContext {
|
||||
#[cfg(test)]
|
||||
let _ = TEST_CONTEXT_CLONES.try_with(|c| c.fetch_add(1, Ordering::Relaxed));
|
||||
let mut cloned = context.clone();
|
||||
if let Ok(unit) = RESOURCE_IO_UNIT.try_with(Clone::clone) {
|
||||
cloned.resource_unit = Some(unit);
|
||||
}
|
||||
cloned
|
||||
}
|
||||
|
||||
/// An owned commit outlives its waiter. Retain an outer I/O class and physical
|
||||
/// ownership, but give admission its own cancellation lifetime. Leave per-disk
|
||||
/// scopes to the caller's existing ownership handoff: inheriting their class
|
||||
/// without a lease could wait behind the parent awaiting this commit.
|
||||
/// The drive timeout bounds only queued admission; an admitted mutation still
|
||||
/// drains to completion. Nested owners retain the original admission deadline.
|
||||
pub(crate) fn with_detached_disk_io_context<F: Future>(future: F) -> impl Future<Output = F::Output> {
|
||||
let context = DISK_IO_CONTEXT
|
||||
.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
|
||||
(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();
|
||||
async move {
|
||||
match context {
|
||||
Some(context) => with_disk_io_context(context, future).await,
|
||||
None => future.await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_disk_io_context() -> Option<DiskIoContext> {
|
||||
DISK_IO_CONTEXT.try_with(clone_context_with_current_resource_unit).ok()
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_wrapper_disk_io_permit(admission: &Arc<DiskIoAdmission>) -> io::Result<Option<DiskIoPermit>> {
|
||||
enum WrapperPermitAction {
|
||||
Immediate(Option<DiskIoPermit>),
|
||||
Background(DiskIoContext),
|
||||
}
|
||||
|
||||
let action = match DISK_IO_CONTEXT.try_with(|context| {
|
||||
if let Some(permit) = context.permit.as_ref()
|
||||
&& permit.is_for(admission)
|
||||
{
|
||||
return WrapperPermitAction::Immediate(Some(permit.clone()));
|
||||
}
|
||||
if context
|
||||
.admission
|
||||
.as_ref()
|
||||
.is_some_and(|ctx_admission| Arc::ptr_eq(ctx_admission, admission))
|
||||
{
|
||||
return WrapperPermitAction::Immediate(None);
|
||||
}
|
||||
match context.class {
|
||||
DiskIoClass::Foreground => WrapperPermitAction::Immediate(Some(admission.foreground())),
|
||||
DiskIoClass::Background => WrapperPermitAction::Background(clone_context_with_current_resource_unit(context)),
|
||||
}
|
||||
}) {
|
||||
Ok(action) => action,
|
||||
Err(_) => return Ok(Some(admission.foreground())),
|
||||
};
|
||||
|
||||
match action {
|
||||
WrapperPermitAction::Immediate(permit) => Ok(permit),
|
||||
WrapperPermitAction::Background(context) => context.background_permit(admission).await.map(Some),
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire one low-level permit only when the current walker explicitly owns a gate.
|
||||
/// Ordinary wrapper calls use their outer operation permit instead.
|
||||
pub(crate) async fn acquire_context_disk_io_permit() -> io::Result<Option<DiskIoPermit>> {
|
||||
let Some(context) = current_disk_io_context() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(admission) = context.admission else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(permit) = context.permit
|
||||
&& permit.is_for(&admission)
|
||||
{
|
||||
return Ok(Some(permit));
|
||||
enum ContextPermitAction {
|
||||
Immediate(Option<DiskIoPermit>),
|
||||
Background(Arc<DiskIoAdmission>, DiskIoContext),
|
||||
}
|
||||
match context.class {
|
||||
DiskIoClass::Foreground => Ok(Some(admission.foreground())),
|
||||
DiskIoClass::Background => Ok(Some(admission.background(&context.cancellation).await?)),
|
||||
|
||||
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),
|
||||
};
|
||||
|
||||
match action {
|
||||
ContextPermitAction::Immediate(permit) => Ok(permit),
|
||||
ContextPermitAction::Background(admission, context) => context.background_permit(&admission).await.map(Some),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,6 +483,7 @@ impl DiskIoAdmission {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn background(self: &Arc<Self>, cancellation: &CancellationToken) -> std::io::Result<DiskIoPermit> {
|
||||
self.background_with_resource(cancellation, current_resource_unit()).await
|
||||
}
|
||||
@@ -663,11 +766,8 @@ impl<R> AdmissionReader<R> {
|
||||
let mut wait = self.wait.lock().unwrap_or_else(|error| error.into_inner());
|
||||
if wait.is_none() {
|
||||
let admission = self.admission.clone();
|
||||
let cancellation = self.context.cancellation.clone();
|
||||
let resource_unit = self.context.resource_unit.clone();
|
||||
*wait = Some(Box::pin(
|
||||
async move { admission.background_with_resource(&cancellation, resource_unit).await },
|
||||
));
|
||||
let context = self.context.clone();
|
||||
*wait = Some(Box::pin(async move { context.background_permit(&admission).await }));
|
||||
}
|
||||
let Some(wait_future) = wait.as_mut() else {
|
||||
return Poll::Ready(Err(io::Error::other("background disk I/O admission waiter is missing")));
|
||||
@@ -909,6 +1009,7 @@ mod tests {
|
||||
let existing = DiskIoContext {
|
||||
class: DiskIoClass::Foreground,
|
||||
cancellation: cancellation.clone(),
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: None,
|
||||
@@ -954,6 +1055,94 @@ mod tests {
|
||||
assert_eq!(gate.snapshot().active, 0);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn detached_commit_keeps_background_admission_after_waiter_cancellation() {
|
||||
let admission = DiskIoAdmission::new("detached-commit".to_string());
|
||||
let foreground = admission.foreground();
|
||||
let cancellation = CancellationToken::new();
|
||||
let worker_admission = admission.clone();
|
||||
with_background_disk_io(cancellation.clone(), async {
|
||||
let worker = tokio::spawn(with_detached_disk_io_context(async move {
|
||||
let context = current_disk_io_context().expect("owned commit retains its class");
|
||||
assert_eq!(context.class, DiskIoClass::Background);
|
||||
context.background_permit(&worker_admission).await
|
||||
}));
|
||||
wait_for_background_waiters(&admission, 1).await;
|
||||
cancellation.cancel();
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!worker.is_finished(), "caller cancellation must not abandon a queued commit");
|
||||
drop(foreground);
|
||||
let permit = tokio::time::timeout(Duration::from_secs(1), worker)
|
||||
.await
|
||||
.expect("commit admission should finish after foreground work")
|
||||
.expect("owned worker joins")
|
||||
.expect("owned commit survives waiter cancellation");
|
||||
assert_eq!(admission.background_admissions_for_tests(), 1);
|
||||
drop(permit);
|
||||
})
|
||||
.await;
|
||||
assert!(!admission.background_active_for_tests());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detached_commit_does_not_inherit_a_parent_disk_lease() {
|
||||
let admission = DiskIoAdmission::new("parent-lease".to_string());
|
||||
let cancellation = CancellationToken::new();
|
||||
let permit = admission.background(&cancellation).await.expect("parent disk admission");
|
||||
with_background_disk_io(
|
||||
cancellation,
|
||||
with_disk_io_permit(Some(permit), async {
|
||||
tokio::spawn(with_detached_disk_io_context(async {
|
||||
assert!(current_disk_io_context().is_none(), "do not queue behind the parent's disk lease");
|
||||
}))
|
||||
.await
|
||||
.expect("resource-only commit joins while parent keeps its disk lease");
|
||||
assert!(admission.background_active_for_tests());
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert!(!admission.background_active_for_tests());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn detached_commit_bounds_queued_admission_without_extending_an_existing_deadline() {
|
||||
let admission = DiskIoAdmission::new("stalled-background-disk");
|
||||
let held = admission
|
||||
.background(&CancellationToken::new())
|
||||
.await
|
||||
.expect("existing native I/O");
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
let worker_admission = admission.clone();
|
||||
let error = with_background_disk_io(CancellationToken::new(), async {
|
||||
let mut context = current_disk_io_context().expect("background scope");
|
||||
context.admission_deadline = Some(deadline);
|
||||
with_disk_io_context(context, async {
|
||||
let worker = tokio::spawn(with_detached_disk_io_context(async move {
|
||||
let context = current_disk_io_context().expect("owned scope");
|
||||
assert_eq!(
|
||||
context.admission_deadline,
|
||||
Some(deadline),
|
||||
"nested ownership must not reset admission time"
|
||||
);
|
||||
context.background_permit(&worker_admission).await
|
||||
}));
|
||||
wait_for_background_waiters(&admission, 1).await;
|
||||
tokio::time::advance(Duration::from_secs(2)).await;
|
||||
worker
|
||||
.await
|
||||
.expect("owned admission worker")
|
||||
.expect_err("stalled disk must not retain queued commit")
|
||||
})
|
||||
.await
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
assert_eq!(admission.background_waiters.load(Ordering::Acquire), 0);
|
||||
assert!(admission.background_active_for_tests(), "timeout must not interrupt admitted native I/O");
|
||||
drop(held);
|
||||
assert!(!admission.background_active_for_tests());
|
||||
}
|
||||
|
||||
struct BlockingWorker(tokio::task::JoinHandle<()>);
|
||||
|
||||
async fn wait_for_background_waiters(admission: &DiskIoAdmission, expected: usize) {
|
||||
@@ -1072,6 +1261,7 @@ mod tests {
|
||||
DiskIoContext {
|
||||
class: DiskIoClass::Foreground,
|
||||
cancellation: CancellationToken::new(),
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: None,
|
||||
@@ -1142,4 +1332,124 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,12 +79,21 @@ impl BackgroundMemoryBudget {
|
||||
pub(crate) fn reserve(self: &Arc<Self>, bytes: usize) -> io::Result<Reservation> {
|
||||
let bytes = u64::try_from(bytes).map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?;
|
||||
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let used = state
|
||||
.used
|
||||
.checked_add(bytes)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::WouldBlock, BackgroundMemoryExhausted))?;
|
||||
if bytes != 0 && (Instant::now() >= state.valid_until || used > state.limit) {
|
||||
return Err(io::Error::new(io::ErrorKind::WouldBlock, BackgroundMemoryExhausted));
|
||||
let expired = Instant::now() >= state.valid_until;
|
||||
let exhausted = || {
|
||||
io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
BackgroundMemoryExhausted {
|
||||
requested: bytes,
|
||||
used: state.used,
|
||||
limit: state.limit,
|
||||
expired,
|
||||
},
|
||||
)
|
||||
};
|
||||
let used = state.used.checked_add(bytes).ok_or_else(exhausted)?;
|
||||
if bytes != 0 && (expired || used > state.limit) {
|
||||
return Err(exhausted());
|
||||
}
|
||||
state.used = used;
|
||||
Ok(Reservation {
|
||||
@@ -95,11 +104,20 @@ impl BackgroundMemoryBudget {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct BackgroundMemoryExhausted;
|
||||
struct BackgroundMemoryExhausted {
|
||||
requested: u64,
|
||||
used: u64,
|
||||
limit: u64,
|
||||
expired: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BackgroundMemoryExhausted {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("background buffer memory budget exhausted")
|
||||
write!(
|
||||
formatter,
|
||||
"background buffer memory budget exhausted (requested={}, used={}, limit={}, expired={})",
|
||||
self.requested, self.used, self.limit, self.expired,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,6 +339,31 @@ impl io::Write for BackgroundEncodeBuffer {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn rejected_reservation_reports_capacity_and_expiration_without_charging() {
|
||||
let owner = BackgroundMemoryBudget::new();
|
||||
owner.set_sampled_limit(64, Duration::from_secs(3));
|
||||
let held = owner.reserve(32).expect("initial reservation fits");
|
||||
let error = owner.reserve(33).err().expect("one byte over remaining capacity");
|
||||
assert!(is_memory_pressure(&error));
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"background buffer memory budget exhausted (requested=33, used=32, limit=64, expired=false)"
|
||||
);
|
||||
assert_eq!(owner.snapshot().used, 32);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(3)).await;
|
||||
let error = owner.reserve(1).err().expect("expired lease rejects a fitting request");
|
||||
assert!(is_memory_pressure(&error));
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"background buffer memory budget exhausted (requested=1, used=32, limit=64, expired=true)"
|
||||
);
|
||||
assert_eq!(owner.snapshot().used, 32);
|
||||
drop(held);
|
||||
assert_eq!(owner.snapshot().used, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_buffer_growth_retains_both_allocations_and_the_last_slice() {
|
||||
use std::io::Write;
|
||||
|
||||
@@ -140,6 +140,28 @@ pub(crate) fn admit(binding: &PhysicalDiskBinding) -> io::Result<()> {
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
/// Wait only at the namespace RPC entry, before storage locks or native I/O.
|
||||
/// The caller owns the deadline; dropping this future releases its queue turn.
|
||||
pub(crate) async fn admit_scanner_preflight(binding: &PhysicalDiskBinding) -> io::Result<()> {
|
||||
let node = REMOTE_RESOURCES
|
||||
.try_with(|context| context.admitted.borrow().is_none().then(|| context.node.clone()))
|
||||
.ok()
|
||||
.flatten();
|
||||
let Some(node) = node else {
|
||||
return admit(binding);
|
||||
};
|
||||
let deferred = || io::Error::from(io::ErrorKind::WouldBlock);
|
||||
let plan = binding.plan().ok_or_else(deferred)?;
|
||||
let permit = plan.acquire(&node).await.ok_or_else(deferred)?;
|
||||
REMOTE_RESOURCES.with(|context| {
|
||||
let mut admitted = context.admitted.borrow_mut();
|
||||
if admitted.is_none() {
|
||||
*admitted = Some(permit);
|
||||
}
|
||||
});
|
||||
admit(binding)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -162,6 +184,76 @@ mod tests {
|
||||
node
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn scanner_preflight_cancellation_and_timeout_release_queued_capacity() {
|
||||
let node = node();
|
||||
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
|
||||
let binding = PhysicalDiskBinding::default();
|
||||
binding.set_test_capacity(vec![gate.clone()]).expect("device plan");
|
||||
for deadline in [false, true] {
|
||||
let held = gate.try_acquire().expect("concurrent disk operation");
|
||||
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
|
||||
let mut wait = Box::pin(admit_scanner_preflight(&binding));
|
||||
assert!(futures_util::poll!(&mut wait).is_pending());
|
||||
assert_eq!(node.snapshot().active, 0, "queued disk work cannot reserve node capacity");
|
||||
if deadline {
|
||||
assert!(tokio::time::timeout(std::time::Duration::from_secs(1), wait).await.is_err());
|
||||
} else {
|
||||
drop(wait);
|
||||
}
|
||||
drop(held);
|
||||
admit(&binding).expect("cancelled queue turn cannot block the immediate path");
|
||||
})
|
||||
.await;
|
||||
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
|
||||
assert_eq!([node.completed(), gate.completed()], [Some(0), Some(0)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scanner_preflight_rejects_a_plan_replaced_while_waiting() {
|
||||
let node = node();
|
||||
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
|
||||
let binding = PhysicalDiskBinding::default();
|
||||
binding.set_test_capacity(vec![gate.clone()]).expect("old plan");
|
||||
let held = gate.try_acquire().expect("busy disk");
|
||||
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
|
||||
let wait = admit_scanner_preflight(&binding);
|
||||
tokio::pin!(wait);
|
||||
assert!(futures_util::poll!(&mut wait).is_pending());
|
||||
binding
|
||||
.set_test_capacity(vec![AdaptiveAdmission::new(NonZeroU16::MIN, 1)])
|
||||
.expect("new plan");
|
||||
drop(held);
|
||||
assert_eq!(wait.await.expect_err("old plan is invalid").kind(), io::ErrorKind::WouldBlock);
|
||||
assert!(resources().is_none());
|
||||
})
|
||||
.await;
|
||||
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
|
||||
assert_eq!(node.completed(), Some(0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scanner_preflight_never_waits_for_additional_devices_under_existing_admission() {
|
||||
let node = node();
|
||||
let first = PhysicalDiskBinding::default();
|
||||
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
|
||||
first.set_test_capacity(vec![gate.clone()]).expect("first plan");
|
||||
let other = PhysicalDiskBinding::default();
|
||||
other
|
||||
.set_test_capacity(vec![AdaptiveAdmission::new(NonZeroU16::MIN, 0)])
|
||||
.expect("closed plan");
|
||||
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
|
||||
admit(&first).expect("existing request admission");
|
||||
let other = admit_scanner_preflight(&other);
|
||||
tokio::pin!(other);
|
||||
assert!(matches!(futures_util::poll!(other), std::task::Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::WouldBlock));
|
||||
assert_eq!([node.snapshot().active, gate.snapshot().active], [1, 1]);
|
||||
})
|
||||
.await;
|
||||
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn receiver_reuses_one_receipt_across_phases_and_releases_only_native_subsets() {
|
||||
let node = node();
|
||||
|
||||
+886
-166
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::bump_local_meta_mutation_gen();
|
||||
crate::bucket::metadata_sys::maybe_bump_local_meta_mutation_gen_for_path(dst_volume, dst_path);
|
||||
}
|
||||
if fi.is_legacy_indexed_delete_marker() {
|
||||
fi.erasure.index = 0;
|
||||
@@ -864,6 +864,13 @@ 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()
|
||||
@@ -943,7 +950,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 {
|
||||
} else if !no_inline || remote_metadata_source {
|
||||
SourcePreparationMode::CreateParent
|
||||
} else {
|
||||
SourcePreparationMode::ExistingParent
|
||||
@@ -975,18 +982,26 @@ 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(nmeta) = FileMeta::load(&old_file.bytes)
|
||||
&& let Ok((mut nmeta, old_inline_buf)) = FileMeta::load_with_borrowed_inline_data(&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() {
|
||||
@@ -1693,7 +1708,7 @@ impl LocalDisk {
|
||||
}
|
||||
} else {
|
||||
prepare_rename_commit_and_destination_metadata(
|
||||
!no_inline && !preserve_upload_metadata,
|
||||
create_source_parent,
|
||||
src_file_parent,
|
||||
dst_file_parent,
|
||||
&dst_file_path,
|
||||
@@ -1709,7 +1724,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(
|
||||
!no_inline && !preserve_upload_metadata,
|
||||
create_source_parent,
|
||||
src_file_parent,
|
||||
dst_file_parent,
|
||||
&dst_file_path,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user