mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-02 22:26:21 +00:00
Compare commits
50 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7ecc80c137 | |||
| c7d828fe6a | |||
| c06a02ce4b | |||
| 3a778c620f | |||
| c6b3cf8675 | |||
| 74615e94d3 | |||
| 5757f554ee | |||
| 485c719ec0 | |||
| 560ee032c7 | |||
| 9d30470316 | |||
| 0e326157cc | |||
| f86e7069d9 | |||
| 7c15d2cc71 | |||
| 1967dec141 | |||
| 5ee681679a | |||
| 123f801671 | |||
| 94ea64359a | |||
| 4f0063da8b | |||
| b71942cf26 | |||
| ad9b5e29e6 | |||
| d8e2353825 | |||
| c3fb1aa4a0 | |||
| 615e55825e | |||
| 2537596a4f | |||
| 6b014ec215 | |||
| a368c669a2 | |||
| e0b548fff0 | |||
| 364dec4b0d | |||
| 152d9a39cc | |||
| 9fe640ff3f | |||
| ba453ce15e | |||
| aa8820e87a | |||
| 82b9897641 | |||
| adc7a7abaa | |||
| 768b7cf58a | |||
| 00a1158e02 | |||
| abef536caa | |||
| 092c865185 | |||
| 1aa042b2e3 | |||
| 8863d2ddd0 | |||
| baa09338ea | |||
| 1d3499b72f | |||
| deea5040a9 | |||
| d82bf5b1f5 | |||
| c09643a2d9 | |||
| f6cee83802 | |||
| 840582da85 | |||
| ff4f38b1b2 | |||
| 1b557aa336 | |||
| b25cc96157 |
@@ -22,7 +22,7 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
|
||||
reason = "chrono is marked unmaintained with no patched release; retained temporarily at compatibility boundaries and transitive datafusion/arrow/openidconnect dependencies during the jiff 1.0 migration reviewed in PR #9492."
|
||||
mitigation = "Informational unmaintained advisory with no CVE or memory-safety vulnerability; core server timestamp paths already migrated to jiff 1.0 in PR #9492 while remaining compatibility boundaries and upstream crates transition off chrono."
|
||||
approved_at = "2026-11-18T12:17:44Z"
|
||||
expires_at = "2026-11-30T23:59:59Z"
|
||||
expires_at = "2027-02-01T23:59:59Z"
|
||||
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
|
||||
|
||||
[[exceptions]]
|
||||
@@ -34,7 +34,7 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
|
||||
reason = "chrono-tz is marked unmaintained with no patched release; pulled transitively by arrow-array 59.3.3 and datafusion-functions 55.3.0 during the jiff migration reviewed in PR #9492."
|
||||
mitigation = "Informational unmaintained advisory with no known security vulnerability; confined to transitive DataFusion/Arrow SQL timezone handling until upstream removes chrono-tz."
|
||||
approved_at = "2026-11-18T12:17:44Z"
|
||||
expires_at = "2026-11-30T23:59:59Z"
|
||||
expires_at = "2027-02-01T23:59:59Z"
|
||||
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
|
||||
|
||||
[[exceptions]]
|
||||
@@ -46,5 +46,5 @@ tracking_issue = "https://github.com/rustfs/backlog/issues/2668"
|
||||
reason = "humantime is marked unmaintained through chrono with no patched release; used by rustfs-madmin and transitively by object_store 0.13.2 / datafusion 55.3.0 as temporarily reviewed in PR #9492."
|
||||
mitigation = "Informational unmaintained advisory with no known security vulnerability; limited to duration formatting and tracked for removal alongside the remaining chrono/jiff migration."
|
||||
approved_at = "2026-11-18T12:17:44Z"
|
||||
expires_at = "2026-11-30T23:59:59Z"
|
||||
expires_at = "2027-02-01T23:59:59Z"
|
||||
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
sha256-darwin=2760507f6c38d1b4bb19aad9c333a9630bdd007fc0622427b069e81dae71c5e9
|
||||
sha256-linux=35319dec9d304310cb459b22cb59a9ee4418502a705c0516f3d474be649cdbc3
|
||||
sha256-linux=88dfb5119dd16fa0095f3dc3801dbd6c438526fa122f9871f87c8387bcdf7779
|
||||
|
||||
@@ -73,6 +73,27 @@ command = ['sh', 'scripts/ci/receipt-fixture-tmpdir.sh', 'namespace-locks']
|
||||
command = ['sh', '-c', 'echo RUST_MIN_STACK=33554432 >> "$NEXTEST_ENV"']
|
||||
|
||||
# --- default profile (local): serialize the flaky groups, never retry --------
|
||||
# These real-store fixtures compose deep async storage futures and need the bounded test stack.
|
||||
[[profile.default.scripts]]
|
||||
filter = """
|
||||
(package(rustfs) & (
|
||||
test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
|
||||
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
|
||||
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
|
||||
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
|
||||
| test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
|
||||
)) | (package(rustfs-iam) & (
|
||||
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
|
||||
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
|
||||
))
|
||||
"""
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
# The 12-drive pinned GET/reconstruction tests share the runner's disk budget.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(rustfs-ecstore) & binary(pinned_erasure_fixtures_test) & test(/^pinned_(legacy|minio)_shards_decode_and_reconstruct_plaintext$/)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# These real-disk progress oracles exercise fsync, quorum IO, and crash/replay
|
||||
# boundaries. Reserve the run's capacity so unrelated fixtures cannot starve
|
||||
# their existing deadlines and typed-failure assertions (rustfs/backlog#2706).
|
||||
@@ -123,6 +144,14 @@ threads-required = "num-test-threads"
|
||||
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# This 12-disk three-pool hot-reload and Pool-0 decommission E2E fixture drives
|
||||
# concurrent S3 traffic and durable pool migration under a 90s drain budget.
|
||||
# Reserve capacity so sibling disk fixtures cannot starve its target capacity
|
||||
# mutation gate; its deadlines, assertions, and zero-retry policy stay intact.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(rustfs) & binary(pool_hot_reload_e2e_test) & test(=multi_pool_1_to_2_to_3_expand_and_3_to_2_pool0_removal_with_concurrent_s3_io_e2e)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(rustfs-heal) & (binary(mrf_partial_write_test) | (binary(mrf_pipeline_test) & test(/^journal_replay_survives_/)) | test(=admin_selector_survives_sigkill_with_original_scope_and_receipts))'
|
||||
threads-required = "num-test-threads"
|
||||
@@ -158,6 +187,24 @@ setup = 'ecstore-base-stack'
|
||||
filter = 'package(rustfs) & (test(/^admin::handlers::table_catalog::tests::/) | test(/^table_catalog::store::tests::/) | test(=app::object::get::tests::execute_get_object_resumes_from_relocated_pool_without_splicing_body) | test(=startup_services::tests::managed_lance_ecstore_catalog_commits_exact_files))'
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
# These real-store regressions compose deep storage futures on Linux test threads.
|
||||
[[profile.default.scripts]]
|
||||
filter = """
|
||||
(package(rustfs) & (
|
||||
test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
|
||||
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
|
||||
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
|
||||
| test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
|
||||
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
|
||||
))
|
||||
| (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test) & test(=serial_tests::test_exact_null_heal_with_current_and_historical_markers))
|
||||
| (package(rustfs-iam) & (
|
||||
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
|
||||
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
|
||||
))
|
||||
"""
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
[[profile.default.scripts]]
|
||||
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
|
||||
setup = 'lifecycle-large-stack'
|
||||
@@ -389,6 +436,27 @@ fail-fast = false
|
||||
# marker is the observable signal the flake policy is built around.
|
||||
path = "junit.xml"
|
||||
|
||||
# These real-store fixtures compose deep async storage futures and need the bounded test stack.
|
||||
[[profile.ci.scripts]]
|
||||
filter = """
|
||||
(package(rustfs) & (
|
||||
test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
|
||||
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
|
||||
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
|
||||
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
|
||||
| test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
|
||||
)) | (package(rustfs-iam) & (
|
||||
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
|
||||
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
|
||||
))
|
||||
"""
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
# Reserve the runner for each 12-drive fixture while keeping its deadline.
|
||||
[[profile.ci.overrides]]
|
||||
filter = 'package(rustfs-ecstore) & binary(pinned_erasure_fixtures_test) & test(/^pinned_(legacy|minio)_shards_decode_and_reconstruct_plaintext$/)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# Match the local durable-progress reservations. All members, deadlines,
|
||||
# assertions, and internal concurrency remain enabled without retries.
|
||||
[[profile.ci.overrides]]
|
||||
@@ -451,6 +519,13 @@ threads-required = "num-test-threads"
|
||||
filter = 'package(rustfs) & test(=admin::handlers::table_catalog::tests::cold_object_registration_completes_while_other_bucket_backup_waits)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# Match the local capacity reservation for the 12-disk three-pool hot-reload
|
||||
# and Pool-0 decommission E2E fixture; deadlines, assertions, and zero retries
|
||||
# remain in force.
|
||||
[[profile.ci.overrides]]
|
||||
filter = 'package(rustfs) & binary(pool_hot_reload_e2e_test) & test(=multi_pool_1_to_2_to_3_expand_and_3_to_2_pool0_removal_with_concurrent_s3_io_e2e)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
[[profile.ci.overrides]]
|
||||
filter = 'package(rustfs-heal) & (binary(mrf_partial_write_test) | (binary(mrf_pipeline_test) & test(/^journal_replay_survives_/)) | test(=admin_selector_survives_sigkill_with_original_scope_and_receipts))'
|
||||
threads-required = "num-test-threads"
|
||||
@@ -503,6 +578,24 @@ setup = 'ecstore-base-stack'
|
||||
filter = 'package(rustfs) & (test(/^admin::handlers::table_catalog::tests::/) | test(/^table_catalog::store::tests::/) | test(=app::object::get::tests::execute_get_object_resumes_from_relocated_pool_without_splicing_body) | test(=startup_services::tests::managed_lance_ecstore_catalog_commits_exact_files))'
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
# These real-store regressions compose deep storage futures on Linux test threads.
|
||||
[[profile.ci.scripts]]
|
||||
filter = """
|
||||
(package(rustfs) & (
|
||||
test(=table_catalog::tests::prepared_commit::catalog_vector_empty_delete_rejects_namespace_without_parent)
|
||||
| test(=table_catalog::store::directory_index::tests::directory_index_real_backend_requires_authoritative_eof_before_ready)
|
||||
| test(=app::object::get::tests::get_object_resume_reopen_rejects_a_replaced_object_version)
|
||||
| test(=app::delete_objects_stat_gating_test::delete_all_exact_object_preserves_a_retained_child_key)
|
||||
| test(=app::object::delete::tests::durable_quota_reclaims_overwrites_and_deleted_bytes)
|
||||
))
|
||||
| (package(rustfs-heal) & binary(=heal_b5_versioned_regression_test) & test(=serial_tests::test_exact_null_heal_with_current_and_historical_markers))
|
||||
| (package(rustfs-iam) & (
|
||||
test(=store::object::tests::service_account_conditional_delete_preserves_replacement_account_and_policy)
|
||||
| test(=store::object::tests::service_account_owner_delete_mismatch_emits_no_notification_and_admin_cleans_corrupt_record)
|
||||
))
|
||||
"""
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
[[profile.ci.scripts]]
|
||||
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
|
||||
setup = 'lifecycle-large-stack'
|
||||
|
||||
@@ -31,7 +31,8 @@ selected_tests = [
|
||||
]
|
||||
expected_rejection = "Unsigned x-amz-* headers on presigned requests must fail with S3ErrorCode::AccessDenied"
|
||||
timeout_seconds = 120
|
||||
compile_timeout_seconds = 1800
|
||||
# The two cases share a baseline. Cold rustfs lib test builds can exceed 30 minutes.
|
||||
compile_timeout_seconds = 3600
|
||||
|
||||
[[cases]]
|
||||
id = "presigned_allow_duplicate_signed_headers"
|
||||
@@ -54,7 +55,7 @@ selected_tests = [
|
||||
]
|
||||
expected_rejection = "Duplicate X-Amz-SignedHeaders query parameters must sign nothing and reject unsigned x-amz-* headers with AccessDenied"
|
||||
timeout_seconds = 120
|
||||
compile_timeout_seconds = 1800
|
||||
compile_timeout_seconds = 3600
|
||||
|
||||
[[cases]]
|
||||
id = "notify_xml_allow_duplicate_queue"
|
||||
|
||||
@@ -7,3 +7,4 @@ self-hosted-runner:
|
||||
- dind-sm-standard-2
|
||||
- smoke-testing
|
||||
- pf-testing
|
||||
- rdma
|
||||
|
||||
@@ -296,6 +296,29 @@
|
||||
"origin": "baseline",
|
||||
"alert_contract": "scheduled-validation"
|
||||
},
|
||||
{
|
||||
"workflow": ".github/workflows/rdma-build.yml",
|
||||
"name": "S3-over-RDMA compile",
|
||||
"roles": [
|
||||
"pr",
|
||||
"manual"
|
||||
],
|
||||
"events": [
|
||||
"pull_request",
|
||||
"push",
|
||||
"workflow_dispatch"
|
||||
],
|
||||
"cadence": "event",
|
||||
"timezone": "UTC",
|
||||
"schedule": [],
|
||||
"owner": "@overtrue",
|
||||
"policy": "active",
|
||||
"monitor": "none",
|
||||
"result_owner": "rdma-build.yml",
|
||||
"disposition": "retained independent entry",
|
||||
"monitor_reason": "Event-driven or operator-requested work has no periodic freshness obligation.",
|
||||
"origin": "added"
|
||||
},
|
||||
{
|
||||
"workflow": ".github/workflows/rdma-feature-check.yml",
|
||||
"name": "S3-over-RDMA feature check",
|
||||
|
||||
@@ -45,7 +45,7 @@ A hosted runner is also the only choice for a few things the pods cannot do: `mo
|
||||
|
||||
- Every `shared-key` has exactly one writer. `cache-warm.yml` owns `ci-dev`, `ci-feat-proto` and `ci-uring`; every other `./.github/actions/setup` call states `cache-save-if` explicitly, and `scripts/security/check_cache_save_if.sh` fails the build when one does not.
|
||||
- The `ci-dev` key ends in a digest of `warm-ci-dev`'s build commands. Changing what that job warms therefore needs a new key, or readers keep restoring the old artifacts: `scripts/ci_gate.py --check-workflow` prints the key the commands require and fails until the writer and every registered `sm-standard-4` reader (`ci.yml`, `dual-stack-nightly.yml`, `e2e-replication-nightly.yml`, `fuzz.yml`, `gateway-acceptance.yml`, `mint.yml` and `reference-parity.yml`) name it.
|
||||
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`).
|
||||
- All readers of a key run on the same image as its writer. Keys that live on hosted runners say so in their name (`ci-uring` is warmed on `ubuntu-latest`; `ci-e2e-distributed-hosted` is written on `ubuntu-latest` by `e2e-distributed.yml` and read without saving by hosted server/E2E lanes such as `gateway-acceptance.yml`, `on-demand-migration-interop.yml`, `oidc-keycloak.yml`, `minio-interop.yml`, `e2e-upgrade.yml` and `rdma-feature-check.yml`). `rdma-build.yml` owns `ci-nixl-rdma` on the `rdma` label and is the only job that saves it.
|
||||
- Moving a job between pools therefore means renaming its key. The new key is empty until a run from `main` (a scheduled run, or a manual dispatch of that workflow from `main`) saves it; until then that lane does a cold build. The `build.yml` aarch64 release legs append `-ubicloud-arm` for this reason. `cache-warm.yml` does not write those keys.
|
||||
- `CARGO_BUILD_JOBS` and every other `CARGO*`, `CC*`, `CFLAGS*`, `CXX*`, `CMAKE*` and `RUST*` variable is hashed into the key. `ci.yml` sets `CARGO_BUILD_JOBS` at step level for that reason; promoting it to job level rotates the key for every lane that shares it.
|
||||
|
||||
|
||||
@@ -404,8 +404,10 @@ jobs:
|
||||
needs: [ workspace-lint-and-build, classify-changes ]
|
||||
# The archive retains compile-time fixture paths and the large test set
|
||||
# requires the same runner image until the hosted-runtime pilot passes.
|
||||
# Full mode runs archive extraction, the 75m workspace suite, the 80m
|
||||
# serial ILM suite, and Vector KMS verification under their own step budgets.
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
timeout-minutes: 180
|
||||
env:
|
||||
CI_PACKAGES: ${{ needs.classify-changes.outputs.packages }}
|
||||
steps:
|
||||
|
||||
+37
-10
@@ -106,6 +106,7 @@ jobs:
|
||||
targets_csv: ${{ steps.select.outputs.targets_csv }}
|
||||
has_targets: ${{ steps.select.outputs.has_targets }}
|
||||
run_mutants: ${{ steps.select.outputs.run_mutants }}
|
||||
build_matrix: ${{ steps.group-builds.outputs.matrix }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -164,6 +165,19 @@ jobs:
|
||||
--ci-mode "$CALLER_CI_MODE" \
|
||||
--output artifacts/security-input-gate/selection-manifest.json
|
||||
|
||||
- name: Group selected harness builds
|
||||
id: group-builds
|
||||
env:
|
||||
SELECTED_TARGETS: ${{ steps.select.outputs.targets_json }}
|
||||
run: |
|
||||
matrix=$(jq -cn --argjson selected "$SELECTED_TARGETS" '
|
||||
{include: [
|
||||
{profile: "core", targets_csv: ($selected | map(select(. != "fuzz_s3_select_sql")) | join(","))},
|
||||
{profile: "s3-select", targets_csv: ($selected | map(select(. == "fuzz_s3_select_sql")) | join(","))}
|
||||
] | map(select(.targets_csv != ""))}
|
||||
')
|
||||
printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload selection manifest
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
@@ -184,13 +198,17 @@ jobs:
|
||||
needs.select-targets.outputs.has_targets == 'true'
|
||||
# Self-hosted runner required: nightly libFuzzer builds exceed hosted disk budget.
|
||||
runs-on: sm-standard-4
|
||||
# A cold build links seven instrumented binaries, about 13 minutes each.
|
||||
# Full validation builds one instrumented dependency graph per runner.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.select-targets.outputs.build_matrix) }}
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
CARGO_BUILD_TARGET: x86_64-unknown-linux-gnu
|
||||
# Fuzz targets build without the dial9 feature, so tokio_unstable is not needed.
|
||||
RUSTFLAGS: "-C target-feature=-crt-static"
|
||||
# Use lld with bounded linker threads so linking all instrumented harnesses stays within the pod memory budget.
|
||||
RUSTFLAGS: "-C target-feature=-crt-static -C link-arg=-fuse-ld=lld -C link-arg=-Wl,--threads=2"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -201,7 +219,7 @@ jobs:
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: nightly
|
||||
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
|
||||
cache-shared-key: fuzz-nightly-${{ matrix.profile }}-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'schedule' }}
|
||||
|
||||
- name: Install cargo-fuzz
|
||||
@@ -209,14 +227,21 @@ jobs:
|
||||
with:
|
||||
tool: cargo-fuzz
|
||||
|
||||
- name: Install lld
|
||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends lld
|
||||
|
||||
- name: Build selected fuzz targets
|
||||
env:
|
||||
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
|
||||
# Keep memory-intensive instrumented rustc processes from crowding out the runner.
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
# Split monolithic ASan+SanCov LLVM modules across 16 codegen units so huge crates stay within 28 GB RAM.
|
||||
FUZZ_CODEGEN_UNITS: "16"
|
||||
FUZZ_TARGET: ${{ matrix.targets_csv }}
|
||||
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
|
||||
|
||||
- name: Stage prebuilt fuzz binaries
|
||||
env:
|
||||
SELECTED_TARGETS_CSV: ${{ needs.select-targets.outputs.targets_csv }}
|
||||
SELECTED_TARGETS_CSV: ${{ matrix.targets_csv }}
|
||||
run: |
|
||||
binary_root="fuzz/prebuilt/${CARGO_BUILD_TARGET}/release"
|
||||
mkdir -p "${binary_root}"
|
||||
@@ -234,8 +259,10 @@ jobs:
|
||||
- name: Upload prebuilt fuzz binaries
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.profile }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/
|
||||
# Reuse successful group artifacts when another group is rerun.
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
compression-level: 0
|
||||
@@ -274,7 +301,7 @@ jobs:
|
||||
- name: Download prebuilt fuzz binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
|
||||
|
||||
- name: Restore executable bit
|
||||
@@ -312,8 +339,8 @@ jobs:
|
||||
needs.select-targets.outputs.run_mutants == 'true'
|
||||
# Self-hosted runner required: builds rustfs + rustfs-notify test targets.
|
||||
runs-on: sm-standard-4
|
||||
# Allow for the baseline and the isolated rebuilds, each with its own compile deadline.
|
||||
timeout-minutes: 150
|
||||
# Allow for three rustfs builds, two notify builds, runner setup and test execution.
|
||||
timeout-minutes: 270
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
@@ -383,7 +410,7 @@ jobs:
|
||||
- name: Download prebuilt fuzz binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
|
||||
|
||||
- name: Restore executable bit
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# Copyright 2024 RustFS Team
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
name: S3-over-RDMA compile
|
||||
|
||||
# Compile the optional `nixl` feature when NIXL/RDMA sources change.
|
||||
# Pull requests and pushes to main share one path list; workflow_dispatch
|
||||
# runs the same job with no path filter. Unrelated changes do not start a runner.
|
||||
#
|
||||
# The job runs on the self-hosted `rdma` label, the same bare-label form as
|
||||
# `smoke-testing` and `sm-standard-4`. nixl-sys links libnixl when that
|
||||
# runner has it installed (NIXL_PREFIX, default /opt/nvidia/nvda_nixl, or
|
||||
# pkg-config). When the libraries are absent it compiles wrapper.h plus the
|
||||
# dlopen stub. This job does not set NIXL_NO_STUBS_FALLBACK. bindgen needs
|
||||
# g++ and libclang; the setup action installs a C toolchain, and the step
|
||||
# below adds libclang only when the image lacks it.
|
||||
#
|
||||
# Host-memory unit tests and the cuObject SDK lane stay in
|
||||
# rdma-feature-check.yml (pull requests, weekly schedule, manual dispatch).
|
||||
# Not a required check and not part of the `Test and Lint` aggregate.
|
||||
#
|
||||
# When adding a nixl-gated module, extend both path lists below. GitHub
|
||||
# filters are whole files: shared files are listed because they contain
|
||||
# `feature = "nixl"` branches, and crates/config/src/constants/internode.rs
|
||||
# also holds unrelated internode constants.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "crates/nixl/**"
|
||||
- "crates/ecstore/src/cluster/rpc/nixl_internode.rs"
|
||||
- "crates/ecstore/src/cluster/rpc/nixl_internode/**"
|
||||
- "crates/config/src/constants/internode.rs"
|
||||
- "rustfs/src/app/multipart_usecase/upload_part.rs"
|
||||
- "rustfs/src/app/object/cuobject.rs"
|
||||
- "rustfs/src/app/object/get.rs"
|
||||
- "rustfs/src/app/object/mod.rs"
|
||||
- "rustfs/src/app/object/put.rs"
|
||||
- "rustfs/src/app/storage_api.rs"
|
||||
- "rustfs/src/startup_server.rs"
|
||||
- "rustfs/src/storage/rpc/http_service.rs"
|
||||
- "rustfs/src/storage/rpc/mod.rs"
|
||||
- "rustfs/src/storage/rpc/nixl*"
|
||||
- "rustfs/src/storage/storage_api.rs"
|
||||
- "Cargo.toml"
|
||||
- "rustfs/Cargo.toml"
|
||||
- ".github/workflows/rdma-build.yml"
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "crates/nixl/**"
|
||||
- "crates/ecstore/src/cluster/rpc/nixl_internode.rs"
|
||||
- "crates/ecstore/src/cluster/rpc/nixl_internode/**"
|
||||
- "crates/config/src/constants/internode.rs"
|
||||
- "rustfs/src/app/multipart_usecase/upload_part.rs"
|
||||
- "rustfs/src/app/object/cuobject.rs"
|
||||
- "rustfs/src/app/object/get.rs"
|
||||
- "rustfs/src/app/object/mod.rs"
|
||||
- "rustfs/src/app/object/put.rs"
|
||||
- "rustfs/src/app/storage_api.rs"
|
||||
- "rustfs/src/startup_server.rs"
|
||||
- "rustfs/src/storage/rpc/http_service.rs"
|
||||
- "rustfs/src/storage/rpc/mod.rs"
|
||||
- "rustfs/src/storage/rpc/nixl*"
|
||||
- "rustfs/src/storage/storage_api.rs"
|
||||
- "Cargo.toml"
|
||||
- "rustfs/Cargo.toml"
|
||||
- ".github/workflows/rdma-build.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Cancel a superseded pull-request attempt. Pushes and manual runs finish.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
|
||||
jobs:
|
||||
nixl-build:
|
||||
name: cargo check and test compile (nixl)
|
||||
# Hardware: the RDMA/NIXL runner. Hosted ubuntu-latest has no NIXL/UCX
|
||||
# libraries. The label matches smoke-testing and sm-standard-4 (bare
|
||||
# label, not a [self-hosted, ...] list).
|
||||
runs-on: rdma
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
# Own key: rust-cache does not include the runner label, and
|
||||
# ci-e2e-distributed-hosted is written on ubuntu-latest.
|
||||
cache-shared-key: ci-nixl-rdma
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
- name: Install only missing native build tools
|
||||
run: |
|
||||
packages=()
|
||||
command -v g++ >/dev/null || packages+=(g++)
|
||||
ldconfig -p | grep -q 'libclang' || packages+=(libclang-dev)
|
||||
if (( ${#packages[@]} )); then
|
||||
sudo apt-get update
|
||||
sudo apt-get install --no-install-recommends -y "${packages[@]}"
|
||||
fi
|
||||
|
||||
- name: Check the nixl feature build
|
||||
run: cargo check --locked -p rustfs --features nixl
|
||||
|
||||
# Compiles rustfs-nixl unit and integration tests, including client-http.
|
||||
# Does not execute them: the host-memory suite runs in rdma-feature-check.yml.
|
||||
# `cargo test --no-run -p rustfs` is not used; that harness is the workspace
|
||||
# test build and does not fit this runner.
|
||||
- name: Compile rustfs-nixl tests
|
||||
run: cargo test --locked --no-run -p rustfs-nixl --features client-http
|
||||
@@ -2,6 +2,8 @@ name: S3-over-RDMA feature check
|
||||
|
||||
# Compile the optional RDMA features independently. The cuObject tests link
|
||||
# the NVIDIA SDK and exercise the host-side behavior on a CPU runner.
|
||||
# Pushes to main are compiled by rdma-build.yml; this workflow keeps the
|
||||
# rustfs-nixl unit tests, the cuObject SDK lane, and the weekly run.
|
||||
# Not a required check and not part of the `Test and Lint` aggregate.
|
||||
|
||||
on:
|
||||
|
||||
Generated
+562
-415
File diff suppressed because it is too large
Load Diff
+81
-76
@@ -40,6 +40,7 @@ members = [
|
||||
"crates/lock", # Distributed locking implementation
|
||||
"crates/log-analyzer", # Offline log fault-analysis core (rustfs diagnose)
|
||||
"crates/madmin", # Management dashboard and admin API interface
|
||||
"crates/metrics-compat", # Shared recorder for dependencies requiring metrics 0.24
|
||||
"crates/notify", # Notification system for events
|
||||
"crates/obs", # Observability utilities
|
||||
"crates/object-capacity", # Capacity scan and refresh core
|
||||
@@ -75,6 +76,7 @@ members = [
|
||||
]
|
||||
exclude = [
|
||||
"vendor/hyper",
|
||||
"vendor/nkeys",
|
||||
"vendor/openidconnect",
|
||||
"vendor/rustfs-dst-faults",
|
||||
"vendor/rustfs-dst-runtime",
|
||||
@@ -86,7 +88,7 @@ edition = "2024"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/rustfs/rustfs"
|
||||
rust-version = "1.99.0"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
homepage = "https://rustfs.com"
|
||||
keywords = ["RustFS", "Minio", "object-storage", "filesystem", "s3"]
|
||||
categories = ["web-programming", "development-tools", "filesystem", "network-programming"]
|
||||
@@ -102,60 +104,60 @@ redundant_clone = "warn"
|
||||
|
||||
[workspace.dependencies]
|
||||
# RustFS Internal Crates
|
||||
rustfs-gateway-adapter = { path = "crates/gateway-adapter", version = "1.0.5" }
|
||||
rustfs-heal = { path = "crates/heal", version = "1.0.5" }
|
||||
rustfs-heal-contracts = { path = "crates/heal-contracts", version = "1.0.5" }
|
||||
rustfs-scanner-metrics = { path = "crates/scanner-metrics", version = "1.0.5" }
|
||||
rustfs-audit = { path = "crates/audit", version = "1.0.5" }
|
||||
rustfs-checksums = { path = "crates/checksums", version = "1.0.5" }
|
||||
rustfs-common = { path = "crates/common", version = "1.0.5" }
|
||||
rustfs-data-usage = { path = "crates/data-usage", version = "1.0.5" }
|
||||
rustfs-config = { path = "./crates/config", version = "1.0.5" }
|
||||
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" }
|
||||
rustfs-iam = { path = "crates/iam", version = "1.0.5" }
|
||||
rustfs-keystone = { path = "crates/keystone", version = "1.0.5" }
|
||||
rustfs-license = { path = "crates/license", version = "1.0.5" }
|
||||
rustfs-lifecycle = { path = "crates/lifecycle", version = "1.0.5" }
|
||||
rustfs-kms = { path = "crates/kms", version = "1.0.5" }
|
||||
rustfs-lock = { path = "crates/lock", version = "1.0.5" }
|
||||
rustfs-madmin = { path = "crates/madmin", version = "1.0.5" }
|
||||
rustfs-notify = { path = "crates/notify", version = "1.0.5" }
|
||||
rustfs-io-metrics = { path = "crates/io-metrics", version = "1.0.5" }
|
||||
rustfs-io-core = { path = "crates/io-core", version = "1.0.5" }
|
||||
rustfs-object-capacity = { path = "crates/object-capacity", version = "1.0.5" }
|
||||
rustfs-object-data-cache = { path = "crates/object-data-cache", version = "1.0.5", default-features = false }
|
||||
rustfs-log-analyzer = { path = "crates/log-analyzer", version = "1.0.5" }
|
||||
rustfs-obs = { path = "crates/obs", version = "1.0.5" }
|
||||
rustfs-policy = { path = "crates/policy", version = "1.0.5" }
|
||||
rustfs-protos = { path = "crates/protos", version = "1.0.5" }
|
||||
rustfs-protocols = { path = "crates/protocols", version = "1.0.5" }
|
||||
rustfs-replication = { path = "crates/replication", version = "1.0.5" }
|
||||
rustfs-rio = { path = "crates/rio", version = "1.0.5" }
|
||||
rustfs-rio-v2 = { path = "crates/rio-v2", version = "1.0.5" }
|
||||
rustfs-s3-client = { path = "crates/s3-client", version = "1.0.5" }
|
||||
rustfs-s3-types = { path = "crates/s3-types", version = "1.0.5" }
|
||||
rustfs-s3-ops = { path = "crates/s3-ops", version = "1.0.5" }
|
||||
rustfs-s3select-api = { path = "crates/s3select-api", version = "1.0.5" }
|
||||
rustfs-s3select-query = { path = "crates/s3select-query", version = "1.0.5" }
|
||||
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" }
|
||||
rustfs-test-utils = { path = "crates/test-utils", version = "1.0.5" }
|
||||
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" }
|
||||
rustfs-gateway-adapter = { path = "crates/gateway-adapter", version = "1.0.8" }
|
||||
rustfs-heal = { path = "crates/heal", version = "1.0.8" }
|
||||
rustfs-heal-contracts = { path = "crates/heal-contracts", version = "1.0.8" }
|
||||
rustfs-scanner-metrics = { path = "crates/scanner-metrics", version = "1.0.8" }
|
||||
rustfs-audit = { path = "crates/audit", version = "1.0.8" }
|
||||
rustfs-checksums = { path = "crates/checksums", version = "1.0.8" }
|
||||
rustfs-common = { path = "crates/common", version = "1.0.8" }
|
||||
rustfs-data-usage = { path = "crates/data-usage", version = "1.0.8" }
|
||||
rustfs-config = { path = "./crates/config", version = "1.0.8" }
|
||||
rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.8" }
|
||||
rustfs-credentials = { path = "crates/credentials", version = "1.0.8" }
|
||||
rustfs-crypto = { path = "crates/crypto", version = "1.0.8" }
|
||||
rustfs-cuobject = { path = "crates/cuobject", version = "1.0.8" }
|
||||
rustfs-cuobject-sys = { path = "crates/cuobject-sys", version = "1.0.8" }
|
||||
rustfs-nixl = { path = "crates/nixl", version = "1.0.8" }
|
||||
rustfs-ecstore = { path = "crates/ecstore", version = "1.0.8" }
|
||||
rustfs-filemeta = { path = "crates/filemeta", version = "1.0.8" }
|
||||
rustfs-iam = { path = "crates/iam", version = "1.0.8" }
|
||||
rustfs-keystone = { path = "crates/keystone", version = "1.0.8" }
|
||||
rustfs-license = { path = "crates/license", version = "1.0.8" }
|
||||
rustfs-lifecycle = { path = "crates/lifecycle", version = "1.0.8" }
|
||||
rustfs-kms = { path = "crates/kms", version = "1.0.8" }
|
||||
rustfs-lock = { path = "crates/lock", version = "1.0.8" }
|
||||
rustfs-madmin = { path = "crates/madmin", version = "1.0.8" }
|
||||
rustfs-notify = { path = "crates/notify", version = "1.0.8" }
|
||||
rustfs-io-metrics = { path = "crates/io-metrics", version = "1.0.8" }
|
||||
rustfs-io-core = { path = "crates/io-core", version = "1.0.8" }
|
||||
rustfs-object-capacity = { path = "crates/object-capacity", version = "1.0.8" }
|
||||
rustfs-object-data-cache = { path = "crates/object-data-cache", version = "1.0.8", default-features = false }
|
||||
rustfs-log-analyzer = { path = "crates/log-analyzer", version = "1.0.8" }
|
||||
rustfs-obs = { path = "crates/obs", version = "1.0.8" }
|
||||
rustfs-policy = { path = "crates/policy", version = "1.0.8" }
|
||||
rustfs-protos = { path = "crates/protos", version = "1.0.8" }
|
||||
rustfs-protocols = { path = "crates/protocols", version = "1.0.8" }
|
||||
rustfs-replication = { path = "crates/replication", version = "1.0.8" }
|
||||
rustfs-rio = { path = "crates/rio", version = "1.0.8" }
|
||||
rustfs-rio-v2 = { path = "crates/rio-v2", version = "1.0.8" }
|
||||
rustfs-s3-client = { path = "crates/s3-client", version = "1.0.8" }
|
||||
rustfs-s3-types = { path = "crates/s3-types", version = "1.0.8" }
|
||||
rustfs-s3-ops = { path = "crates/s3-ops", version = "1.0.8" }
|
||||
rustfs-s3select-api = { path = "crates/s3select-api", version = "1.0.8" }
|
||||
rustfs-s3select-query = { path = "crates/s3select-query", version = "1.0.8" }
|
||||
rustfs-scanner = { path = "crates/scanner", version = "1.0.8" }
|
||||
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.8" }
|
||||
rustfs-extension-schema = { path = "crates/extension-schema", version = "1.0.8" }
|
||||
rustfs-signer = { path = "crates/signer", version = "1.0.8" }
|
||||
rustfs-sse = { path = "crates/sse", version = "1.0.8" }
|
||||
rustfs-storage-api = { path = "crates/storage-api", version = "1.0.8" }
|
||||
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.8" }
|
||||
rustfs-targets = { path = "crates/targets", version = "1.0.8" }
|
||||
rustfs-test-utils = { path = "crates/test-utils", version = "1.0.8" }
|
||||
rustfs-tls-runtime = { path = "crates/tls-runtime", version = "1.0.8" }
|
||||
rustfs-utils = { path = "crates/utils", version = "1.0.8" }
|
||||
rustfs-zip = { path = "./crates/zip", version = "1.0.8" }
|
||||
rustfs-dst-runtime = { path = "vendor/rustfs-dst-runtime", default-features = false }
|
||||
rustfs-dst-faults = { path = "vendor/rustfs-dst-faults", default-features = false }
|
||||
|
||||
@@ -191,13 +193,13 @@ hyper = { version = "=1.12.0" } # Keep the HTTP/2 Expect backport below active.
|
||||
h2 = { version = "0.4.21" }
|
||||
hyper-rustls = { default-features = false, version = "0.27.10" }
|
||||
hyper-util = { version = "0.1.21" }
|
||||
http = "1.5.0"
|
||||
http = "1.6.0"
|
||||
http-body = "1.1.0"
|
||||
http-body-util = "0.1.5"
|
||||
memchr = "2.8.3"
|
||||
minlz = "1.2.3"
|
||||
reqwest = "0.13.5"
|
||||
rustfs-kafka-async = { version = "1.4.1" }
|
||||
rustfs-kafka-async = { version = "1.5.0" }
|
||||
slab = { version = "0.4.12" }
|
||||
socket2 = { version = "0.6.5" }
|
||||
tokio = { version = "1.54.1" }
|
||||
@@ -223,7 +225,7 @@ apache-avro = { version = "0.23.0", features = ["snappy", "zstandard"] }
|
||||
bytes = { version = "1.12.2" }
|
||||
csv-core = "0.1.13"
|
||||
bytesize = "2.7.0"
|
||||
byteorder = "1.5.0"
|
||||
byteorder = "1.5.1"
|
||||
flatbuffers = "25.12.19"
|
||||
form_urlencoded = "1.2.3"
|
||||
prost = "0.14.6"
|
||||
@@ -260,7 +262,7 @@ rustls-native-certs = "0.8"
|
||||
rustls-pki-types = "1.16.0"
|
||||
x509-parser = "0.18.1"
|
||||
sha1 = "0.11.0"
|
||||
sha2 = "0.11.2"
|
||||
sha2 = "0.11.3"
|
||||
subtle = "2.6"
|
||||
zeroize = { version = "1.9.2" }
|
||||
proptest = "1"
|
||||
@@ -268,7 +270,7 @@ proptest = "1"
|
||||
# Time and Date
|
||||
chrono = { version = "0.4.45" }
|
||||
humantime = "2.4.0"
|
||||
jiff = { version = "1.0.3" }
|
||||
jiff = { version = "1.1.0" }
|
||||
time = { version = "0.3.55" }
|
||||
|
||||
# Database
|
||||
@@ -281,16 +283,16 @@ anyhow = "1.0.105"
|
||||
arc-swap = "1.9.5"
|
||||
rustfs-tokio-tar = { version = "0.7.1" }
|
||||
# Candidate Snowball parser versions exercised by rustfs-zip compatibility fixtures.
|
||||
tar-codec = "0.0.17"
|
||||
tar-framing = "0.0.17"
|
||||
tar-codec = "0.0.18"
|
||||
tar-framing = "0.0.18"
|
||||
atoi = "3.1.1"
|
||||
atomic_enum = "0.3.0"
|
||||
aws-config = { version = "1.13.4" }
|
||||
aws-credential-types = { version = "1.3.1" }
|
||||
aws-sdk-kms = { default-features = false, version = "1.134.0" }
|
||||
aws-sdk-s3 = { default-features = false, version = "1.162.0" }
|
||||
aws-sdk-sts = { default-features = false, version = "1.129.0" }
|
||||
aws-sdk-s3vectors = { default-features = false, version = "=1.49.0" }
|
||||
aws-sdk-s3 = { default-features = false, version = "1.163.0" }
|
||||
aws-sdk-sts = { default-features = false, version = "1.130.0" }
|
||||
aws-sdk-s3vectors = { default-features = false, version = "=1.52.0" }
|
||||
aws-smithy-async = { version = "1.3.1" }
|
||||
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
|
||||
aws-smithy-runtime-api = { version = "1.22.1" }
|
||||
@@ -356,7 +358,7 @@ percent-encoding = "2.3.2"
|
||||
# Server-side QR rendering for TOTP enrollment, so neither the console nor the
|
||||
# CLI needs its own QR encoder. No default features: the image/render backends
|
||||
# pull in an image stack this only needs SVG and text output from.
|
||||
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
|
||||
qrcode-rs = { version = "2.2.1", default-features = false, features = ["std", "svg"] }
|
||||
pin-project-lite = "0.2.18"
|
||||
pretty_assertions = "1.4.1"
|
||||
rand = { version = "0.10.4" }
|
||||
@@ -377,10 +379,10 @@ siphasher = "1.0.4"
|
||||
smallvec = { version = "1.16.6" }
|
||||
compact_str = "0.10.0"
|
||||
snap = "1.1.2"
|
||||
starshard = { version = "2.4.1" }
|
||||
starshard = { version = "2.4.2" }
|
||||
strum = { version = "0.28.0" }
|
||||
sync_wrapper = "1.0.2"
|
||||
sysinfo = "0.40.4"
|
||||
sysinfo = "0.40.5"
|
||||
temp-env = "0.3.6"
|
||||
tempfile = "3.27.0"
|
||||
test-case = "3.4.1"
|
||||
@@ -399,15 +401,15 @@ vaultrs = { version = "0.8.0" }
|
||||
tar = "0.4.46"
|
||||
walkdir = "2.5.1"
|
||||
winapi-util = "0.1.11"
|
||||
windows = { version = "0.62.2" }
|
||||
windows-sys = "0.61.2"
|
||||
windows = { version = "0.101.0" }
|
||||
windows-sys = "0.101.0"
|
||||
xxhash-rust = { version = "0.8.21" }
|
||||
zip = "9.9.0"
|
||||
zstd = "0.14.5"
|
||||
|
||||
# Observability and Metrics
|
||||
metrics = "0.24.6"
|
||||
metrics-util = "0.20"
|
||||
metrics = "0.25.1"
|
||||
metrics-util = "0.21"
|
||||
dial9 = { version = "0.5.9", default-features = false }
|
||||
opentelemetry = { version = "0.33.1" }
|
||||
opentelemetry-appender-tracing = { version = "0.33.1" }
|
||||
@@ -415,7 +417,7 @@ opentelemetry-otlp = { version = "0.33.1" }
|
||||
opentelemetry-proto = { version = "0.33.1", default-features = false, features = ["metrics", "gen-tonic-messages"] }
|
||||
opentelemetry_sdk = { version = "0.33.1" }
|
||||
opentelemetry-semantic-conventions = { version = "0.33.1" }
|
||||
opentelemetry-stdout = { version = "0.33.1" }
|
||||
opentelemetry-stdout = { version = "0.33.2" }
|
||||
pyroscope = { version = "2.1.5" }
|
||||
|
||||
# FTP and SFTP
|
||||
@@ -430,9 +432,9 @@ russh-sftp = "4.0.0"
|
||||
dav-server = "0.12.0"
|
||||
|
||||
# Performance Analysis and Memory Profiling
|
||||
rustfs-mimalloc = { version = "0.7.5" }
|
||||
# Preserve method names in existing HOTPATH_FOCUS filters and reports.
|
||||
hotpath = { version = "=0.32.1", default-features = false }
|
||||
rustfs-mimalloc = { version = "0.7.6" }
|
||||
# Hotpath 0.33 infers type-qualified names for methods without explicit labels or impl_type.
|
||||
hotpath = { version = "=0.33.1", default-features = false }
|
||||
# Snapshot testing for output format regression detection
|
||||
insta = { version = "1.49" }
|
||||
|
||||
@@ -482,9 +484,12 @@ strip = "none"
|
||||
|
||||
# Pin upstream fixes until compatible crates.io releases are available.
|
||||
[patch.crates-io]
|
||||
metrics = { path = "crates/metrics-compat" }
|
||||
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
|
||||
hyper = { path = "vendor/hyper" }
|
||||
lance-bitpacking = { git = "https://github.com/GatewayJ/lance", rev = "35a95d99a1f413d9cad0427837ee6939974a1570" }
|
||||
# Remove once async-nats can use a published nkeys release with ed25519-dalek 3 (RUSTSEC-2026-0620).
|
||||
nkeys = { path = "vendor/nkeys" }
|
||||
# Remove after openidconnect releases an rsa >= 0.10 build (ramosbugs/openidconnect-rs#140).
|
||||
openidconnect = { path = "vendor/openidconnect" }
|
||||
simba = { git = "https://github.com/GatewayJ/simba", rev = "e2dbec306b6f30593d105c4410582a77196fda37" }
|
||||
|
||||
@@ -26,8 +26,8 @@
|
||||
//! channel and await a checkpoint receipt; ordinary complete writes do not use
|
||||
//! it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::{BuildHasher, Hash};
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
@@ -225,19 +225,34 @@ impl MrfDurableRepairAnchor {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
|
||||
let Some(lease) = event.lease else {
|
||||
return false;
|
||||
};
|
||||
self.kind == event.kind
|
||||
&& self.bucket == event.bucket
|
||||
&& self.object == event.object
|
||||
&& self.version_id == event.version_id
|
||||
&& self.scope == event.scope
|
||||
&& self.delete_marker_purge == event.delete_marker_purge
|
||||
&& self.lease == lease
|
||||
&& self.bucket_incarnation_id == event.bucket_incarnation_id
|
||||
fn proof_identity(&self) -> MrfProofIdentity<'_> {
|
||||
MrfProofIdentity {
|
||||
kind: self.kind,
|
||||
bucket: &self.bucket,
|
||||
object: &self.object,
|
||||
version_id: self.version_id,
|
||||
scope: self.scope,
|
||||
delete_marker_purge: self.delete_marker_purge,
|
||||
lease: self.lease,
|
||||
bucket_incarnation_id: self.bucket_incarnation_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
|
||||
event.proof_identity() == Some(self.proof_identity())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash)]
|
||||
struct MrfProofIdentity<'a> {
|
||||
kind: MrfKind,
|
||||
bucket: &'a str,
|
||||
object: &'a str,
|
||||
version_id: Option<[u8; 16]>,
|
||||
scope: Option<MrfScope>,
|
||||
delete_marker_purge: Option<MrfDeleteMarkerPurgeIdentity>,
|
||||
lease: MrfIngressLease,
|
||||
bucket_incarnation_id: Uuid,
|
||||
}
|
||||
|
||||
/// Consume only anchors proven by a complete verified-repair identity. The
|
||||
@@ -252,44 +267,81 @@ pub fn consume_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnch
|
||||
before.saturating_sub(anchors.len())
|
||||
}
|
||||
|
||||
/// Consume recorded verified repairs for one bucket without draining
|
||||
/// unrelated or still-unmatched proofs. If the caller crashes before
|
||||
/// persisting the retained anchor set, the proof may be replayed by repair
|
||||
/// instead of silently deleting the old responsibility.
|
||||
/// Consume recorded verified repairs for one bucket, retaining unmatched events.
|
||||
pub fn consume_recorded_verified_mrf_repair_events_for(bucket: &str, anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
|
||||
consume_recorded_verified_mrf_repairs(anchors, Some(bucket))
|
||||
}
|
||||
|
||||
/// Match recorded receipts across all supplied anchors in one pass.
|
||||
/// Only the first exact receipt for each identity is consumed. The caller
|
||||
/// persists the successor checkpoint before cleaning up older replay files.
|
||||
pub fn consume_recorded_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
|
||||
consume_recorded_verified_mrf_repairs(anchors, None)
|
||||
}
|
||||
|
||||
fn consume_recorded_verified_mrf_repairs(anchors: &mut Vec<MrfDurableRepairAnchor>, bucket: Option<&str>) -> usize {
|
||||
let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
|
||||
return 0;
|
||||
};
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
let leases: HashSet<_> = {
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
};
|
||||
if events.is_empty() {
|
||||
events.shrink_to_fit();
|
||||
return 0;
|
||||
}
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| bucket.is_none_or(|bucket| event.bucket.as_ref() == bucket))
|
||||
.filter_map(|event| event.lease)
|
||||
.collect()
|
||||
};
|
||||
consume_verified_mrf_repair_events_from_queue(bucket, anchors, &mut events)
|
||||
let proved = {
|
||||
// The queue bounds the relevant leases. Scan the journal outside the
|
||||
// lock and hash full identities only for those leases.
|
||||
let pending = anchors
|
||||
.iter()
|
||||
.filter(|anchor| leases.contains(&anchor.lease) && bucket.is_none_or(|bucket| anchor.bucket.as_ref() == bucket))
|
||||
.map(|anchor| (anchor.proof_identity(), anchor))
|
||||
.collect();
|
||||
let matched = {
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
};
|
||||
match_recorded_verified_mrf_repairs(&mut events, &pending)
|
||||
};
|
||||
matched.into_iter().cloned().collect()
|
||||
};
|
||||
remove_proved_anchors(anchors, &proved)
|
||||
}
|
||||
|
||||
fn consume_verified_mrf_repair_events_from_queue(
|
||||
bucket: &str,
|
||||
anchors: &mut Vec<MrfDurableRepairAnchor>,
|
||||
events: &mut std::collections::VecDeque<MrfVerifiedRepairEvent>,
|
||||
) -> usize {
|
||||
let before = anchors.len();
|
||||
fn match_recorded_verified_mrf_repairs<'a>(
|
||||
events: &mut VecDeque<MrfVerifiedRepairEvent>,
|
||||
pending: &HashMap<MrfProofIdentity<'_>, &'a MrfDurableRepairAnchor>,
|
||||
) -> HashSet<&'a MrfDurableRepairAnchor> {
|
||||
let previous_event_count = events.len();
|
||||
let mut proved = HashSet::new();
|
||||
events.retain(|event| {
|
||||
if event.bucket.as_ref() != bucket {
|
||||
let Some(anchor) = event.proof_identity().and_then(|identity| pending.get(&identity)) else {
|
||||
return true;
|
||||
}
|
||||
let mut matched = false;
|
||||
anchors.retain(|anchor| {
|
||||
let proven = anchor.is_proven_by(event);
|
||||
matched |= proven;
|
||||
!proven
|
||||
});
|
||||
!matched
|
||||
};
|
||||
!proved.insert(*anchor)
|
||||
});
|
||||
// The old queue rebuild reserved the pre-consumption event count. Reuse
|
||||
// that buffer when possible without extending its capacity lifetime:
|
||||
// an emptied queue releases its backing storage on the next consumption.
|
||||
// Release the backing buffer on an empty pass and keep all unmatched
|
||||
// notices in FIFO order.
|
||||
events.shrink_to(previous_event_count);
|
||||
before.saturating_sub(anchors.len())
|
||||
proved
|
||||
}
|
||||
|
||||
fn remove_proved_anchors(anchors: &mut Vec<MrfDurableRepairAnchor>, proved: &HashSet<MrfDurableRepairAnchor>) -> usize {
|
||||
if proved.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let before = anchors.len();
|
||||
let leases: HashSet<_> = proved.iter().map(|anchor| anchor.lease).collect();
|
||||
anchors.retain(|anchor| !leases.contains(&anchor.lease) || !proved.contains(anchor));
|
||||
before - anchors.len()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -870,6 +922,21 @@ pub struct MrfVerifiedRepairEvent {
|
||||
pub disposition: MrfVerifiedRepairDisposition,
|
||||
}
|
||||
|
||||
impl MrfVerifiedRepairEvent {
|
||||
fn proof_identity(&self) -> Option<MrfProofIdentity<'_>> {
|
||||
Some(MrfProofIdentity {
|
||||
kind: self.kind,
|
||||
bucket: &self.bucket,
|
||||
object: &self.object,
|
||||
version_id: self.version_id,
|
||||
scope: self.scope,
|
||||
delete_marker_purge: self.delete_marker_purge,
|
||||
lease: self.lease?,
|
||||
bucket_incarnation_id: self.bucket_incarnation_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound on the repaired-event backlog. Notices are best-effort hints; when
|
||||
/// the ring is full the oldest are dropped and the affected ledger entries
|
||||
/// simply expire through their own attempts/age limits.
|
||||
@@ -992,6 +1059,15 @@ pub fn note_mrf_unverified_legacy(event: MrfUnverifiedLegacyEvent) {
|
||||
/// Take held-legacy notices for one bucket. The durable ledger still verifies
|
||||
/// the full anchor before changing the journal entry to its held state.
|
||||
pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
take_mrf_unverified_legacy_events_matching(|candidate| candidate == bucket)
|
||||
}
|
||||
|
||||
/// Take held-legacy notices for the supplied buckets in queue order.
|
||||
pub fn take_mrf_unverified_legacy_events_for_buckets(buckets: &HashSet<&str>) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
take_mrf_unverified_legacy_events_matching(|bucket| buckets.contains(bucket))
|
||||
}
|
||||
|
||||
fn take_mrf_unverified_legacy_events_matching(mut matches: impl FnMut(&str) -> bool) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
let Some(registry) = MRF_UNVERIFIED_LEGACY_EVENTS.get() else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -1000,7 +1076,7 @@ pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedL
|
||||
};
|
||||
let mut taken = Vec::new();
|
||||
events.retain(|event| {
|
||||
if event.anchor.bucket.as_ref() == bucket {
|
||||
if matches(&event.anchor.bucket) {
|
||||
taken.push(event.clone());
|
||||
false
|
||||
} else {
|
||||
|
||||
@@ -138,3 +138,70 @@ fn event_presence_keeps_poisoned_legacy_unknown() {
|
||||
assert!(mrf_durable_repair_events_may_be_pending());
|
||||
assert!(registry.is_poisoned(), "the hint must not clear or recover poisoned state");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_consumption_matches_exact_receipts_and_keeps_other_notices() {
|
||||
if isolated("batch_consumption_matches_exact_receipts_and_keeps_other_notices") {
|
||||
return;
|
||||
}
|
||||
let first = MrfDurableRepairAnchor {
|
||||
kind: MrfKind::PartialWrite,
|
||||
bucket: Arc::from("batch-first"),
|
||||
object: Arc::from("same-object"),
|
||||
version_id: None,
|
||||
scope: Some(MrfScope {
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
}),
|
||||
delete_marker_purge: None,
|
||||
lease: MrfIngressLease::new(41),
|
||||
bucket_incarnation_id: Uuid::new_v4(),
|
||||
};
|
||||
let second = MrfDurableRepairAnchor {
|
||||
bucket: Arc::from("batch-second"),
|
||||
..first.clone()
|
||||
};
|
||||
let waiting = MrfDurableRepairAnchor {
|
||||
lease: MrfIngressLease::new(42),
|
||||
..first.clone()
|
||||
};
|
||||
let other = MrfDurableRepairAnchor {
|
||||
bucket: Arc::from("batch-other"),
|
||||
..first.clone()
|
||||
};
|
||||
let proof = |anchor: &MrfDurableRepairAnchor| MrfVerifiedRepairEvent {
|
||||
kind: anchor.kind,
|
||||
bucket: anchor.bucket.clone(),
|
||||
object: anchor.object.clone(),
|
||||
version_id: anchor.version_id,
|
||||
scope: anchor.scope,
|
||||
delete_marker_purge: anchor.delete_marker_purge,
|
||||
lease: Some(anchor.lease),
|
||||
bucket_incarnation_id: anchor.bucket_incarnation_id,
|
||||
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
|
||||
};
|
||||
let stale = MrfVerifiedRepairEvent {
|
||||
bucket_incarnation_id: Uuid::new_v4(),
|
||||
..proof(&waiting)
|
||||
};
|
||||
for event in [proof(&other), proof(&second), proof(&first), stale.clone(), proof(&first)] {
|
||||
note_mrf_verified_repair(event);
|
||||
}
|
||||
let legacy = |anchor: &MrfDurableRepairAnchor| MrfUnverifiedLegacyEvent { anchor: anchor.clone() };
|
||||
for anchor in [&other, &second, &first] {
|
||||
note_mrf_unverified_legacy(legacy(anchor));
|
||||
}
|
||||
|
||||
let mut anchors = vec![first.clone(), waiting.clone(), second.clone(), first.clone()];
|
||||
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
|
||||
assert_eq!(
|
||||
take_mrf_unverified_legacy_events_for_buckets(&buckets),
|
||||
vec![legacy(&second), legacy(&first)]
|
||||
);
|
||||
assert_eq!(consume_recorded_verified_mrf_repair_events(&mut anchors), 3);
|
||||
assert_eq!(anchors, vec![waiting]);
|
||||
assert_eq!(take_mrf_verified_repair_events_for(&first.bucket), vec![stale, proof(&first)]);
|
||||
assert!(take_mrf_verified_repair_events_for(&second.bucket).is_empty());
|
||||
assert_eq!(take_mrf_verified_repair_events_for(&other.bucket), vec![proof(&other)]);
|
||||
assert_eq!(take_mrf_unverified_legacy_events_for(&other.bucket), vec![legacy(&other)]);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,25 @@
|
||||
use super::*;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
fn consume_verified_mrf_repair_events_from_queue(
|
||||
bucket: &str,
|
||||
anchors: &mut Vec<MrfDurableRepairAnchor>,
|
||||
events: &mut VecDeque<MrfVerifiedRepairEvent>,
|
||||
) -> usize {
|
||||
let proved = {
|
||||
let pending = anchors
|
||||
.iter()
|
||||
.filter(|anchor| anchor.bucket.as_ref() == bucket)
|
||||
.map(|anchor| (anchor.proof_identity(), anchor))
|
||||
.collect();
|
||||
match_recorded_verified_mrf_repairs(events, &pending)
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.collect()
|
||||
};
|
||||
remove_proved_anchors(anchors, &proved)
|
||||
}
|
||||
|
||||
fn proof_fixture() -> (MrfDurableRepairAnchor, MrfVerifiedRepairEvent) {
|
||||
let anchor = MrfDurableRepairAnchor {
|
||||
kind: MrfKind::PartialWrite,
|
||||
|
||||
@@ -25,6 +25,14 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
pub const S3VECTORS_MAINTENANCE_SUB_SYS: &str = "s3vectors_maintenance";
|
||||
/// Existing ordinary IAM account selected to execute Vector maintenance.
|
||||
pub const S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT: &str = "execution_account";
|
||||
/// Environment variable enabling or disabling the external S3 Vectors HTTP service.
|
||||
///
|
||||
/// Defaults to `true`. Setting `0`, `false`, `off`, or `no` makes S3 Vectors
|
||||
/// requests fail closed with `503 ServiceUnavailableException` while keeping
|
||||
/// ordinary S3 traffic unaffected.
|
||||
pub const ENV_S3VECTORS_ENABLE: &str = "RUSTFS_S3VECTORS_ENABLE";
|
||||
/// Default enablement for the external S3 Vectors HTTP service.
|
||||
pub const DEFAULT_S3VECTORS_ENABLE: bool = true;
|
||||
|
||||
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
|
||||
/// Defaults to false. Enable only after all possible writers support receipt
|
||||
|
||||
@@ -45,6 +45,9 @@ pub const ENV_CAPACITY_METRICS_INTERVAL: &str = "RUSTFS_CAPACITY_METRICS_INTERVA
|
||||
/// Environment variable for following symbolic links during capacity calculation
|
||||
pub const ENV_CAPACITY_FOLLOW_SYMLINKS: &str = "RUSTFS_CAPACITY_FOLLOW_SYMLINKS";
|
||||
|
||||
/// Use filesystem-reported used space on dedicated drive mounts.
|
||||
pub const ENV_CAPACITY_USE_MOUNT_USAGE: &str = "RUSTFS_CAPACITY_USE_MOUNT_USAGE";
|
||||
|
||||
/// Environment variable for enabling dynamic timeout calculation
|
||||
pub const ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: &str = "RUSTFS_CAPACITY_ENABLE_DYNAMIC_TIMEOUT";
|
||||
|
||||
@@ -94,6 +97,9 @@ pub const DEFAULT_CAPACITY_METRICS_INTERVAL_SECS: u64 = 600;
|
||||
/// Default: false (disabled for safety)
|
||||
pub const DEFAULT_CAPACITY_FOLLOW_SYMLINKS: bool = false;
|
||||
|
||||
/// Use directory scans by default to preserve logical file-size accounting.
|
||||
pub const DEFAULT_CAPACITY_USE_MOUNT_USAGE: bool = false;
|
||||
|
||||
/// Enable dynamic timeout calculation based on directory characteristics
|
||||
/// Default: true (enabled)
|
||||
pub const DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: bool = true;
|
||||
|
||||
@@ -71,15 +71,15 @@ const _: () = assert!(DEFAULT_INTERNODE_RPC_TCP_NODELAY);
|
||||
/// unary responses such as `ReadMultiple` and `BatchReadVersion`. Set to 0 to use the
|
||||
/// `tonic`/`hyper` default. Defaults to 1MiB.
|
||||
pub const ENV_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE";
|
||||
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024;
|
||||
pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024;
|
||||
|
||||
/// HTTP/2 initial connection window size (bytes) for internode gRPC client channels.
|
||||
///
|
||||
/// Should be >= the stream window so multiple concurrent streams are not starved by the
|
||||
/// connection-level flow-control window. Set to 0 to fall back to the library default.
|
||||
/// Defaults to 2MiB.
|
||||
/// Defaults to 16MiB.
|
||||
pub const ENV_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE";
|
||||
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 2 * 1024 * 1024;
|
||||
pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 16 * 1024 * 1024;
|
||||
|
||||
// Compile-time invariant: the connection-level window must be >= the per-stream window, or
|
||||
// concurrent streams would be starved by the connection-level flow-control budget.
|
||||
@@ -284,23 +284,23 @@ pub const DEFAULT_INTERNODE_IDEMPOTENT_READ_RETRIES: usize = 1;
|
||||
|
||||
/// Enable control/bulk internode gRPC channel isolation.
|
||||
///
|
||||
/// Defaults to `false`: this touches lock-RPC transport routing (consistency-sensitive), so it
|
||||
/// is opt-in and validated against a baseline before rollout. When `false`, bulk RPCs reuse the
|
||||
/// control channel exactly as before, so the switch is a single-env rollback.
|
||||
/// Defaults to `true` so bulk `ReadAll`/`WriteAll`/`ReadMultiple`/`BatchReadVersion` transfers
|
||||
/// use dedicated bulk HTTP/2 channels instead of head-of-line blocking latency-sensitive
|
||||
/// `Lock`/`UnLock`/`Refresh`/`DiskInfo` control RPCs under high concurrency. Set
|
||||
/// `RUSTFS_INTERNODE_CHANNEL_ISOLATION=false` for single-env rollback to legacy shared-channel behavior.
|
||||
pub const ENV_INTERNODE_CHANNEL_ISOLATION: &str = "RUSTFS_INTERNODE_CHANNEL_ISOLATION";
|
||||
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = false;
|
||||
pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = true;
|
||||
|
||||
// Compile-time invariant: isolation is opt-in so the default build behaves exactly as before P1.
|
||||
const _: () = assert!(!DEFAULT_INTERNODE_CHANNEL_ISOLATION);
|
||||
// Compile-time invariant: channel isolation defaults on so bulk data RPCs cannot starve lock/quorum RPCs.
|
||||
const _: () = assert!(DEFAULT_INTERNODE_CHANNEL_ISOLATION);
|
||||
|
||||
/// Number of bulk channels maintained per peer when channel isolation is enabled.
|
||||
///
|
||||
/// A tonic `Channel` is a single TCP/HTTP2 connection; multiple bulk channels are round-robined
|
||||
/// to relieve the single-connection throughput ceiling for large transfers. Kept small (default
|
||||
/// 2) to avoid a connection storm; clamped to at least 1. Set to 1 to isolate bulk onto a single
|
||||
/// dedicated connection (still separate from control).
|
||||
/// to relieve the single-connection throughput ceiling for large transfers. Defaults to 4 (matching
|
||||
/// typical 4-drive-per-node stripes); clamped to at least 1.
|
||||
pub const ENV_INTERNODE_BULK_CHANNELS: &str = "RUSTFS_INTERNODE_BULK_CHANNELS";
|
||||
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 2;
|
||||
pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 4;
|
||||
|
||||
/// Optional receive-window overrides for isolated bulk channels. When unset, inherit the
|
||||
/// corresponding `RUSTFS_INTERNODE_RPC_HTTP2_*` setting. Zero selects the library default.
|
||||
@@ -310,7 +310,7 @@ pub const ENV_INTERNODE_BULK_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_BU
|
||||
/// Transport admission and pending-buffer limits for isolated bulk channels. These limits
|
||||
/// apply to the tonic service; complete unary bodies are observed separately by RPC metrics.
|
||||
pub const ENV_INTERNODE_BULK_CONCURRENCY_LIMIT: &str = "RUSTFS_INTERNODE_BULK_CONCURRENCY_LIMIT";
|
||||
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 64;
|
||||
pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 128;
|
||||
pub const ENV_INTERNODE_BULK_BUFFER_SIZE: &str = "RUSTFS_INTERNODE_BULK_BUFFER_SIZE";
|
||||
pub const DEFAULT_INTERNODE_BULK_BUFFER_SIZE: usize = 1024;
|
||||
|
||||
@@ -501,8 +501,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn internode_rpc_channel_tuning_defaults() {
|
||||
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 1024 * 1024);
|
||||
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 2 * 1024 * 1024);
|
||||
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 4 * 1024 * 1024);
|
||||
assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 16 * 1024 * 1024);
|
||||
// The nodelay-on and connection-window >= stream-window invariants are enforced at
|
||||
// compile time next to the constant definitions.
|
||||
}
|
||||
@@ -525,8 +525,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn internode_channel_isolation_defaults_and_env_names() {
|
||||
// The isolation-off default is asserted at compile time next to the constant definition.
|
||||
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 2);
|
||||
// The isolation-on default is asserted at compile time next to the constant definition.
|
||||
assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 4);
|
||||
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, 0);
|
||||
assert_eq!(DEFAULT_INTERNODE_BULK_BODY_WAIT_TIMEOUT_MS, 1_000);
|
||||
assert_eq!(ENV_INTERNODE_CHANNEL_ISOLATION, "RUSTFS_INTERNODE_CHANNEL_ISOLATION");
|
||||
|
||||
@@ -482,7 +482,7 @@ pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MIN_SIZE_BYTES: usize = 0;
|
||||
/// A short wait smooths transient bursts while still returning S3
|
||||
/// `SlowDown`/503 before body ingest when the node is already saturated.
|
||||
pub const ENV_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = "RUSTFS_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS";
|
||||
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250;
|
||||
pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 2_000;
|
||||
|
||||
/// Time in milliseconds a multipart UploadPart waits for a foreground write permit.
|
||||
///
|
||||
|
||||
@@ -11,9 +11,9 @@ use std::fs::{self, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::Path;
|
||||
|
||||
const MAX_BINARY_BYTES: u64 = 1_073_741_824;
|
||||
const MAX_CATALOG_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_SYMBOLS: usize = 200_000;
|
||||
const MAX_BINARY_BYTES: u64 = 2 * 1_073_741_824;
|
||||
const MAX_CATALOG_BYTES: usize = 128 * 1024 * 1024;
|
||||
const MAX_SYMBOLS: usize = 500_000;
|
||||
const NORMALIZATION: &str = "pyroscope-2.1.1-symbolic-demangle-13.9.0";
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -251,13 +251,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn release_sized_catalog_retains_all_function_names() {
|
||||
let binary = bulk_executable(110_000, 160);
|
||||
// Exercises above the observed release GNU binary footprint (~268,737 symbols / ~62.5 MiB JSON).
|
||||
let binary = bulk_executable(280_000, 200);
|
||||
let encoded = catalog(&binary, &"a".repeat(40), "x86_64-unknown-linux-gnu", vec!["pyroscope".into()])
|
||||
.expect("retain complete bounded symbol catalog");
|
||||
assert!(encoded.len() > 16 * 1024 * 1024);
|
||||
assert!(encoded.len() > 60 * 1024 * 1024);
|
||||
assert!(encoded.len() <= MAX_CATALOG_BYTES);
|
||||
let value: serde_json::Value = serde_json::from_slice(&encoded).expect("catalog JSON");
|
||||
assert_eq!(value["symbols"].as_array().expect("symbol array").len(), 110_000);
|
||||
assert_eq!(value["symbols"].as_array().expect("symbol array").len(), 280_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -273,7 +274,7 @@ mod tests {
|
||||
assert!(too_many.to_string().contains("reviewed symbol limit"));
|
||||
|
||||
let too_large = catalog(
|
||||
&bulk_executable(10_000, 3_500),
|
||||
&bulk_executable(38_000, 3_500),
|
||||
&source,
|
||||
"x86_64-unknown-linux-gnu",
|
||||
vec!["pyroscope".into()],
|
||||
|
||||
@@ -54,6 +54,9 @@ pub const DATA_USAGE_OBJECT_NAME: &str = ".usage.v2.json";
|
||||
/// [`DATA_USAGE_OBJECT_NAME`], this object is never authoritative for quota
|
||||
/// admission because namespace activity may have raced the scan.
|
||||
pub const DATA_USAGE_OBSERVED_OBJECT_NAME: &str = ".usage.observed.json";
|
||||
/// Completed bucket measurements between full namespace snapshots. Older
|
||||
/// leaders keep reading the unchanged authoritative object during rollout.
|
||||
pub const DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME: &str = ".usage.buckets.json";
|
||||
|
||||
/// Usage snapshot written by scanner implementations predating distributed
|
||||
/// leadership fencing. It is read only when neither authoritative snapshot
|
||||
@@ -634,6 +637,21 @@ pub struct DataUsageInfo {
|
||||
/// authoritative usage snapshot yet.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub usage_snapshot_bootstrap_pending: bool,
|
||||
/// Only an initial bootstrap can authorize display of first-scan progress.
|
||||
/// Recovery, reset and older markers leave this false across restarts.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub usage_snapshot_initial_bootstrap: bool,
|
||||
/// Present only on the independent completed-bucket snapshot object.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_certified_buckets: Option<CertifiedBucketsScope>,
|
||||
/// An older writer drops this opt-in, disabling initial fallback.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_initial_view_version: Option<u16>,
|
||||
/// Non-first barriers are durable before bucket-sidecar publication.
|
||||
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub usage_snapshot_noninitial_buckets: HashMap<String, String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_rebuild_generation: Option<String>,
|
||||
/// Deprecated kept here for backward compatibility reasons
|
||||
pub bucket_sizes: HashMap<String, u64>,
|
||||
/// Per-disk snapshot information when available
|
||||
@@ -654,6 +672,25 @@ pub struct DataUsageSnapshotIdentity {
|
||||
pub scanner_epoch: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct CertifiedBucketsScope {
|
||||
pub version: u16,
|
||||
pub baseline_initial_bootstrap: bool,
|
||||
pub baseline_bootstrap_pending: bool,
|
||||
pub movement_generation: u64,
|
||||
pub sources: Vec<CertifiedBucketsSource>,
|
||||
pub bucket_incarnations: HashMap<String, String>,
|
||||
pub baseline: DataUsageSnapshotIdentity,
|
||||
pub baseline_rebuild_generation: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct CertifiedBucketsSource {
|
||||
pub pool_index: u64,
|
||||
pub set_index: u64,
|
||||
pub layout: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct DataUsageSegmentInvalidationProof {
|
||||
#[serde(default)]
|
||||
@@ -687,6 +724,149 @@ pub struct DataUsageSnapshotSetState {
|
||||
}
|
||||
|
||||
impl DataUsageInfo {
|
||||
/// Whether the canonical root can supply completed values to a persisted usage view.
|
||||
pub fn is_completed_usage_baseline(&self) -> bool {
|
||||
self.is_complete_bucket_usage_snapshot()
|
||||
&& !self.usage_snapshot_observational
|
||||
&& !self.usage_snapshot_partial
|
||||
&& self.usage_snapshot_certified_buckets.is_none()
|
||||
}
|
||||
|
||||
/// A bootstrap marker records ownership and history before a namespace baseline exists.
|
||||
/// It cannot contain measurements, observations or partial coverage.
|
||||
pub fn has_usage_bootstrap_marker_shape(&self) -> bool {
|
||||
self.usage_snapshot_bootstrap_pending
|
||||
&& self.last_update.is_some()
|
||||
&& self
|
||||
== &Self {
|
||||
last_update: self.last_update,
|
||||
scanner_epoch: self.scanner_epoch,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_rebuild_generation: self.usage_snapshot_rebuild_generation.clone(),
|
||||
usage_snapshot_initial_bootstrap: self.usage_snapshot_initial_bootstrap,
|
||||
usage_snapshot_initial_view_version: self.usage_snapshot_initial_view_version,
|
||||
usage_snapshot_noninitial_buckets: self.usage_snapshot_noninitial_buckets.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Ownership fencing alone does not refresh a completed measurement.
|
||||
pub fn certified_buckets_match_baseline(&self, baseline: &Self) -> bool {
|
||||
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
|
||||
(baseline.is_completed_usage_baseline() || baseline.has_usage_bootstrap_marker_shape())
|
||||
&& self.is_certified_buckets_snapshot()
|
||||
&& scope.baseline.last_update == baseline.last_update
|
||||
&& scope.baseline.scanner_cycle == baseline.scanner_cycle
|
||||
&& baseline.scanner_epoch >= scope.baseline.scanner_epoch
|
||||
&& scope.baseline_initial_bootstrap == baseline.usage_snapshot_initial_bootstrap
|
||||
&& scope.baseline_bootstrap_pending == baseline.usage_snapshot_bootstrap_pending
|
||||
&& scope.baseline_rebuild_generation == baseline.usage_snapshot_rebuild_generation
|
||||
}
|
||||
/// Keep earlier complete bucket values under the same persisted scope.
|
||||
pub fn retain_prior_certified_buckets(&mut self, previous: &Self) -> bool {
|
||||
let (Some(current), Some(old)) = (&self.usage_snapshot_certified_buckets, &previous.usage_snapshot_certified_buckets)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
if !previous.is_certified_buckets_snapshot()
|
||||
|| current.baseline.last_update != old.baseline.last_update
|
||||
|| current.baseline.scanner_cycle != old.baseline.scanner_cycle
|
||||
|| current.baseline.scanner_epoch < old.baseline.scanner_epoch
|
||||
|| current.baseline_rebuild_generation != old.baseline_rebuild_generation
|
||||
|| current.baseline_initial_bootstrap != old.baseline_initial_bootstrap
|
||||
|| current.baseline_bootstrap_pending != old.baseline_bootstrap_pending
|
||||
|| current.movement_generation != old.movement_generation
|
||||
|| current.sources != old.sources
|
||||
{
|
||||
return true;
|
||||
}
|
||||
for (bucket, usage) in &previous.buckets_usage {
|
||||
if usage.bucket_incarnation.as_ref() == current.bucket_incarnations.get(bucket) {
|
||||
let replace = self.buckets_usage.get(bucket).is_none_or(|current| {
|
||||
match (usage.usage_certification, current.usage_certification) {
|
||||
(Some(old), Some(next)) => {
|
||||
(old.epoch, old.cycle, old.certified_at) > (next.epoch, next.cycle, next.certified_at)
|
||||
}
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
if replace {
|
||||
self.buckets_usage.insert(bucket.clone(), usage.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
|
||||
self.checked_calculate_totals() && self.is_certified_buckets_snapshot()
|
||||
}
|
||||
|
||||
/// Validate the independent bucket snapshot without granting whole-cycle
|
||||
/// convergence, namespace completeness or dirty-usage acknowledgement.
|
||||
pub fn is_certified_buckets_snapshot(&self) -> bool {
|
||||
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
|
||||
let (Some(epoch), Some(cycle), Some(updated_at)) = (self.scanner_epoch, self.scanner_cycle, self.last_update) else {
|
||||
return false;
|
||||
};
|
||||
if scope.version != 1
|
||||
|| scope.sources.is_empty()
|
||||
|| !scope
|
||||
.sources
|
||||
.windows(2)
|
||||
.all(|pair| (pair[0].pool_index, pair[0].set_index) < (pair[1].pool_index, pair[1].set_index))
|
||||
|| scope.sources.iter().any(|source| source.layout == [0; 32])
|
||||
|| self.usage_snapshot_authoritative_baseline != Some(scope.baseline)
|
||||
|| scope.baseline.last_update.is_none()
|
||||
|| self.usage_snapshot_complete
|
||||
|| self.usage_snapshot_converged == Some(true)
|
||||
|| !self.usage_snapshot_partial
|
||||
|| self.usage_snapshot_observational
|
||||
|| self.usage_snapshot_admin_projection
|
||||
|| self.usage_snapshot_bootstrap_pending
|
||||
|| self.buckets_usage.is_empty()
|
||||
|| u64::try_from(self.buckets_usage.len()).ok() != Some(self.buckets_count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut objects = 0_u64;
|
||||
let mut bytes = 0_u64;
|
||||
let mut versions = 0_u64;
|
||||
let mut markers = 0_u64;
|
||||
for (bucket, usage) in &self.buckets_usage {
|
||||
let Some(certificate) = usage.usage_certification else { return false };
|
||||
if usage.bucket_incarnation.as_ref() != scope.bucket_incarnations.get(bucket)
|
||||
|| usage.bucket_incarnation.is_none()
|
||||
|| !matches!(
|
||||
usage.usage_value_state,
|
||||
Some(crate::BucketUsageValueState::Certified | crate::BucketUsageValueState::Carried)
|
||||
)
|
||||
|| (certificate.epoch, certificate.cycle) > (epoch, cycle)
|
||||
|| certificate.certified_at > updated_at
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let (Some(next_objects), Some(next_bytes)) =
|
||||
(objects.checked_add(usage.objects_count), bytes.checked_add(usage.size))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
objects = next_objects;
|
||||
bytes = next_bytes;
|
||||
let (Some(next_versions), Some(next_markers)) = (
|
||||
versions.checked_add(usage.versions_count),
|
||||
markers.checked_add(usage.delete_markers_count),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
versions = next_versions;
|
||||
markers = next_markers;
|
||||
}
|
||||
objects == self.objects_total_count
|
||||
&& bytes == self.objects_total_size
|
||||
&& versions == self.versions_total_count
|
||||
&& markers == self.delete_markers_total_count
|
||||
}
|
||||
|
||||
pub fn snapshot_identity(&self) -> DataUsageSnapshotIdentity {
|
||||
DataUsageSnapshotIdentity {
|
||||
last_update: self.last_update,
|
||||
@@ -2457,6 +2637,24 @@ impl DataUsageInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update all scalar totals atomically, rejecting overflow without wrapping.
|
||||
pub fn checked_calculate_totals(&mut self) -> bool {
|
||||
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
|
||||
Some([
|
||||
total[0].checked_add(usage.objects_count)?,
|
||||
total[1].checked_add(usage.size)?,
|
||||
total[2].checked_add(usage.versions_count)?,
|
||||
total[3].checked_add(usage.delete_markers_count)?,
|
||||
])
|
||||
});
|
||||
let Some([objects, size, versions, markers]) = totals else { return false };
|
||||
self.objects_total_count = objects;
|
||||
self.objects_total_size = size;
|
||||
self.versions_total_count = versions;
|
||||
self.delete_markers_total_count = markers;
|
||||
true
|
||||
}
|
||||
|
||||
/// Merge another DataUsageInfo into this one
|
||||
pub fn merge(&mut self, other: &DataUsageInfo) {
|
||||
// Merge bucket usage
|
||||
@@ -2653,6 +2851,117 @@ pub struct CompressionTotalInfo {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn complete_bucket_sidecar() -> (DataUsageInfo, DataUsageInfo) {
|
||||
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
|
||||
let baseline = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
scanner_epoch: Some(1),
|
||||
scanner_cycle: Some(2),
|
||||
usage_snapshot_complete: true,
|
||||
..Default::default()
|
||||
};
|
||||
let id = "00000000-0000-0000-0000-000000000001".to_owned();
|
||||
let mut usage = BucketUsageInfo {
|
||||
size: 71,
|
||||
objects_count: 7,
|
||||
versions_count: 8,
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
usage.certify(crate::BucketUsageCertification {
|
||||
epoch: 3,
|
||||
cycle: 4,
|
||||
certified_at: time,
|
||||
});
|
||||
let mut data = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
scanner_epoch: Some(3),
|
||||
scanner_cycle: Some(4),
|
||||
usage_snapshot_partial: true,
|
||||
buckets_count: 1,
|
||||
buckets_usage: HashMap::from([("bucket".into(), usage)]),
|
||||
usage_snapshot_authoritative_baseline: Some(baseline.snapshot_identity()),
|
||||
usage_snapshot_certified_buckets: Some(CertifiedBucketsScope {
|
||||
version: 1,
|
||||
baseline: baseline.snapshot_identity(),
|
||||
baseline_initial_bootstrap: false,
|
||||
baseline_bootstrap_pending: false,
|
||||
baseline_rebuild_generation: None,
|
||||
movement_generation: 0,
|
||||
sources: vec![CertifiedBucketsSource {
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
layout: [1; 32],
|
||||
}],
|
||||
bucket_incarnations: HashMap::from([("bucket".into(), id)]),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
data.calculate_totals();
|
||||
(baseline, data)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_is_not_whole_namespace_or_observational_usage() {
|
||||
let (mut baseline, data) = complete_bucket_sidecar();
|
||||
assert!(data.is_certified_buckets_snapshot());
|
||||
assert!(!data.is_complete_bucket_usage_snapshot());
|
||||
assert!(data.certified_buckets_match_baseline(&baseline));
|
||||
baseline.scanner_epoch = Some(5);
|
||||
assert!(
|
||||
data.certified_buckets_match_baseline(&baseline),
|
||||
"owner fencing must retain the original complete bucket value"
|
||||
);
|
||||
baseline.usage_snapshot_rebuild_generation = Some("reset".into());
|
||||
assert!(!data.certified_buckets_match_baseline(&baseline));
|
||||
let mut bad = data.clone();
|
||||
bad.versions_total_count += 1;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
let mut bad = data.clone();
|
||||
bad.buckets_usage.get_mut("bucket").expect("bucket").usage_certification = None;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
let mut bad = data;
|
||||
bad.usage_snapshot_observational = true;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_retains_newer_sidecar_value_over_carried_primary_value() {
|
||||
let (_, previous) = complete_bucket_sidecar();
|
||||
let mut candidate = previous.clone();
|
||||
candidate.scanner_cycle = Some(5);
|
||||
let carried = candidate.buckets_usage.get_mut("bucket").expect("carried bucket");
|
||||
carried.objects_count = 1;
|
||||
carried.usage_certification.as_mut().expect("certificate").cycle = 3;
|
||||
let id = "00000000-0000-0000-0000-000000000002".to_owned();
|
||||
let mut next = BucketUsageInfo {
|
||||
size: 20,
|
||||
objects_count: 2,
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
next.certify(crate::BucketUsageCertification {
|
||||
epoch: 3,
|
||||
cycle: 5,
|
||||
certified_at: candidate.last_update.expect("timestamp"),
|
||||
});
|
||||
candidate
|
||||
.usage_snapshot_certified_buckets
|
||||
.as_mut()
|
||||
.expect("scope")
|
||||
.bucket_incarnations
|
||||
.insert("new".into(), id);
|
||||
candidate.buckets_usage.insert("new".into(), next);
|
||||
assert!(candidate.retain_prior_certified_buckets(&previous));
|
||||
assert_eq!(candidate.buckets_usage["bucket"].objects_count, 7);
|
||||
assert_eq!(
|
||||
candidate.buckets_usage["bucket"].usage_certification,
|
||||
previous.buckets_usage["bucket"].usage_certification
|
||||
);
|
||||
assert_eq!((candidate.objects_total_count, candidate.objects_total_size), (9, 91));
|
||||
assert_eq!(candidate.buckets_usage["new"].objects_count, 2);
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct LegacyUsageReader {
|
||||
buckets_count: u64,
|
||||
|
||||
@@ -47,6 +47,10 @@ pub struct BucketScanProgressSource {
|
||||
/// Accepted logical object usage; enumeration alone leaves both absent.
|
||||
pub objects: Option<u64>,
|
||||
pub size: Option<u64>,
|
||||
/// Why this sample has not completed its sweep, when the writer knows.
|
||||
/// Display-only; it never authorizes reuse or quota admission.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocker: Option<String>,
|
||||
}
|
||||
|
||||
/// Response-only progress, deliberately separate from a bucket's total usage.
|
||||
@@ -58,6 +62,15 @@ pub struct BucketScanProgress {
|
||||
pub size: Option<u64>,
|
||||
pub sources_observed: u64,
|
||||
pub sources_total: u64,
|
||||
/// True while this sample is not an authoritative complete sweep.
|
||||
#[serde(default)]
|
||||
pub partial: bool,
|
||||
/// True only when every expected source completed and agrees.
|
||||
#[serde(default)]
|
||||
pub converged: bool,
|
||||
/// The dominant incomplete stage, or `unknown` when no writer reported one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocker: Option<String>,
|
||||
}
|
||||
|
||||
impl BucketScanProgressSource {
|
||||
@@ -120,6 +133,21 @@ pub fn aggregate_bucket_scan_progress(
|
||||
}
|
||||
}
|
||||
let complete = selected.len() == expected.len() && selected.values().all(|s| s.stage == BucketScanStage::Completed);
|
||||
let blockers = selected
|
||||
.values()
|
||||
.filter_map(|sample| sample.blocker.as_deref())
|
||||
.filter(|blocker| !blocker.is_empty())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
let blocker = if complete {
|
||||
None
|
||||
} else {
|
||||
match blockers.len() {
|
||||
// Samples written before the blocker field existed remain readable.
|
||||
0 => Some("unknown".to_owned()),
|
||||
1 => blockers.first().map(|blocker| (*blocker).to_owned()),
|
||||
_ => Some("multiple".to_owned()),
|
||||
}
|
||||
};
|
||||
Some(BucketScanProgress {
|
||||
stage: if complete {
|
||||
BucketScanStage::Completed
|
||||
@@ -135,6 +163,9 @@ pub fn aggregate_bucket_scan_progress(
|
||||
size,
|
||||
sources_observed: u64::try_from(selected.len()).ok()?,
|
||||
sources_total: u64::try_from(expected.len()).ok()?,
|
||||
partial: !complete,
|
||||
converged: complete,
|
||||
blocker,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -158,6 +189,7 @@ mod tests {
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(77),
|
||||
blocker: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,6 +240,43 @@ mod tests {
|
||||
assert!(aggregate_bucket_scan_progress([sample(0), huge], &[(0, 0), (0, 1)]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_progress_reports_blocker_and_completion_converges() {
|
||||
let mut scanning = sample(0);
|
||||
scanning.blocker = Some("object_budget".into());
|
||||
let partial = aggregate_bucket_scan_progress([scanning], &[(0, 0)]).expect("partial progress");
|
||||
assert!(partial.partial);
|
||||
assert!(!partial.converged);
|
||||
assert_eq!(partial.blocker.as_deref(), Some("object_budget"));
|
||||
|
||||
let mut one = sample(0);
|
||||
one.stage = BucketScanStage::Completed;
|
||||
one.blocker = None;
|
||||
let mut two = sample(1);
|
||||
two.stage = BucketScanStage::Completed;
|
||||
two.blocker = None;
|
||||
let done = aggregate_bucket_scan_progress([one, two], &[(0, 0), (0, 1)]).expect("completed progress");
|
||||
assert!(!done.partial);
|
||||
assert!(done.converged);
|
||||
assert_eq!(done.blocker, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregate_progress_defaults_new_state_for_old_readers() {
|
||||
let decoded: BucketScanProgress = serde_json::from_value(serde_json::json!({
|
||||
"stage": "scanning",
|
||||
"updated_at": 1000,
|
||||
"objects": 7,
|
||||
"size": 77,
|
||||
"sources_observed": 1,
|
||||
"sources_total": 2
|
||||
}))
|
||||
.expect("legacy aggregate progress");
|
||||
assert!(!decoded.partial);
|
||||
assert!(!decoded.converged);
|
||||
assert_eq!(decoded.blocker, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_cannot_cross_bucket_incarnation_or_movement_generation() {
|
||||
let one = sample(0);
|
||||
|
||||
@@ -613,6 +613,130 @@ mod integration_tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A recount must still reclaim deleted bytes while other writes keep landing.
|
||||
///
|
||||
/// Same-size overwrites admit no growth, but each one reserves and saves the
|
||||
/// durable ledger. A recount that discards its scan whenever another write
|
||||
/// overlaps it never publishes under this load, so deleted bytes stay charged.
|
||||
#[tokio::test]
|
||||
async fn test_quota_admits_fitting_put_while_overwrites_continue() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
const KIB: usize = 1024;
|
||||
const HOT_KEYS: usize = 4;
|
||||
|
||||
init_logging();
|
||||
let env = QuotaTestEnv::new().await?;
|
||||
env.create_bucket().await?;
|
||||
env.set_bucket_quota(100 * KIB as u64).await?;
|
||||
|
||||
for index in 0..8 {
|
||||
env.upload_object(&format!("fill-{index}"), 10 * KIB).await?;
|
||||
}
|
||||
for index in 0..HOT_KEYS {
|
||||
env.upload_object(&format!("hot-{index}"), KIB).await?;
|
||||
}
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let overwrites = Arc::new(AtomicU64::new(0));
|
||||
let mut writers = Vec::with_capacity(HOT_KEYS);
|
||||
for index in 0..HOT_KEYS {
|
||||
let client = env.client.clone();
|
||||
let bucket = env.bucket_name.clone();
|
||||
let stop = Arc::clone(&stop);
|
||||
let overwrites = Arc::clone(&overwrites);
|
||||
writers.push(tokio::spawn(async move {
|
||||
let key = format!("hot-{index}");
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
client
|
||||
.put_object()
|
||||
.bucket(&bucket)
|
||||
.key(&key)
|
||||
.body(aws_sdk_s3::primitives::ByteStream::from(vec![0u8; KIB]))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| format!("overwrite of {key} failed: {error:?}"))?;
|
||||
overwrites.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Ok::<(), String>(())
|
||||
}));
|
||||
}
|
||||
|
||||
// Deletes give no immediate credit: 34 KiB stays live, the ledger keeps 84 KiB.
|
||||
for index in 0..5 {
|
||||
env.client
|
||||
.delete_object()
|
||||
.bucket(&env.bucket_name)
|
||||
.key(format!("fill-{index}"))
|
||||
.send()
|
||||
.await?;
|
||||
}
|
||||
|
||||
let overwrites_before = overwrites.load(Ordering::Relaxed);
|
||||
let admission = async {
|
||||
loop {
|
||||
let result = env
|
||||
.client
|
||||
.put_object()
|
||||
.bucket(&env.bucket_name)
|
||||
.key("fit")
|
||||
.body(aws_sdk_s3::primitives::ByteStream::from(vec![0u8; 30 * KIB]))
|
||||
.send()
|
||||
.await;
|
||||
match result {
|
||||
Ok(_) => break,
|
||||
Err(error) => assert_quota_rejection(
|
||||
error.raw_response().map(|response| response.status().as_u16()),
|
||||
error.as_service_error(),
|
||||
&error,
|
||||
),
|
||||
}
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
};
|
||||
// Allow the 30-second reconciliation cooldown to elapse more than once.
|
||||
let admitted = timeout(Duration::from_secs(90), admission).await;
|
||||
let overwrites_during = overwrites.load(Ordering::Relaxed) - overwrites_before;
|
||||
|
||||
// 64 KiB is live now; 40 KiB more exceeds the 100 KiB limit even with an exact count.
|
||||
let over_limit = if admitted.is_ok() {
|
||||
Some(
|
||||
env.client
|
||||
.put_object()
|
||||
.bucket(&env.bucket_name)
|
||||
.key("over")
|
||||
.body(aws_sdk_s3::primitives::ByteStream::from(vec![0u8; 40 * KIB]))
|
||||
.send()
|
||||
.await,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
for writer in writers {
|
||||
writer.await??;
|
||||
}
|
||||
|
||||
assert!(
|
||||
admitted.is_ok(),
|
||||
"a 30 KiB PUT was not admitted within 90 seconds while overwrites continued ({overwrites_during} overwrites)"
|
||||
);
|
||||
assert!(overwrites_during > 0, "overwrites must stay active while the fitting PUT is retried");
|
||||
let error = over_limit
|
||||
.expect("over-limit PUT runs after admission")
|
||||
.expect_err("PUT above the remaining quota must be rejected");
|
||||
assert_quota_rejection(
|
||||
error.raw_response().map(|response| response.status().as_u16()),
|
||||
error.as_service_error(),
|
||||
&error,
|
||||
);
|
||||
|
||||
env.cleanup_bucket().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_quota_usage_tracking() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
init_logging();
|
||||
|
||||
@@ -56,6 +56,15 @@ async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str)
|
||||
Ok(response.error_for_status()?.json().await?)
|
||||
}
|
||||
|
||||
async fn account_bucket(env: &RustFSTestEnvironment, resource: &str) -> TestResult<serde_json::Value> {
|
||||
let account: serde_json::Value = admin(env, resource).await?;
|
||||
account["buckets"]
|
||||
.as_array()
|
||||
.and_then(|buckets| buckets.iter().find(|bucket| bucket["name"] == BUCKET))
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("accountinfo omitted visible bucket {BUCKET}").into())
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -135,6 +144,20 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
// The checkpoint and its display companion commit independently. Wait for
|
||||
// both before terminating the process to exercise the actual first-scan API.
|
||||
let row = account_bucket(&env, "accountinfo?view=snapshot").await?;
|
||||
if row["initial_scan"] != true {
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
assert!(row.get("objects").is_none() && row.get("size").is_none(), "{row}");
|
||||
let progress = &row["scan_progress"];
|
||||
assert_eq!(progress["sources_observed"], 1);
|
||||
assert_eq!(progress["sources_total"], 1);
|
||||
assert!(progress["updated_at"].as_u64().is_some_and(|ts| ts > 0));
|
||||
assert_eq!(progress["partial"], true);
|
||||
assert_eq!(progress["converged"], false);
|
||||
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
|
||||
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
|
||||
}
|
||||
@@ -143,6 +166,8 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
|
||||
let ordinary = account_bucket(&env, "accountinfo").await?;
|
||||
assert!(ordinary.get("initial_scan").is_none(), "default account view opted into initial progress");
|
||||
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
|
||||
assert!(
|
||||
partial
|
||||
@@ -192,6 +217,16 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
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));
|
||||
let completed = account_bucket(&env, "accountinfo?view=snapshot").await?;
|
||||
assert_eq!(completed["initial_scan"], false);
|
||||
assert!(completed.get("scan_progress").is_none());
|
||||
assert_eq!(completed["objects"], count);
|
||||
assert_eq!(completed["size"], bytes);
|
||||
let snapshot: serde_json::Value = admin(&env, "datausageinfo?view=snapshot").await?;
|
||||
assert_eq!(snapshot["snapshot_view"], true);
|
||||
assert_eq!(snapshot["buckets_usage"][BUCKET]["objects_count"], count);
|
||||
assert_eq!(snapshot["buckets_usage"][BUCKET]["size"], bytes);
|
||||
assert!(snapshot["initial_scan_progress"].get(BUCKET).is_none());
|
||||
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
|
||||
|
||||
@@ -242,10 +242,10 @@ metrics = { workspace = true }
|
||||
# io-uring integration; only the tokio "io-uring" runtime feature is banned.
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Native completion owners keep physical I/O leases alive after cancellation.
|
||||
rustfs-uring = { git = "https://github.com/rustfs/uring.git", rev = "eb8fc160e71d804427de1e905f5c226d580f71bf" }
|
||||
rustfs-uring = "0.4.0"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dev-dependencies]
|
||||
rustfs-uring = { git = "https://github.com/rustfs/uring.git", rev = "eb8fc160e71d804427de1e905f5c226d580f71bf", features = ["fault-injection"] }
|
||||
rustfs-uring = { version = "0.4.0", features = ["fault-injection"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winapi-util.workspace = true
|
||||
|
||||
@@ -192,8 +192,8 @@ pub mod bucket {
|
||||
BUCKET_REPLICATION_CONFIG, BUCKET_REQUEST_PAYMENT_CONFIG, BUCKET_SSECONFIG, BUCKET_TABLE_CATALOG_META_PREFIX,
|
||||
BUCKET_TABLE_CATALOG_TABLE_BUCKETS_PREFIX, BUCKET_TABLE_CONFIG, BUCKET_TABLE_RESERVED_PREFIX, BUCKET_TAGGING_CONFIG,
|
||||
BUCKET_TARGETS_FILE, BUCKET_VECTOR_STORAGE_PREFIX, BUCKET_VERSIONING_CONFIG, BUCKET_WEBSITE_CONFIG, BucketMetadata,
|
||||
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, load_bucket_metadata,
|
||||
table_catalog_path_hash, unreadable_config_refusal,
|
||||
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, is_vector_pagination_session,
|
||||
load_bucket_metadata, table_catalog_path_hash, unreadable_config_refusal,
|
||||
};
|
||||
pub use crate::bucket::metadata::{
|
||||
BUCKET_DURABILITY_CONFIG, BUCKET_ETAG_CONFIG, BUCKET_ON_DEMAND_MIGRATION_CONFIG, MAX_SWIFT_METADATA_COUNT,
|
||||
@@ -453,8 +453,9 @@ pub mod data_usage {
|
||||
};
|
||||
#[cfg(feature = "test-util")]
|
||||
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
|
||||
pub use crate::data_usage::{AdminUsageSnapshot, load_admin_usage_snapshot};
|
||||
pub use crate::data_usage::{
|
||||
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
|
||||
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME, PutUsageReceipt,
|
||||
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
|
||||
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations,
|
||||
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
|
||||
@@ -672,6 +673,7 @@ pub mod rio {
|
||||
}
|
||||
|
||||
pub mod rpc {
|
||||
pub use crate::cluster::rpc::{current_propagated_request_id, in_propagated_request_id, with_captured_request_id};
|
||||
#[cfg(all(feature = "test-util", feature = "internode-transport"))]
|
||||
pub mod test_util {
|
||||
/// Build a remote disk using a controlled transport and no health monitor.
|
||||
|
||||
@@ -5692,26 +5692,25 @@ const _MAX_RESTORE_OBJECT_REQUEST_SIZE: i64 = 2 << 20;
|
||||
|
||||
/// Builds an exact-version lifecycle delete target with the concrete
|
||||
/// generation observed by the evaluator. The null S3 version ID is reusable,
|
||||
/// so null data versions additionally require a write-unique data directory.
|
||||
/// so a null data version needs a body revision that survives pool movement.
|
||||
pub fn lifecycle_version_delete_target(oi: &ObjectInfo) -> Option<ObjectToDelete> {
|
||||
let version_id = oi.version_id?;
|
||||
if version_id.is_nil()
|
||||
&& ((!oi.delete_marker && oi.data_dir.is_none_or(|data_dir| data_dir.is_nil()))
|
||||
|| (oi.delete_marker && oi.mod_time.is_none_or(|mod_time| mod_time == OffsetDateTime::UNIX_EPOCH)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let target = ObjectToDelete {
|
||||
object_name: oi.name.clone(),
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
};
|
||||
Some(if version_id.is_nil() {
|
||||
target.with_expected_identity(oi.data_dir, oi.mod_time, oi.delete_marker)
|
||||
if !version_id.is_nil() {
|
||||
return Some(target);
|
||||
}
|
||||
let revision = if oi.delete_marker {
|
||||
oi.mod_time.filter(|time| *time != OffsetDateTime::UNIX_EPOCH)?;
|
||||
oi.data_dir
|
||||
} else {
|
||||
target
|
||||
})
|
||||
oi.data_dir.filter(|id| !id.is_nil())?;
|
||||
oi.logical_body_revision()
|
||||
};
|
||||
Some(target.with_expected_identity(revision, oi.mod_time, oi.delete_marker))
|
||||
}
|
||||
|
||||
pub async fn eval_action_from_lifecycle(
|
||||
|
||||
@@ -557,6 +557,23 @@ pub fn table_bucket_catalog_metadata_prefix(bucket: &str) -> String {
|
||||
/// Internal physical names are reserved even if their identity record is missing.
|
||||
pub const BUCKET_VECTOR_STORAGE_PREFIX: &str = "rustfs-v-";
|
||||
|
||||
/// Server-owned pagination sessions in physical Vector buckets carry no dataset quota charge.
|
||||
pub fn is_vector_pagination_session(bucket: &str, object: &str) -> bool {
|
||||
if !bucket.starts_with(BUCKET_VECTOR_STORAGE_PREFIX) {
|
||||
return false;
|
||||
}
|
||||
let Some(path) = object.strip_prefix(".rustfs-table/") else {
|
||||
return false;
|
||||
};
|
||||
let Some((table, file)) = path.split_once("/query-results/") else {
|
||||
return false;
|
||||
};
|
||||
Uuid::parse_str(table).is_ok_and(|id| !id.is_nil())
|
||||
&& file
|
||||
.strip_suffix(".session")
|
||||
.is_some_and(|id| id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct BucketIdentityConfigError(&'static str);
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ use crate::storage_api_contracts::heal::HealOperations as _;
|
||||
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
|
||||
use crate::store::{ECStore, await_bucket_namespace_operation};
|
||||
use futures::future::join_all;
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
use rustfs_gateway_types::cors_tagging::{PersistedCorsConfiguration as CORSConfiguration, PersistedTagging as Tagging};
|
||||
use rustfs_gateway_types::persistence::{
|
||||
PersistedAccelerateConfiguration as AccelerateConfiguration,
|
||||
@@ -51,7 +52,7 @@ use std::{
|
||||
};
|
||||
use time::OffsetDateTime;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use tokio::time::sleep;
|
||||
use tokio::time::{Instant, sleep};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::{error, warn};
|
||||
use uuid::Uuid;
|
||||
@@ -629,7 +630,7 @@ pub(crate) async fn get_bucket_incarnation_id_for_options_in(
|
||||
let guard =
|
||||
acquire_bucket_metadata_transaction_read_lock_for_options_in(ctx, bucket, opts, "bucket_incarnation_options_read")
|
||||
.await?;
|
||||
sys.get_bucket_incarnation_id_under_transaction_lock(bucket, &guard).await
|
||||
sys.get_bucket_incarnation_id_for_options_under_guard(bucket, &guard).await
|
||||
}
|
||||
|
||||
pub(crate) async fn get_cached_bucket_incarnation_id_in(
|
||||
@@ -2496,6 +2497,7 @@ pub(crate) fn current_local_meta_mutation_gen() -> u64 {
|
||||
}
|
||||
|
||||
type LocalAuthorityCache = Arc<StdMutex<HashMap<String, (u64, Arc<BucketMetadata>)>>>;
|
||||
type LocalIncarnationCache = Arc<StdMutex<HashMap<String, (u64, Uuid)>>>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct PendingBucketCreationProof {
|
||||
@@ -2519,6 +2521,7 @@ pub struct BucketMetadataSys {
|
||||
metadata_map: Arc<RwLock<HashMap<String, Arc<BucketMetadata>>>>,
|
||||
pending_bucket_creations: Arc<RwLock<HashMap<String, PendingBucketCreationProof>>>,
|
||||
local_authority_cache: LocalAuthorityCache,
|
||||
local_incarnation_cache: LocalIncarnationCache,
|
||||
/// Serializes metadata-map commits and their derived cache updates for one
|
||||
/// bucket. Namespace locks, when present, are acquired before this lock.
|
||||
metadata_publish_locks: Arc<MetadataPublishLockRegistry>,
|
||||
@@ -2578,6 +2581,7 @@ impl BucketMetadataSys {
|
||||
metadata_map: Arc::new(RwLock::new(HashMap::new())),
|
||||
pending_bucket_creations: Arc::new(RwLock::new(HashMap::new())),
|
||||
local_authority_cache: Arc::new(StdMutex::new(HashMap::new())),
|
||||
local_incarnation_cache: Arc::new(StdMutex::new(HashMap::new())),
|
||||
metadata_publish_locks: Arc::new(MetadataPublishLockRegistry {
|
||||
locks: StdMutex::new(HashMap::new()),
|
||||
}),
|
||||
@@ -3670,19 +3674,75 @@ impl BucketMetadataSys {
|
||||
Self::require_bucket_incarnation_id(bucket, incarnation_id)
|
||||
}
|
||||
|
||||
async fn get_bucket_incarnation_id_for_options_under_guard(
|
||||
&self,
|
||||
bucket: &str,
|
||||
transaction_guard: &rustfs_lock::NamespaceLockGuard,
|
||||
) -> Result<Uuid> {
|
||||
let store = self.object_store();
|
||||
let can_use_local_cache = !store.ctx.lock_manager().is_disabled() && store.all_disks_local_and_online();
|
||||
let gen_before = current_local_meta_mutation_gen();
|
||||
if can_use_local_cache {
|
||||
// Drop each cache mutex guard before acquiring the other so the two
|
||||
// cache locks are never nested.
|
||||
let from_incarnation_cache = self
|
||||
.local_incarnation_cache
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(bucket)
|
||||
.filter(|(cached_gen, _)| *cached_gen == gen_before)
|
||||
.map(|(_, id)| *id);
|
||||
let cached_id = from_incarnation_cache.or_else(|| {
|
||||
self.local_authority_cache
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(bucket)
|
||||
.filter(|(cached_gen, bm)| {
|
||||
*cached_gen == gen_before && bm.bucket_incarnation_sidecar && !bm.bucket_incarnation_id.is_nil()
|
||||
})
|
||||
.map(|(_, bm)| bm.bucket_incarnation_id)
|
||||
});
|
||||
if let Some(incarnation_id) = cached_id {
|
||||
Self::ensure_transaction_lock_held(bucket, transaction_guard)?;
|
||||
if current_local_meta_mutation_gen() == gen_before && store.all_disks_local_and_online() {
|
||||
return Ok(incarnation_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let incarnation_id = self
|
||||
.get_bucket_incarnation_id_under_transaction_lock(bucket, transaction_guard)
|
||||
.await?;
|
||||
if can_use_local_cache
|
||||
&& !incarnation_id.is_nil()
|
||||
&& current_local_meta_mutation_gen() == gen_before
|
||||
&& store.all_disks_local_and_online()
|
||||
{
|
||||
self.local_incarnation_cache
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.insert(bucket.to_string(), (gen_before, incarnation_id));
|
||||
}
|
||||
Ok(incarnation_id)
|
||||
}
|
||||
|
||||
fn require_bucket_incarnation_id(bucket: &str, incarnation_id: Option<Uuid>) -> Result<Uuid> {
|
||||
incarnation_id.ok_or_else(|| Error::other(format!("bucket incarnation metadata is not authoritative: {bucket}")))
|
||||
}
|
||||
|
||||
fn ensure_transaction_lock_held(bucket: &str, transaction_guard: &rustfs_lock::NamespaceLockGuard) -> Result<()> {
|
||||
if transaction_guard.is_lock_lost() {
|
||||
return Err(Error::other(format!("bucket incarnation metadata transaction lock was lost: {bucket}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn find_bucket_incarnation_id_under_transaction_lock(
|
||||
&self,
|
||||
bucket: &str,
|
||||
transaction_guard: &rustfs_lock::NamespaceLockGuard,
|
||||
) -> Result<Option<Uuid>> {
|
||||
let incarnation_id = load_bucket_incarnation(self.object_store(), bucket).await?;
|
||||
if transaction_guard.is_lock_lost() {
|
||||
return Err(Error::other(format!("bucket incarnation metadata transaction lock was lost: {bucket}")));
|
||||
}
|
||||
Self::ensure_transaction_lock_held(bucket, transaction_guard)?;
|
||||
Ok(incarnation_id)
|
||||
}
|
||||
|
||||
@@ -4173,6 +4233,70 @@ impl BucketMetadataSys {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read configured quota limits for observability, in input order.
|
||||
///
|
||||
/// An unavailable or unset limit is reported as zero. Cache misses use the
|
||||
/// regular metadata lookup, including its namespace and publication fences.
|
||||
/// Returns `None` after the observation's deadline. Already admitted reads
|
||||
/// finish their metadata publication before the result is discarded.
|
||||
pub async fn quota_limits_for_metrics<'a>(
|
||||
&self,
|
||||
mut buckets: impl ExactSizeIterator<Item = &'a str> + Send,
|
||||
deadline: Option<Instant>,
|
||||
) -> Option<Vec<u64>> {
|
||||
const CACHE_BATCH_SIZE: usize = 256;
|
||||
const MAX_COLD_READS: usize = 4;
|
||||
|
||||
let expired = || deadline.is_some_and(|deadline| Instant::now() >= deadline);
|
||||
if expired() {
|
||||
return None;
|
||||
}
|
||||
let mut limits = Vec::with_capacity(buckets.len());
|
||||
let mut missing = Vec::new();
|
||||
while buckets.len() != 0 {
|
||||
// Read only the quota field under the map lock. Release it between
|
||||
// batches and before acquiring any lazy-load or namespace locks.
|
||||
let cached = self.metadata_map.read().await;
|
||||
if expired() {
|
||||
return None;
|
||||
}
|
||||
for bucket in buckets.by_ref().take(CACHE_BATCH_SIZE) {
|
||||
let limit = match cached.get(bucket) {
|
||||
Some(metadata) => metadata
|
||||
.quota_config
|
||||
.as_ref()
|
||||
.and_then(BucketQuota::get_quota_limit)
|
||||
.unwrap_or(0),
|
||||
None => {
|
||||
missing.push((limits.len(), bucket));
|
||||
0
|
||||
}
|
||||
};
|
||||
limits.push(limit);
|
||||
}
|
||||
}
|
||||
|
||||
let mut missing = missing.into_iter();
|
||||
let mut reads = FuturesUnordered::new();
|
||||
loop {
|
||||
for (index, bucket) in missing.by_ref().take_while(|_| !expired()).take(MAX_COLD_READS - reads.len()) {
|
||||
reads.push(async move {
|
||||
let limit = self
|
||||
.get_quota_config(bucket)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|(quota, _)| quota.get_quota_limit());
|
||||
(index, limit.unwrap_or(0))
|
||||
});
|
||||
}
|
||||
let Some((index, limit)) = reads.next().await else {
|
||||
break;
|
||||
};
|
||||
limits[index] = limit;
|
||||
}
|
||||
(!expired()).then_some(limits)
|
||||
}
|
||||
|
||||
async fn cached_quota_config_and_incarnation(&self, bucket: &str) -> Result<Option<CachedQuotaMetadataSnapshot>> {
|
||||
let metadata = {
|
||||
let metadata_map = self.metadata_map.read().await;
|
||||
@@ -6556,6 +6680,92 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn metrics_quota_batch_reads_cache_and_falls_back_to_persisted_limits() {
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let (_dirs, store) = isolated_store_over_temp_disks().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let cold = "metrics-quota-cold";
|
||||
store
|
||||
.make_bucket(cold, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create cold quota fixture");
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(cold)
|
||||
.await
|
||||
.expect("read cold bucket incarnation");
|
||||
store
|
||||
.update_bucket_metadata_config_for_incarnation_validated(
|
||||
cold,
|
||||
"quota.json",
|
||||
br#"{"quota":4096}"#.to_vec(),
|
||||
incarnation,
|
||||
|| Ok(()),
|
||||
)
|
||||
.await
|
||||
.expect("persist cold quota fixture");
|
||||
|
||||
let sys = BucketMetadataSys::new(store.clone());
|
||||
let warm = "metrics-quota-warm";
|
||||
let mut cached = BucketMetadata::new(warm);
|
||||
cached.quota_config = Some(BucketQuota::new(Some(2048)));
|
||||
let invalid = "metrics-quota-invalid";
|
||||
let mut malformed = BucketMetadata::new(invalid);
|
||||
malformed.quota_config_json = b"{not-json".to_vec();
|
||||
sys.metadata_map.write().await.extend([
|
||||
(warm.to_string(), Arc::new(cached)),
|
||||
(invalid.to_string(), Arc::new(malformed)),
|
||||
]);
|
||||
|
||||
let buckets = [cold, warm, invalid, warm];
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
|
||||
Some(vec![4096, 2048, 0, 2048])
|
||||
);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
|
||||
Some(vec![4096, 2048, 0, 2048])
|
||||
);
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(std::iter::repeat_n(warm, 257), None).await,
|
||||
Some(vec![2048; 257]),
|
||||
);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn expired_metrics_quota_batch_drains_admitted_reads_without_starting_more() {
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let (_dirs, store) = isolated_store_over_temp_disks().await;
|
||||
let sys = BucketMetadataSys::new(store.clone());
|
||||
let names = ["expired-q1", "expired-q2", "expired-q3", "expired-q4", "expired-q5"];
|
||||
let mut guards = Vec::new();
|
||||
for name in &names[..4] {
|
||||
guards.push(sys.lazy_load_lock(name).lock_owned().await);
|
||||
}
|
||||
|
||||
tokio::time::pause();
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
let mut batch = std::pin::pin!(sys.quota_limits_for_metrics(names.into_iter(), Some(deadline)));
|
||||
assert!(futures::poll!(&mut batch).is_pending());
|
||||
tokio::time::advance(Duration::from_secs(2)).await;
|
||||
// The deadline alone cannot cancel a read holding or awaiting a metadata lock.
|
||||
assert!(futures::poll!(&mut batch).is_pending());
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 0);
|
||||
drop(guards);
|
||||
tokio::time::resume();
|
||||
|
||||
assert_eq!(batch.await, None);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
|
||||
assert_eq!(sys.quota_limits_for_metrics([names[4]].into_iter(), Some(deadline)).await, None,);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn validated_config_update_rejects_a_different_bucket_incarnation() {
|
||||
@@ -7707,12 +7917,42 @@ mod tests {
|
||||
let guard = acquire_bucket_metadata_transaction_read_lock_in(&ecstore.ctx, bucket)
|
||||
.await
|
||||
.expect("transaction read lock");
|
||||
let _ = sys
|
||||
let warm_bm = match sys
|
||||
.read_authoritative_metadata_from_disk_under_guard(bucket, &guard)
|
||||
.await
|
||||
.expect("warm cached read");
|
||||
.expect("warm cached read")
|
||||
{
|
||||
BucketMetadataAuthority::Authoritative(bm) => bm,
|
||||
_ => panic!("expected Authoritative metadata"),
|
||||
};
|
||||
assert_eq!(sys.authority_disk_loads.load(Ordering::Relaxed), 1);
|
||||
|
||||
// Incarnation lookup under transaction guard reuses local_authority_cache,
|
||||
// and populates local_incarnation_cache when local_authority_cache is cleared.
|
||||
let cached_incarnation = sys
|
||||
.get_bucket_incarnation_id_for_options_under_guard(bucket, &guard)
|
||||
.await
|
||||
.expect("incarnation from local_authority_cache");
|
||||
assert_eq!(cached_incarnation, warm_bm.bucket_incarnation_id);
|
||||
sys.local_authority_cache
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clear();
|
||||
let populated_incarnation = sys
|
||||
.get_bucket_incarnation_id_for_options_under_guard(bucket, &guard)
|
||||
.await
|
||||
.expect("cold incarnation read populates local_incarnation_cache");
|
||||
assert_eq!(populated_incarnation, warm_bm.bucket_incarnation_id);
|
||||
assert_eq!(
|
||||
sys.local_incarnation_cache
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(bucket)
|
||||
.copied(),
|
||||
Some((current_local_meta_mutation_gen(), warm_bm.bucket_incarnation_id))
|
||||
);
|
||||
drop(guard);
|
||||
|
||||
// Negative controls: authority paths and suffix-bearing bucket names MUST bump LOCAL_META_MUTATION_GEN.
|
||||
for authority_path in [
|
||||
format!("buckets/{bucket}/.metadata.bin"),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -32,14 +32,16 @@ use super::replication_storage_boundary::{
|
||||
pub struct ReplicationObjectBridge;
|
||||
|
||||
impl ReplicationObjectBridge {
|
||||
/// Builds a decision snapshot using the replication-request flag from the
|
||||
/// caller's authorized storage options.
|
||||
pub fn must_replicate_options(
|
||||
user_defined: &HashMap<String, String>,
|
||||
user_tags: String,
|
||||
status: ReplicationStatusType,
|
||||
op_type: ReplicationType,
|
||||
opts: ObjectOptions,
|
||||
replication_request: bool,
|
||||
) -> MustReplicateOptions {
|
||||
get_must_replicate_options(user_defined, user_tags, status, op_type, opts)
|
||||
get_must_replicate_options(user_defined, user_tags, status, op_type, replication_request)
|
||||
}
|
||||
|
||||
pub async fn must_replicate(bucket: &str, object: &str, options: MustReplicateOptions) -> ReplicateDecision {
|
||||
@@ -204,7 +206,7 @@ mod tests {
|
||||
String::new(),
|
||||
ReplicationStatusType::Empty,
|
||||
ReplicationType::Metadata,
|
||||
ObjectOptions::default(),
|
||||
false,
|
||||
);
|
||||
assert!(metadata.is_metadata_replication());
|
||||
assert!(!metadata.is_existing_object_replication());
|
||||
@@ -214,7 +216,7 @@ mod tests {
|
||||
String::new(),
|
||||
ReplicationStatusType::Empty,
|
||||
ReplicationType::ExistingObject,
|
||||
ObjectOptions::default(),
|
||||
false,
|
||||
);
|
||||
assert!(existing.is_existing_object_replication());
|
||||
assert!(!existing.is_metadata_replication());
|
||||
|
||||
@@ -396,9 +396,9 @@ pub(crate) fn get_must_replicate_options(
|
||||
user_tags: String,
|
||||
status: ReplicationStatusType,
|
||||
op_type: ReplicationType,
|
||||
opts: ObjectOptions,
|
||||
replication_request: bool,
|
||||
) -> MustReplicateOptions {
|
||||
MustReplicateOptions::new(user_defined, user_tags, op_type, opts.replication_request).with_replication_status(status)
|
||||
MustReplicateOptions::new(user_defined, user_tags, op_type, replication_request).with_replication_status(status)
|
||||
}
|
||||
|
||||
pub(crate) async fn check_replicate_delete(
|
||||
@@ -716,10 +716,7 @@ mod tests {
|
||||
"env=prod".to_string(),
|
||||
ReplicationStatusType::Empty,
|
||||
ReplicationType::Metadata,
|
||||
ObjectOptions {
|
||||
replication_request: true,
|
||||
..Default::default()
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
assert!(options.is_metadata_replication());
|
||||
|
||||
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
|
||||
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
|
||||
};
|
||||
use super::replication_resyncer::{
|
||||
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
|
||||
replicate_object_with_outcome, update_resync_status_cas,
|
||||
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
|
||||
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
|
||||
};
|
||||
use super::replication_state::ReplicationStats;
|
||||
use super::replication_storage_boundary::{
|
||||
@@ -1329,12 +1329,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let storage = self.storage.clone();
|
||||
let stats = self.stats.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut rx = rx;
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1389,12 +1391,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let stats = self.stats.clone();
|
||||
let storage = self.storage.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut rx = rx;
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1434,6 +1438,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let stats = self.stats.clone();
|
||||
let storage = self.storage.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
@@ -1453,7 +1458,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let Some(operation) = operation else { break };
|
||||
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
self.task_handles.lock().await.push(handle);
|
||||
@@ -1935,7 +1941,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
|
||||
process_replication_operation(
|
||||
operation,
|
||||
stats.clone(),
|
||||
self.storage.clone(),
|
||||
self.in_flight.clone(),
|
||||
&self.mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1953,7 +1966,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1970,7 +1984,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
|
||||
process_replication_operation(
|
||||
operation,
|
||||
stats.clone(),
|
||||
self.storage.clone(),
|
||||
self.in_flight.clone(),
|
||||
&self.mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2539,6 +2560,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
|
||||
stats: Arc<ReplicationStats>,
|
||||
storage: Arc<S>,
|
||||
in_flight: Arc<ReplicationInFlight>,
|
||||
mrf_save_tx: &Sender<MrfReplicateEntry>,
|
||||
) {
|
||||
match operation {
|
||||
ReplicationOperation::Object(obj_info) => {
|
||||
@@ -2548,7 +2570,14 @@ async fn process_replication_operation<S: ReplicationStorage>(
|
||||
}
|
||||
ReplicationOperation::Delete(del_info) => {
|
||||
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
|
||||
replicate_delete(*del_info, storage).await;
|
||||
// The delete request already succeeded, so a source lock that is
|
||||
// still held (a bulk delete keeps its key locks until the whole
|
||||
// batch commits) must not cost the replication: journal it for
|
||||
// the next MRF replay.
|
||||
let retry_entry = del_info.to_mrf_entry();
|
||||
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
|
||||
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4506,6 +4535,102 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
|
||||
async fn delete_worker_journal(
|
||||
delete: DeletedObjectReplicationInfo,
|
||||
writeback_error: EcstoreError,
|
||||
) -> Vec<MrfReplicateEntry> {
|
||||
let shared = empty_resync_shared_state();
|
||||
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
|
||||
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
|
||||
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
|
||||
|
||||
process_replication_operation(
|
||||
ReplicationOperation::Delete(Box::new(delete)),
|
||||
Arc::new(ReplicationStats::new()),
|
||||
storage,
|
||||
Arc::new(ReplicationInFlight::default()),
|
||||
&mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
|
||||
drop(mrf_save_tx);
|
||||
let mut journaled = Vec::new();
|
||||
while let Some(entry) = mrf_save_rx.recv().await {
|
||||
journaled.push(entry);
|
||||
}
|
||||
journaled
|
||||
}
|
||||
|
||||
fn purged_on_target_delete(
|
||||
arn: &str,
|
||||
version_id: Uuid,
|
||||
target_status: VersionPurgeStatusType,
|
||||
) -> DeletedObjectReplicationInfo {
|
||||
DeletedObjectReplicationInfo {
|
||||
bucket: "source".to_string(),
|
||||
delete_object: ReplicationDeletedObject {
|
||||
object_name: "purged".to_string(),
|
||||
version_id: Some(version_id),
|
||||
replication_state: Some(ReplicationState {
|
||||
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
|
||||
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
op_type: ReplicationType::Delete,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
|
||||
let arn = "arn:test";
|
||||
let version_id = Uuid::new_v4();
|
||||
// A bulk delete of the same key still holds the object lock.
|
||||
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
|
||||
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
|
||||
));
|
||||
|
||||
let journaled =
|
||||
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
|
||||
|
||||
assert_eq!(
|
||||
journaled.len(),
|
||||
1,
|
||||
"a delete whose result never reached the source must be kept for replay"
|
||||
);
|
||||
let entry = &journaled[0];
|
||||
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
|
||||
assert_eq!(entry.version_id, Some(version_id));
|
||||
assert_eq!(entry.op, MrfOpKind::Delete);
|
||||
assert_eq!(entry.target_arns, vec![arn.to_string()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
|
||||
let arn = "arn:test";
|
||||
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
|
||||
|
||||
let completed = delete_worker_journal(
|
||||
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
|
||||
source_gone(),
|
||||
)
|
||||
.await;
|
||||
assert!(completed.is_empty(), "a completed delete must not be replayed");
|
||||
|
||||
let target_pending = delete_worker_journal(
|
||||
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
|
||||
source_gone(),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
target_pending.is_empty(),
|
||||
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_preserves_persisted_admission_without_live_config() {
|
||||
let arn = "arn:test";
|
||||
|
||||
@@ -2422,12 +2422,40 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
|
||||
let _ = replicate_delete_with_outcome(dobj, storage).await;
|
||||
}
|
||||
|
||||
/// How one delete replication attempt ended.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum DeleteReplicationAttempt {
|
||||
/// Every admitted target finished and the source state was persisted.
|
||||
Completed,
|
||||
/// The attempt did not finish for a reason another path already owns: a
|
||||
/// target failure is recorded in the persisted state for the scanner, and
|
||||
/// a force delete or delete-marker purge journals its own intent.
|
||||
Unfinished,
|
||||
/// A source-side lock or read kept the attempt from running, or from
|
||||
/// persisting its result. Nothing durable records that, so the caller must
|
||||
/// keep the delete for a later attempt.
|
||||
SourceDeferred,
|
||||
}
|
||||
|
||||
impl DeleteReplicationAttempt {
|
||||
fn from_finished(finished: bool) -> Self {
|
||||
if finished { Self::Completed } else { Self::Unfinished }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
dobj: DeletedObjectReplicationInfo,
|
||||
storage: Arc<S>,
|
||||
) -> bool {
|
||||
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
|
||||
}
|
||||
|
||||
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
dobj: DeletedObjectReplicationInfo,
|
||||
storage: Arc<S>,
|
||||
) -> DeleteReplicationAttempt {
|
||||
if dobj.delete_object.force_delete {
|
||||
return replicate_force_delete_to_targets(&dobj, storage).await;
|
||||
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
|
||||
}
|
||||
|
||||
let bucket = dobj.bucket.clone();
|
||||
@@ -2472,7 +2500,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return false;
|
||||
return DeleteReplicationAttempt::Unfinished;
|
||||
}
|
||||
};
|
||||
let target_arns = dobj.admitted_target_arns();
|
||||
@@ -2480,7 +2508,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
// Batch expiry can return an empty state after removing the source.
|
||||
// It owes no remote work or local writeback. Persisted target admission
|
||||
// must still be honored even when the live configuration is gone.
|
||||
return true;
|
||||
return DeleteReplicationAttempt::Completed;
|
||||
}
|
||||
|
||||
if dobj.delete_object.delete_marker
|
||||
@@ -2502,7 +2530,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
reason = "source_not_delete_marker",
|
||||
"Skipping stale delete-marker replication"
|
||||
);
|
||||
return true;
|
||||
return DeleteReplicationAttempt::Completed;
|
||||
}
|
||||
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
|
||||
debug!(
|
||||
@@ -2520,7 +2548,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
// purge-intent replay landing here on purpose). Purge instead
|
||||
// of just skipping; the result decides whether an MRF replay
|
||||
// may acknowledge the entry.
|
||||
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
|
||||
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
|
||||
}
|
||||
Err(err) => {
|
||||
// A transient source error (lock timeout, IO error) must not
|
||||
@@ -2529,7 +2557,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
// target mint one more delete marker (rustfs#6823). Fail the
|
||||
// entry without touching the target; the MRF replay / heal
|
||||
// scanner retries once the source is readable again.
|
||||
debug!(
|
||||
warn!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2554,7 +2582,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return false;
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2565,7 +2593,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
{
|
||||
Ok(ns_lock) => ns_lock,
|
||||
Err(e) => {
|
||||
debug!(
|
||||
warn!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2589,14 +2617,14 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return false;
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
};
|
||||
|
||||
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
|
||||
Ok(lock_guard) => lock_guard,
|
||||
Err(e) => {
|
||||
debug!(
|
||||
warn!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2620,7 +2648,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return false;
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2858,7 +2886,12 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
}
|
||||
};
|
||||
|
||||
replicate_delete_outcome(
|
||||
if !state_persisted {
|
||||
// The targets were driven, but the result never reached the source
|
||||
// metadata, so a scanner pass would still see the pre-attempt state.
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
|
||||
expected_targets,
|
||||
rinfos.targets.len(),
|
||||
state_persisted,
|
||||
@@ -2866,7 +2899,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
// error returns early above instead of replicating unverified.
|
||||
true,
|
||||
&replication_status,
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
/// Reads the source version addressed by `delete_marker_version_id` so a
|
||||
|
||||
@@ -1007,6 +1007,65 @@ fn prepare_msgpack_send_policy_with_gates(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn peer_authenticated_boot_epoch_for_addr(addr: &str) -> Option<Uuid> {
|
||||
let uri = addr.parse::<Uri>().ok()?;
|
||||
let audience = uri
|
||||
.authority()
|
||||
.and_then(|authority| normalize_tonic_rpc_audience(authority.as_str()).ok())?;
|
||||
PEER_REPLAY_STATES
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|states| states.replay.get(&audience).and_then(|state| state.boot_epoch))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn set_peer_authenticated_boot_epoch_for_addr_for_test(addr: &str, boot_epoch: Option<Uuid>) {
|
||||
let Ok(uri) = addr.parse::<Uri>() else {
|
||||
return;
|
||||
};
|
||||
let Some(Ok(audience)) = uri
|
||||
.authority()
|
||||
.map(|authority| normalize_tonic_rpc_audience(authority.as_str()))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let previous = if let Ok(mut states) = PEER_REPLAY_STATES.lock() {
|
||||
let entry = states.replay.entry(audience.clone()).or_default();
|
||||
let prev = entry.boot_epoch;
|
||||
entry.boot_epoch = boot_epoch;
|
||||
prev
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let (Some(old_epoch), Some(new_epoch)) = (previous, boot_epoch)
|
||||
&& old_epoch != new_epoch
|
||||
{
|
||||
super::internode_data_transport::on_authenticated_peer_boot_epoch_changed(&audience, old_epoch, new_epoch);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ForceBootEpochProbe;
|
||||
|
||||
/// Actively probe a peer's cryptographically authenticated boot epoch via a signed v2 gRPC `Ping`
|
||||
/// with a fresh challenge nonce (bypassing any stale v3 replay-scope epoch so a restarted peer can
|
||||
/// answer the challenge and prove its new boot epoch).
|
||||
pub(crate) async fn probe_authenticated_peer_boot_epoch_for_addr(addr: &str, timeout: Duration) -> Option<Uuid> {
|
||||
let probe = async {
|
||||
let mut client = node_service_time_out_client(addr, TonicInterceptor::Signature(gen_tonic_signature_interceptor()))
|
||||
.await
|
||||
.ok()?;
|
||||
let mut request = tonic::Request::new(rustfs_protos::proto_gen::node_service::PingRequest {
|
||||
version: 1,
|
||||
body: bytes::Bytes::new(),
|
||||
});
|
||||
request.extensions_mut().insert(ForceBootEpochProbe);
|
||||
let _ = client.ping(request).await;
|
||||
peer_authenticated_boot_epoch_for_addr(addr)
|
||||
};
|
||||
tokio::time::timeout(timeout, probe).await.ok().flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn clear_peer_replay_state_for_addr(addr: &str) -> std::io::Result<()> {
|
||||
let uri = addr
|
||||
.parse::<Uri>()
|
||||
@@ -1048,6 +1107,7 @@ fn apply_peer_capabilities_response(
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn apply_peer_capabilities_response_for_connection(
|
||||
audience: String,
|
||||
sent_state: PeerReplayStateSnapshot,
|
||||
@@ -1055,17 +1115,36 @@ fn apply_peer_capabilities_response_for_connection(
|
||||
msgpack_response: Option<std::io::Result<AuthenticatedPeerMsgpackCapabilities>>,
|
||||
current_connection: Option<GrpcConnectionSnapshot>,
|
||||
) {
|
||||
apply_peer_capabilities_response_for_connection_inner(
|
||||
audience,
|
||||
sent_state,
|
||||
replay_response,
|
||||
msgpack_response,
|
||||
current_connection,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
fn apply_peer_capabilities_response_for_connection_inner(
|
||||
audience: String,
|
||||
sent_state: PeerReplayStateSnapshot,
|
||||
replay_response: std::io::Result<AuthenticatedPeerReplayCapabilities>,
|
||||
msgpack_response: Option<std::io::Result<AuthenticatedPeerMsgpackCapabilities>>,
|
||||
current_connection: Option<GrpcConnectionSnapshot>,
|
||||
force_boot_epoch_update: bool,
|
||||
) {
|
||||
let mut changed_boot_epoch: Option<(Uuid, Uuid)> = None;
|
||||
if let Ok(mut states) = PEER_REPLAY_STATES.lock() {
|
||||
let current_snapshot = states.snapshot(&audience, sent_state.connection);
|
||||
let current_state = current_snapshot.replay;
|
||||
let mut next_state = current_state;
|
||||
if let Ok(response) = &replay_response
|
||||
&& sent_state.replay.boot_epoch == current_state.boot_epoch
|
||||
&& (force_boot_epoch_update || sent_state.replay.boot_epoch == current_state.boot_epoch)
|
||||
{
|
||||
next_state.boot_epoch = Some(response.boot_epoch);
|
||||
}
|
||||
|
||||
if sent_state.replay.boot_epoch == current_state.boot_epoch {
|
||||
if force_boot_epoch_update || sent_state.replay.boot_epoch == current_state.boot_epoch {
|
||||
let response_capability = replay_response
|
||||
.as_ref()
|
||||
.ok()
|
||||
@@ -1106,6 +1185,9 @@ fn apply_peer_capabilities_response_for_connection(
|
||||
if current_state.boot_epoch != next_state.boot_epoch {
|
||||
states.msgpack_by_channel.remove(&audience);
|
||||
states.rename_batch_rejections.remove(&audience);
|
||||
if let (Some(old_epoch), Some(new_epoch)) = (current_state.boot_epoch, next_state.boot_epoch) {
|
||||
changed_boot_epoch = Some((old_epoch, new_epoch));
|
||||
}
|
||||
}
|
||||
if next_state.cache_capability == Some(PeerReplayCapability::Revoked) {
|
||||
states.rename_batch_rejections.remove(&audience);
|
||||
@@ -1133,7 +1215,10 @@ fn apply_peer_capabilities_response_for_connection(
|
||||
}
|
||||
}
|
||||
}
|
||||
states.replay.insert(audience, next_state);
|
||||
states.replay.insert(audience.clone(), next_state);
|
||||
}
|
||||
if let Some((old_epoch, new_epoch)) = changed_boot_epoch {
|
||||
super::internode_data_transport::on_authenticated_peer_boot_epoch_changed(&audience, old_epoch, new_epoch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1179,6 +1264,7 @@ where
|
||||
== Some(RPC_AUTH_VERSION_V2)
|
||||
});
|
||||
let challenge = authenticated.then(Uuid::new_v4);
|
||||
let force_boot_epoch_probe = request.extensions().get::<ForceBootEpochProbe>().is_some();
|
||||
let sent_state = request
|
||||
.extensions()
|
||||
.get::<PeerReplayStateSnapshot>()
|
||||
@@ -1210,14 +1296,16 @@ where
|
||||
.expect("static msgpack capability must be a valid header value"),
|
||||
);
|
||||
}
|
||||
if let (Some(boot_epoch), Some(timestamp), Some(content_sha256)) = (
|
||||
sent_state.replay.boot_epoch,
|
||||
request.headers().get(TIMESTAMP_HEADER).and_then(|value| value.to_str().ok()),
|
||||
request
|
||||
.headers()
|
||||
.get(RPC_CONTENT_SHA256_HEADER)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
) {
|
||||
if !force_boot_epoch_probe
|
||||
&& let (Some(boot_epoch), Some(timestamp), Some(content_sha256)) = (
|
||||
sent_state.replay.boot_epoch,
|
||||
request.headers().get(TIMESTAMP_HEADER).and_then(|value| value.to_str().ok()),
|
||||
request
|
||||
.headers()
|
||||
.get(RPC_CONTENT_SHA256_HEADER)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
)
|
||||
{
|
||||
match rpc_background_admission(request.headers()).and_then(|background| {
|
||||
gen_tonic_replay_scope_headers_with_admission(
|
||||
audience,
|
||||
@@ -1305,12 +1393,13 @@ where
|
||||
} else {
|
||||
None
|
||||
};
|
||||
apply_peer_capabilities_response_for_connection(
|
||||
apply_peer_capabilities_response_for_connection_inner(
|
||||
audience,
|
||||
sent_state,
|
||||
response_state,
|
||||
msgpack_response,
|
||||
current_connection,
|
||||
force_boot_epoch_probe,
|
||||
);
|
||||
if let Some((audience, connection, boot_epoch)) = rejection {
|
||||
remember_rename_batch_rejection(audience, connection, boot_epoch);
|
||||
|
||||
@@ -15,9 +15,42 @@
|
||||
use http::{HeaderMap, HeaderValue};
|
||||
use opentelemetry::{global, propagation::Injector, trace::TraceContextExt};
|
||||
pub(crate) use rustfs_utils::http::headers::REQUEST_ID_HEADER;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use tracing::Span;
|
||||
use tracing_opentelemetry::OpenTelemetrySpanExt;
|
||||
|
||||
tokio::task_local! {
|
||||
static PROPAGATED_REQUEST_ID: Option<Arc<str>>;
|
||||
}
|
||||
|
||||
pub fn in_propagated_request_id<T>(request_id: Option<&Arc<str>>, operation: impl FnOnce() -> T) -> T {
|
||||
PROPAGATED_REQUEST_ID.sync_scope(request_id.cloned(), operation)
|
||||
}
|
||||
|
||||
pub fn current_propagated_request_id() -> Option<Arc<str>> {
|
||||
PROPAGATED_REQUEST_ID.try_with(Clone::clone).ok().flatten()
|
||||
}
|
||||
|
||||
pub fn with_captured_request_id<F>(future: F) -> impl Future<Output = F::Output>
|
||||
where
|
||||
F: Future,
|
||||
{
|
||||
let captured = current_propagated_request_id();
|
||||
async move {
|
||||
match captured {
|
||||
Some(request_id) => PROPAGATED_REQUEST_ID.scope(Some(request_id), future).await,
|
||||
None => future.await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_request_id_or_fallback(fallback: impl FnOnce() -> String) -> String {
|
||||
current_propagated_request_id()
|
||||
.map(|id| id.to_string())
|
||||
.unwrap_or_else(fallback)
|
||||
}
|
||||
|
||||
struct HttpHeaderInjector<'a> {
|
||||
headers: &'a mut HeaderMap,
|
||||
}
|
||||
@@ -64,9 +97,10 @@ fn fallback_request_id() -> String {
|
||||
format!("req-{}", &uuid::Uuid::new_v4().to_string()[..8])
|
||||
}
|
||||
|
||||
fn propagated_request_id() -> String {
|
||||
current_trace_id()
|
||||
.map(|trace_id| format!("trace-{trace_id}"))
|
||||
pub(crate) fn propagated_request_id() -> String {
|
||||
current_propagated_request_id()
|
||||
.map(|id| id.to_string())
|
||||
.or_else(|| current_trace_id().map(|trace_id| format!("trace-{trace_id}")))
|
||||
.unwrap_or_else(fallback_request_id)
|
||||
}
|
||||
|
||||
@@ -151,6 +185,23 @@ mod tests {
|
||||
assert_eq!(headers.get(REQUEST_ID_HEADER).and_then(|v| v.to_str().ok()), Some("req-upstream-123"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_propagated_request_id_prefers_scoped_s3_request_id_across_spawns() {
|
||||
let s3_req_id: Arc<str> = Arc::from("s3-req-3390-abcd");
|
||||
let (hdr_id, spawned_id) = in_propagated_request_id(Some(&s3_req_id), || {
|
||||
let mut headers = HeaderMap::new();
|
||||
inject_request_id_into_http_headers(&mut headers);
|
||||
let hdr_id = headers
|
||||
.get(REQUEST_ID_HEADER)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(ToOwned::to_owned);
|
||||
let handle = tokio::spawn(with_captured_request_id(async { propagated_request_id() }));
|
||||
(hdr_id, handle)
|
||||
});
|
||||
assert_eq!(hdr_id.as_deref(), Some("s3-req-3390-abcd"));
|
||||
assert_eq!(spawned_id.await.expect("spawned task"), "s3-req-3390-abcd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inject_request_id_into_http_headers_uses_trace_id_when_missing() {
|
||||
let trace_id = "abcdefabcdefabcdefabcdefabcdefab";
|
||||
|
||||
@@ -12,11 +12,13 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use crate::cluster::rpc::client::{peer_authenticated_boot_epoch_for_addr, probe_authenticated_peer_boot_epoch_for_addr};
|
||||
use crate::cluster::rpc::{
|
||||
StreamResponseAuthDomain, build_auth_headers, build_put_file_auth_trailer,
|
||||
verify_ns_scanner_capability_with_checkpoint_coverage, verify_ns_scanner_capability_with_durable_progress,
|
||||
verify_ns_scanner_capability_with_tier_registry_generation, verify_ns_scanner_capability_with_usage_capabilities,
|
||||
verify_put_file_capability, verify_stream_auth_data_frame, verify_stream_auth_eof_frame,
|
||||
StreamResponseAuthDomain, build_auth_headers, build_put_file_auth_trailer, context_propagation::propagated_request_id,
|
||||
normalize_tonic_rpc_audience, verify_ns_scanner_capability_with_checkpoint_coverage,
|
||||
verify_ns_scanner_capability_with_durable_progress, verify_ns_scanner_capability_with_tier_registry_generation,
|
||||
verify_ns_scanner_capability_with_usage_capabilities, verify_put_file_capability, verify_stream_auth_data_frame,
|
||||
verify_stream_auth_eof_frame,
|
||||
};
|
||||
use crate::disk::error::{Error, Result};
|
||||
use crate::disk::{FileReader, FileWriter};
|
||||
@@ -45,7 +47,7 @@ use rustfs_rio::{
|
||||
ChunkReader, ChunkReaderBox, HttpChunkReader, HttpReader, HttpWriter, HttpWriterMemoryReservation, HttpWriterMemoryReserver,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
@@ -54,6 +56,7 @@ use std::task::{Context, Poll};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
|
||||
use tokio::sync::OnceCell;
|
||||
use tracing::{info, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[allow(
|
||||
@@ -73,6 +76,7 @@ const PUT_FILE_MAX_CAPABILITY_RESPONSE_SIZE: usize = 1024;
|
||||
const PUT_FILE_LEGACY_CAPABILITY_TTL: Duration = Duration::from_secs(30);
|
||||
pub(super) const PUT_FILE_V1_CAPABILITY_TTL: Duration = Duration::from_secs(30);
|
||||
const PUT_FILE_CAPABILITY_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const STREAM_AUTH_ROLLBACK_PROBE_TIMEOUT: Duration = Duration::from_millis(1500);
|
||||
const CONTENT_TYPE_JSON: &str = "application/json";
|
||||
const CONTENT_TYPE_MSGPACK: &str = "application/msgpack";
|
||||
|
||||
@@ -99,7 +103,11 @@ fn unsupported_transport_message(transport: &str) -> String {
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum PutFileCapabilityState {
|
||||
LegacyUntil(Instant),
|
||||
V1 { server_epoch: Uuid, revalidate_after: Instant },
|
||||
V1 {
|
||||
server_epoch: Uuid,
|
||||
peer_boot_epoch: Option<Uuid>,
|
||||
revalidate_after: Instant,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -122,6 +130,7 @@ type PutFileCapabilityProbeOutcome = std::result::Result<Option<Uuid>, PutFileCa
|
||||
struct PutFileCapabilityFlight {
|
||||
generation: u64,
|
||||
v1_was_pinned: bool,
|
||||
pinned_boot_epoch: Option<Uuid>,
|
||||
outcome: Arc<OnceCell<PutFileCapabilityProbeOutcome>>,
|
||||
}
|
||||
|
||||
@@ -145,19 +154,119 @@ static STREAM_RESPONSE_AUTH_STRICT: LazyLock<bool> =
|
||||
LazyLock::new(|| rustfs_utils::get_env_bool(ENV_INTERNODE_RPC_STREAM_AUTH_STRICT, DEFAULT_INTERNODE_RPC_STREAM_AUTH_STRICT));
|
||||
|
||||
// Once a peer proves cryptographic support for authenticated framed response streams,
|
||||
// pin it so an on-path attacker cannot strip the header and downgrade subsequent responses.
|
||||
static STREAM_AUTH_PINNED_ENDPOINTS: LazyLock<parking_lot::RwLock<HashSet<String>>> =
|
||||
LazyLock::new(|| parking_lot::RwLock::new(HashSet::new()));
|
||||
// pin it to its HMAC-authenticated gRPC boot_epoch so an on-path attacker cannot strip
|
||||
// the header and downgrade subsequent responses within the same peer incarnation, while
|
||||
// a legitimate rolling rollback (proving possession of the cluster secret with a fresh
|
||||
// boot_epoch) cleanly unpins when strict mode is disabled.
|
||||
static STREAM_AUTH_PINNED_ENDPOINTS: LazyLock<parking_lot::RwLock<HashMap<String, Option<Uuid>>>> =
|
||||
LazyLock::new(|| parking_lot::RwLock::new(HashMap::new()));
|
||||
|
||||
fn normalize_stream_auth_endpoint(endpoint: &str) -> String {
|
||||
endpoint.trim().trim_end_matches('/').to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn endpoint_matches_audience(endpoint: &str, audience: &str) -> bool {
|
||||
endpoint
|
||||
.parse::<http::Uri>()
|
||||
.ok()
|
||||
.and_then(|uri| uri.authority().map(|a| normalize_tonic_rpc_audience(a.as_str())))
|
||||
.and_then(std::result::Result::ok)
|
||||
.is_some_and(|normalized| normalized == audience)
|
||||
}
|
||||
|
||||
pub(crate) fn on_authenticated_peer_boot_epoch_changed(audience: &str, old_epoch: Uuid, new_epoch: Uuid) {
|
||||
if old_epoch == new_epoch || *STREAM_RESPONSE_AUTH_STRICT {
|
||||
return;
|
||||
}
|
||||
let mut removed_endpoints = Vec::new();
|
||||
{
|
||||
let mut pinned = STREAM_AUTH_PINNED_ENDPOINTS.write();
|
||||
pinned.retain(|endpoint, pinned_epoch| {
|
||||
let matches_peer =
|
||||
endpoint_matches_audience(endpoint, audience) && pinned_epoch.is_none_or(|epoch| epoch == old_epoch);
|
||||
if matches_peer {
|
||||
removed_endpoints.push(endpoint.clone());
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
if !removed_endpoints.is_empty() {
|
||||
info!(
|
||||
event = "internode_stream_auth_unpinned_on_peer_restart",
|
||||
audience,
|
||||
old_boot_epoch = %old_epoch,
|
||||
new_boot_epoch = %new_epoch,
|
||||
endpoints = ?removed_endpoints,
|
||||
"Unpinned internode stream auth endpoints after authenticated peer boot_epoch transition"
|
||||
);
|
||||
}
|
||||
|
||||
let matching_entries: Vec<(String, PutFileCapabilityCacheEntry)> = PUT_FILE_CAPABILITY_CACHE
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|(endpoint, _)| endpoint_matches_audience(endpoint, audience))
|
||||
.map(|(endpoint, entry)| (endpoint.clone(), Arc::clone(entry)))
|
||||
.collect();
|
||||
for (endpoint, entry) in matching_entries {
|
||||
let mut state = entry.write();
|
||||
if matches!(
|
||||
state.cached,
|
||||
Some(PutFileCapabilityState::V1 { peer_boot_epoch, .. })
|
||||
if peer_boot_epoch.is_none_or(|epoch| epoch == old_epoch)
|
||||
) {
|
||||
state.cached = None;
|
||||
state.rejected_server_epoch = None;
|
||||
info!(
|
||||
event = "internode_put_file_capability_unpinned_on_peer_restart",
|
||||
endpoint,
|
||||
audience,
|
||||
old_boot_epoch = %old_epoch,
|
||||
new_boot_epoch = %new_epoch,
|
||||
"Cleared put_file v1 capability pin after authenticated peer boot_epoch transition"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pin_stream_auth_endpoint(endpoint: &str) {
|
||||
let key = normalize_stream_auth_endpoint(endpoint);
|
||||
if !key.is_empty() && !STREAM_AUTH_PINNED_ENDPOINTS.read().contains(&key) {
|
||||
STREAM_AUTH_PINNED_ENDPOINTS.write().insert(key);
|
||||
if key.is_empty() {
|
||||
return;
|
||||
}
|
||||
let current_boot_epoch = peer_authenticated_boot_epoch_for_addr(endpoint);
|
||||
let needs_update = {
|
||||
let pinned = STREAM_AUTH_PINNED_ENDPOINTS.read();
|
||||
match pinned.get(&key) {
|
||||
None => true,
|
||||
Some(stored) => current_boot_epoch.is_some() && *stored != current_boot_epoch,
|
||||
}
|
||||
};
|
||||
if needs_update {
|
||||
STREAM_AUTH_PINNED_ENDPOINTS.write().insert(key, current_boot_epoch);
|
||||
}
|
||||
}
|
||||
|
||||
fn try_unpin_if_boot_epoch_advanced(endpoint: &str, key: &str, pinned_epoch: Uuid, live_epoch: Uuid) -> bool {
|
||||
if live_epoch == pinned_epoch {
|
||||
return false;
|
||||
}
|
||||
let mut pinned = STREAM_AUTH_PINNED_ENDPOINTS.write();
|
||||
if pinned.get(key).copied() == Some(Some(pinned_epoch)) {
|
||||
pinned.remove(key);
|
||||
drop(pinned);
|
||||
info!(
|
||||
event = "internode_stream_auth_unpinned_on_peer_restart",
|
||||
request_id = %propagated_request_id(),
|
||||
endpoint,
|
||||
pinned_boot_epoch = %pinned_epoch,
|
||||
live_boot_epoch = %live_epoch,
|
||||
"Unpinned internode stream auth endpoint after verifying peer restart boot_epoch"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn should_authenticate_response_stream(endpoint: &str, response_headers: &HeaderMap, strict: bool) -> Result<bool> {
|
||||
@@ -167,7 +276,17 @@ fn should_authenticate_response_stream(endpoint: &str, response_headers: &Header
|
||||
(Some(_), _) => Err(Error::other("unsupported or duplicate internode stream response auth header")),
|
||||
(None, _) => {
|
||||
let key = normalize_stream_auth_endpoint(endpoint);
|
||||
if strict || STREAM_AUTH_PINNED_ENDPOINTS.read().contains(&key) {
|
||||
if strict {
|
||||
return Err(Error::other("internode stream response auth missing or downgraded"));
|
||||
}
|
||||
let pinned_entry = STREAM_AUTH_PINNED_ENDPOINTS.read().get(&key).copied();
|
||||
if let Some(pinned_epoch_opt) = pinned_entry {
|
||||
if let Some(pinned_epoch) = pinned_epoch_opt
|
||||
&& let Some(live_epoch) = peer_authenticated_boot_epoch_for_addr(endpoint)
|
||||
&& try_unpin_if_boot_epoch_advanced(endpoint, &key, pinned_epoch, live_epoch)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
return Err(Error::other("internode stream response auth missing or downgraded"));
|
||||
}
|
||||
Ok(false)
|
||||
@@ -175,6 +294,40 @@ fn should_authenticate_response_stream(endpoint: &str, response_headers: &Header
|
||||
}
|
||||
}
|
||||
|
||||
async fn should_authenticate_response_stream_async(endpoint: &str, response_headers: &HeaderMap, strict: bool) -> Result<bool> {
|
||||
match should_authenticate_response_stream(endpoint, response_headers, strict) {
|
||||
Ok(auth) => Ok(auth),
|
||||
Err(err) => {
|
||||
if !strict && response_headers.get(STREAM_RESPONSE_AUTH_HEADER).is_none() {
|
||||
let key = normalize_stream_auth_endpoint(endpoint);
|
||||
let pinned_epoch = STREAM_AUTH_PINNED_ENDPOINTS.read().get(&key).copied().flatten();
|
||||
if let Some(pinned_epoch) = pinned_epoch {
|
||||
let live_epoch =
|
||||
probe_authenticated_peer_boot_epoch_for_addr(endpoint, STREAM_AUTH_ROLLBACK_PROBE_TIMEOUT).await;
|
||||
if let Some(live_epoch) = live_epoch
|
||||
&& try_unpin_if_boot_epoch_advanced(endpoint, &key, pinned_epoch, live_epoch)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
// Also handle the case where the probe's ReplayScopeChannel hook already unpinned the entry.
|
||||
if !STREAM_AUTH_PINNED_ENDPOINTS.read().contains_key(&key) {
|
||||
return Ok(false);
|
||||
}
|
||||
warn!(
|
||||
event = "internode_stream_auth_downgrade_rejected",
|
||||
request_id = %propagated_request_id(),
|
||||
endpoint,
|
||||
pinned_boot_epoch = %pinned_epoch,
|
||||
live_boot_epoch = ?live_epoch,
|
||||
"Rejected missing internode stream response auth header on same or unverified peer boot_epoch"
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AuthenticatedStreamReader<R> {
|
||||
inner: R,
|
||||
endpoint: String,
|
||||
@@ -422,6 +575,7 @@ fn fresh_put_file_capability(state: Option<PutFileCapabilityState>, now: Instant
|
||||
Some(PutFileCapabilityState::V1 {
|
||||
server_epoch,
|
||||
revalidate_after,
|
||||
..
|
||||
}) if now < revalidate_after => Some(Some(server_epoch)),
|
||||
Some(PutFileCapabilityState::LegacyUntil(expires_at)) if now < expires_at => Some(None),
|
||||
Some(PutFileCapabilityState::V1 { .. }) | Some(PutFileCapabilityState::LegacyUntil(_)) | None => None,
|
||||
@@ -625,7 +779,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
let mut headers = json_headers();
|
||||
build_auth_headers(&url, &Method::GET, &mut headers)?;
|
||||
let reader = HttpReader::new_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout).await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -647,7 +803,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
let reader =
|
||||
HttpReader::new_fresh_connection_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout)
|
||||
.await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -668,7 +826,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
build_auth_headers(&url, &Method::GET, &mut headers)?;
|
||||
let reader =
|
||||
HttpChunkReader::new_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout).await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Some(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -695,7 +855,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
request.stall_timeout,
|
||||
)
|
||||
.await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Some(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -735,7 +897,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
let reader =
|
||||
HttpReader::new_with_stall_timeout(url.clone(), Method::GET, headers, Some(request.body), request.stall_timeout)
|
||||
.await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -1086,9 +1250,14 @@ where
|
||||
.generation
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| Error::other("put_file capability probe generation exhausted"))?;
|
||||
let (v1_was_pinned, pinned_boot_epoch) = match state.cached {
|
||||
Some(PutFileCapabilityState::V1 { peer_boot_epoch, .. }) => (true, peer_boot_epoch),
|
||||
_ => (false, None),
|
||||
};
|
||||
let flight = PutFileCapabilityFlight {
|
||||
generation: state.generation,
|
||||
v1_was_pinned: matches!(state.cached, Some(PutFileCapabilityState::V1 { .. })),
|
||||
v1_was_pinned,
|
||||
pinned_boot_epoch,
|
||||
outcome: Arc::new(OnceCell::new()),
|
||||
};
|
||||
state.in_flight = Some(flight.clone());
|
||||
@@ -1101,6 +1270,33 @@ where
|
||||
.get_or_init(|| async { probe().await.map_err(PutFileCapabilityProbeFailure) })
|
||||
.await;
|
||||
|
||||
let rollback_verified = if matches!(outcome, Ok(None)) && flight.v1_was_pinned && !*STREAM_RESPONSE_AUTH_STRICT {
|
||||
if let Some(pinned_boot_epoch) = flight.pinned_boot_epoch {
|
||||
let cached_boot_epoch = peer_authenticated_boot_epoch_for_addr(endpoint);
|
||||
let live_boot_epoch = if cached_boot_epoch.is_some_and(|live| live != pinned_boot_epoch) {
|
||||
cached_boot_epoch
|
||||
} else {
|
||||
probe_authenticated_peer_boot_epoch_for_addr(endpoint, STREAM_AUTH_ROLLBACK_PROBE_TIMEOUT).await
|
||||
};
|
||||
let verified = live_boot_epoch.is_some_and(|live| live != pinned_boot_epoch);
|
||||
if verified {
|
||||
info!(
|
||||
event = "internode_put_file_capability_unpinned_on_peer_restart",
|
||||
request_id = %propagated_request_id(),
|
||||
endpoint,
|
||||
pinned_boot_epoch = %pinned_boot_epoch,
|
||||
live_boot_epoch = ?live_boot_epoch,
|
||||
"Allowed put_file legacy fallback after authenticated peer boot_epoch change"
|
||||
);
|
||||
}
|
||||
verified
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
{
|
||||
let mut state = entry.write();
|
||||
let is_current_flight = state
|
||||
@@ -1115,11 +1311,13 @@ where
|
||||
}
|
||||
state.cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch: *server_epoch,
|
||||
peer_boot_epoch: peer_authenticated_boot_epoch_for_addr(endpoint),
|
||||
revalidate_after: Instant::now() + PUT_FILE_V1_CAPABILITY_TTL,
|
||||
});
|
||||
}
|
||||
Ok(None) if !flight.v1_was_pinned => {
|
||||
Ok(None) if !flight.v1_was_pinned || rollback_verified => {
|
||||
state.cached = Some(PutFileCapabilityState::LegacyUntil(Instant::now() + PUT_FILE_LEGACY_CAPABILITY_TTL));
|
||||
state.rejected_server_epoch = None;
|
||||
}
|
||||
Ok(None) | Err(_) => {}
|
||||
}
|
||||
@@ -1129,7 +1327,9 @@ where
|
||||
|
||||
match outcome {
|
||||
Ok(Some(server_epoch)) => Ok(Some(*server_epoch)),
|
||||
Ok(None) if flight.v1_was_pinned => Err(Error::other("remote put_file capability downgrade rejected")),
|
||||
Ok(None) if flight.v1_was_pinned && !rollback_verified => {
|
||||
Err(Error::other("remote put_file capability downgrade rejected"))
|
||||
}
|
||||
Ok(None) => Ok(None),
|
||||
Err(failure) => Err(failure.to_error()),
|
||||
}
|
||||
@@ -1494,6 +1694,7 @@ mod tests {
|
||||
put_file_capability_cache_entry(&endpoint).write().cached = Some(if authenticated {
|
||||
PutFileCapabilityState::V1 {
|
||||
server_epoch: Uuid::new_v4(),
|
||||
peer_boot_epoch: None,
|
||||
revalidate_after: Instant::now() + PUT_FILE_V1_CAPABILITY_TTL,
|
||||
}
|
||||
} else {
|
||||
@@ -2475,6 +2676,7 @@ mod tests {
|
||||
let server_epoch = Uuid::new_v4();
|
||||
v1_entry.write().cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch,
|
||||
peer_boot_epoch: None,
|
||||
revalidate_after: Instant::now() + PUT_FILE_V1_CAPABILITY_TTL,
|
||||
});
|
||||
assert_eq!(
|
||||
@@ -2494,6 +2696,7 @@ mod tests {
|
||||
assert!(!cache_probe_called.load(Ordering::SeqCst));
|
||||
v1_entry.write().cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch,
|
||||
peer_boot_epoch: None,
|
||||
revalidate_after: Instant::now(),
|
||||
});
|
||||
assert!(
|
||||
@@ -2777,6 +2980,7 @@ mod tests {
|
||||
state.generation = state.generation.checked_add(1).expect("test generation should advance");
|
||||
state.cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch: newer_epoch,
|
||||
peer_boot_epoch: None,
|
||||
revalidate_after: Instant::now() + PUT_FILE_V1_CAPABILITY_TTL,
|
||||
});
|
||||
state.in_flight = None;
|
||||
@@ -3449,6 +3653,7 @@ mod tests {
|
||||
STREAM_AUTH_PINNED_ENDPOINTS
|
||||
.write()
|
||||
.remove(&normalize_stream_auth_endpoint(&endpoint))
|
||||
.is_some()
|
||||
);
|
||||
let mut reader = transport.open_walk_dir(walk()).await.unwrap();
|
||||
assert_eq!(reader.read_to_end(&mut Vec::new()).await.unwrap(), 0);
|
||||
@@ -3522,4 +3727,112 @@ mod tests {
|
||||
.write()
|
||||
.remove(&normalize_stream_auth_endpoint(&endpoint));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_response_auth_unpins_on_authenticated_boot_epoch_change_and_rejects_same_epoch() {
|
||||
use crate::cluster::rpc::client::{
|
||||
clear_peer_replay_state_for_addr, set_peer_authenticated_boot_epoch_for_addr_for_test,
|
||||
};
|
||||
use crate::cluster::rpc::encode_stream_auth_eof_frame;
|
||||
use std::io::Cursor;
|
||||
|
||||
crate::runtime::sources::ensure_test_rpc_secret();
|
||||
let endpoint = format!("http://rollback-epoch-{}.invalid:9000", Uuid::new_v4());
|
||||
let empty = HeaderMap::new();
|
||||
let epoch_v2 = Uuid::new_v4();
|
||||
let epoch_rolled_back = Uuid::new_v4();
|
||||
|
||||
// Peer authenticates under epoch_v2 and proves framed stream support -> pinned to epoch_v2.
|
||||
set_peer_authenticated_boot_epoch_for_addr_for_test(&endpoint, Some(epoch_v2));
|
||||
let nonce = Uuid::new_v4();
|
||||
let url = format!("{endpoint}/rustfs/rpc/read_file_stream?disk=d1&stream_auth=framed-v1&stream_auth_nonce={nonce}");
|
||||
let empty_digest: [u8; 32] = Sha256::digest([]).into();
|
||||
let eof = encode_stream_auth_eof_frame(
|
||||
StreamResponseAuthDomain::ReadFileStream,
|
||||
&url,
|
||||
&Method::GET,
|
||||
nonce,
|
||||
0,
|
||||
0,
|
||||
&empty_digest,
|
||||
)
|
||||
.expect("empty EOF");
|
||||
let mut reader = AuthenticatedStreamReader::new(
|
||||
Cursor::new(eof.to_vec()),
|
||||
endpoint.clone(),
|
||||
StreamResponseAuthDomain::ReadFileStream,
|
||||
url,
|
||||
Method::GET,
|
||||
nonce,
|
||||
);
|
||||
reader.read_to_end(&mut Vec::new()).await.expect("verified stream");
|
||||
|
||||
// Same boot_epoch + stripped header MUST still fail closed (MITM downgrade protection).
|
||||
assert!(
|
||||
should_authenticate_response_stream(&endpoint, &empty, false).is_err(),
|
||||
"header stripping within same boot_epoch must still be rejected"
|
||||
);
|
||||
// Strict mode MUST reject even after boot_epoch transition.
|
||||
set_peer_authenticated_boot_epoch_for_addr_for_test(&endpoint, Some(epoch_rolled_back));
|
||||
assert!(
|
||||
should_authenticate_response_stream(&endpoint, &empty, true).is_err(),
|
||||
"strict mode must still reject unframed stream after peer restart"
|
||||
);
|
||||
// Non-strict mode allows unframed legacy stream once peer proves a new authenticated boot_epoch.
|
||||
assert!(
|
||||
!should_authenticate_response_stream(&endpoint, &empty, false)
|
||||
.expect("authenticated peer restart should unpin stream auth in non-strict mode")
|
||||
);
|
||||
|
||||
let _ = clear_peer_replay_state_for_addr(&endpoint);
|
||||
STREAM_AUTH_PINNED_ENDPOINTS
|
||||
.write()
|
||||
.remove(&normalize_stream_auth_endpoint(&endpoint));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_file_capability_allows_rollback_on_authenticated_boot_epoch_change_and_rejects_same_epoch() {
|
||||
use crate::cluster::rpc::client::{
|
||||
clear_peer_replay_state_for_addr, set_peer_authenticated_boot_epoch_for_addr_for_test,
|
||||
};
|
||||
|
||||
crate::runtime::sources::ensure_test_rpc_secret();
|
||||
let endpoint = format!("http://put-rollback-{}.invalid:9000", Uuid::new_v4());
|
||||
let epoch_v2 = Uuid::new_v4();
|
||||
let epoch_rolled_back = Uuid::new_v4();
|
||||
let server_epoch = Uuid::new_v4();
|
||||
|
||||
set_peer_authenticated_boot_epoch_for_addr_for_test(&endpoint, Some(epoch_v2));
|
||||
assert_eq!(
|
||||
resolve_put_file_auth_capability(&endpoint, || async { Ok(Some(server_epoch)) })
|
||||
.await
|
||||
.expect("initial v1 capability"),
|
||||
Some(server_epoch)
|
||||
);
|
||||
|
||||
// Expire TTL under SAME boot_epoch -> probe returning Ok(None) (404) MUST fail closed.
|
||||
put_file_capability_cache_entry(&endpoint).write().cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch,
|
||||
peer_boot_epoch: Some(epoch_v2),
|
||||
revalidate_after: Instant::now(),
|
||||
});
|
||||
assert!(
|
||||
resolve_put_file_auth_capability(&endpoint, || async { Ok(None) })
|
||||
.await
|
||||
.is_err(),
|
||||
"same-epoch downgrade to legacy put_file must be rejected"
|
||||
);
|
||||
|
||||
// Peer restarts and authenticates a new boot_epoch -> rollback to legacy put_file MUST succeed.
|
||||
set_peer_authenticated_boot_epoch_for_addr_for_test(&endpoint, Some(epoch_rolled_back));
|
||||
assert_eq!(
|
||||
resolve_put_file_auth_capability(&endpoint, || async { Ok(None) })
|
||||
.await
|
||||
.expect("authenticated peer restart should allow legacy put_file rollback"),
|
||||
None
|
||||
);
|
||||
|
||||
let _ = clear_peer_replay_state_for_addr(&endpoint);
|
||||
PUT_FILE_CAPABILITY_CACHE.write().remove(&endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use client::{
|
||||
AuthenticatedChannel, TonicInterceptor, gen_tonic_signature_interceptor, node_service_time_out_client,
|
||||
node_service_time_out_client_no_auth,
|
||||
};
|
||||
pub use context_propagation::{current_propagated_request_id, in_propagated_request_id, with_captured_request_id};
|
||||
// Re-exported through `api::rpc`; not every item is consumed inside this crate.
|
||||
#[allow(unused_imports)]
|
||||
pub use http_auth::{
|
||||
|
||||
@@ -63,6 +63,8 @@ pub const READ_FILE_NIXL_PATH: &str = "/rustfs/rpc/read_file_nixl";
|
||||
pub const WRITE_FILE_NIXL_PATH: &str = "/rustfs/rpc/write_file_nixl";
|
||||
/// Comma-separated buffers a NIXL shard write pulls, in file order (signed).
|
||||
pub const NIXL_BUFFERS_QUERY: &str = "nixl_buffers";
|
||||
/// Starting file offset of a NIXL shard write segment (signed).
|
||||
pub const NIXL_OFFSET_QUERY: &str = "nixl_offset";
|
||||
/// One-time nonce of a NIXL shard write (signed; recorded to refuse replays).
|
||||
pub const NIXL_NONCE_QUERY: &str = "nixl_nonce";
|
||||
/// Buffers a writer fills before it sends a segment; a part's shard file
|
||||
@@ -428,6 +430,7 @@ async fn send_segment(
|
||||
request: WriteStreamRequest,
|
||||
buffers: Vec<(LentBuffer, usize)>,
|
||||
append: bool,
|
||||
offset: Option<u64>,
|
||||
last: bool,
|
||||
timeout: Duration,
|
||||
) -> io::Result<()> {
|
||||
@@ -443,7 +446,7 @@ async fn send_segment(
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let url = format!(
|
||||
let mut url = format!(
|
||||
"{}{WRITE_FILE_NIXL_PATH}?disk={}&volume={}&path={}&append={append}&size={}&last={last}&{NIXL_NONCE_QUERY}={}&{NIXL_AGENT_QUERY}={}&{NIXL_BUFFERS_QUERY}={}&{NIXL_METADATA_SHA256_QUERY}={}",
|
||||
request.endpoint,
|
||||
urlencoding::encode(&request.disk),
|
||||
@@ -455,6 +458,9 @@ async fn send_segment(
|
||||
urlencoding::encode(&descriptors),
|
||||
pool.metadata_sha256_hex()
|
||||
);
|
||||
if let Some(offset) = offset {
|
||||
url.push_str(&format!("&{NIXL_OFFSET_QUERY}={offset}"));
|
||||
}
|
||||
let mut headers = json_headers();
|
||||
headers.insert(
|
||||
NIXL_METADATA_HEADER,
|
||||
@@ -509,6 +515,7 @@ struct WriterState {
|
||||
reserving: Option<ReserveFuture>,
|
||||
sending: Option<SegmentFuture>,
|
||||
segments_sent: usize,
|
||||
bytes_sent: u64,
|
||||
shut_down: bool,
|
||||
}
|
||||
|
||||
@@ -516,12 +523,16 @@ impl WriterState {
|
||||
fn start_segment(&mut self, last: bool) {
|
||||
let buffers = std::mem::take(&mut self.filled);
|
||||
let append = self.base.append || self.segments_sent > 0;
|
||||
let offset = (!self.base.append).then_some(self.bytes_sent);
|
||||
let segment_bytes = buffers.iter().fold(0u64, |acc, (_, len)| acc.saturating_add(*len as u64));
|
||||
self.bytes_sent = self.bytes_sent.saturating_add(segment_bytes);
|
||||
self.segments_sent += 1;
|
||||
self.sending = Some(Box::pin(send_segment(
|
||||
Arc::clone(&self.pool),
|
||||
self.base.clone(),
|
||||
buffers,
|
||||
append,
|
||||
offset,
|
||||
last,
|
||||
self.timeout,
|
||||
)));
|
||||
@@ -595,6 +606,26 @@ impl WriterState {
|
||||
}
|
||||
}
|
||||
self.shut_down = true;
|
||||
if !self.base.append
|
||||
&& let Ok(expected) = u64::try_from(self.base.size)
|
||||
{
|
||||
let pending_bytes = self.filled.iter().fold(0u64, |acc, (_, len)| acc.saturating_add(*len as u64));
|
||||
let total_bytes = self.bytes_sent.saturating_add(pending_bytes);
|
||||
if total_bytes != expected {
|
||||
debug!(
|
||||
component = LOG_COMPONENT_INTERNODE,
|
||||
subsystem = LOG_SUBSYSTEM_NIXL,
|
||||
result = "failed",
|
||||
total_bytes,
|
||||
expected,
|
||||
"nixl internode write length does not match declared size"
|
||||
);
|
||||
for (buffer, _) in std::mem::take(&mut self.filled) {
|
||||
buffer.release();
|
||||
}
|
||||
return Poll::Ready(Err(io::Error::other("nixl internode write length does not match declared size")));
|
||||
}
|
||||
}
|
||||
if !self.filled.is_empty() || self.segments_sent == 0 {
|
||||
// The last segment; with nothing written at all it still creates the file.
|
||||
self.start_segment(true);
|
||||
@@ -623,6 +654,7 @@ impl NixlFileWriter {
|
||||
reserving: None,
|
||||
sending: None,
|
||||
segments_sent: 0,
|
||||
bytes_sent: 0,
|
||||
shut_down: false,
|
||||
}),
|
||||
}
|
||||
@@ -857,6 +889,14 @@ mod tests {
|
||||
let request = std::str::from_utf8(&request).expect("request text");
|
||||
let target = request.split_whitespace().nth(1).expect("request target");
|
||||
let url = url::Url::parse(&format!("http://{address}{target}")).expect("segment URL");
|
||||
let offset = url
|
||||
.query_pairs()
|
||||
.find(|(name, _)| name == NIXL_OFFSET_QUERY)
|
||||
.expect("signed segment offset")
|
||||
.1
|
||||
.parse::<usize>()
|
||||
.expect("numeric offset");
|
||||
assert_eq!(offset, received, "each segment carries its starting file offset");
|
||||
let descriptors = url
|
||||
.query_pairs()
|
||||
.find(|(name, _)| name == NIXL_BUFFERS_QUERY)
|
||||
@@ -968,4 +1008,23 @@ mod tests {
|
||||
assert_eq!(bytes.len(), 5);
|
||||
assert_eq!(released.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_rejects_short_or_long_declared_shard_writes() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
for (declared, written) in [(20, 12usize), (12, 20usize), (0, 4usize)] {
|
||||
let request = WriteStreamRequest {
|
||||
endpoint: "http://127.0.0.1:1".to_owned(),
|
||||
disk: "disk".to_owned(),
|
||||
volume: "volume".to_owned(),
|
||||
path: "path".to_owned(),
|
||||
append: false,
|
||||
size: declared,
|
||||
};
|
||||
let mut writer = NixlFileWriter::new(Arc::new(VecPool), request);
|
||||
writer.write_all(&vec![3u8; written]).await.expect("stage bytes");
|
||||
let error = writer.shutdown().await.expect_err("mismatched declared size must fail");
|
||||
assert!(error.to_string().contains("does not match declared size"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1463,6 +1463,114 @@ fn internode_idempotent_read_retries() -> usize {
|
||||
static PREWARMED_PEERS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
|
||||
std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));
|
||||
|
||||
/// Tracks multi-disk timeout bursts per peer `addr` so that when a single host
|
||||
/// stops answering across multiple drives (e.g. `SIGSTOP` grey failure in 3x4),
|
||||
/// sibling drives on that host fast-fail instead of each paying independent 5-10s
|
||||
/// timeouts. A single disk timing out never triggers host-level fast-fail, and
|
||||
/// any successful RPC or periodic re-probe clears degradation immediately.
|
||||
#[derive(Default)]
|
||||
struct HostTimeoutDegradationState {
|
||||
timed_out_endpoints: std::collections::HashMap<String, tokio::time::Instant>,
|
||||
degraded_until: Option<tokio::time::Instant>,
|
||||
last_probe_allowed: Option<tokio::time::Instant>,
|
||||
}
|
||||
|
||||
const HOST_TIMEOUT_CORRELATION_WINDOW: Duration = Duration::from_secs(15);
|
||||
const HOST_TIMEOUT_DEGRADATION_TTL: Duration = Duration::from_secs(5);
|
||||
const HOST_TIMEOUT_REPROBE_INTERVAL: Duration = Duration::from_secs(2);
|
||||
const HOST_TIMEOUT_MIN_DISTINCT_DISKS: usize = 2;
|
||||
|
||||
static HOST_TIMEOUT_DEGRADATION: std::sync::LazyLock<
|
||||
std::sync::Mutex<std::collections::HashMap<String, HostTimeoutDegradationState>>,
|
||||
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
|
||||
|
||||
static HOST_RPC_PROGRESS: std::sync::LazyLock<
|
||||
std::sync::Mutex<std::collections::HashMap<String, Arc<std::sync::atomic::AtomicU64>>>,
|
||||
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
|
||||
|
||||
fn host_progress_counter(addr: &str) -> Arc<std::sync::atomic::AtomicU64> {
|
||||
let mut map = HOST_RPC_PROGRESS.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if let Some(counter) = map.get(addr) {
|
||||
return Arc::clone(counter);
|
||||
}
|
||||
let counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
map.insert(addr.to_owned(), Arc::clone(&counter));
|
||||
counter
|
||||
}
|
||||
|
||||
pub(crate) fn host_completed_ops(addr: &str) -> u64 {
|
||||
let Ok(map) = HOST_RPC_PROGRESS.lock() else {
|
||||
return 0;
|
||||
};
|
||||
map.get(addr)
|
||||
.map_or(0, |counter| counter.load(std::sync::atomic::Ordering::Acquire))
|
||||
}
|
||||
|
||||
fn record_host_rpc_success(addr: &str) {
|
||||
host_progress_counter(addr).fetch_add(1, std::sync::atomic::Ordering::AcqRel);
|
||||
clear_host_timeout_degradation(addr);
|
||||
}
|
||||
|
||||
fn record_host_disk_timeout(addr: &str, endpoint: &str) {
|
||||
let now = tokio::time::Instant::now();
|
||||
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
|
||||
return;
|
||||
};
|
||||
let state = map.entry(addr.to_owned()).or_default();
|
||||
state
|
||||
.timed_out_endpoints
|
||||
.retain(|_, ts| now.saturating_duration_since(*ts) <= HOST_TIMEOUT_CORRELATION_WINDOW);
|
||||
state.timed_out_endpoints.insert(endpoint.to_owned(), now);
|
||||
if state.timed_out_endpoints.len() >= HOST_TIMEOUT_MIN_DISTINCT_DISKS {
|
||||
state.degraded_until = Some(now + HOST_TIMEOUT_DEGRADATION_TTL);
|
||||
state.last_probe_allowed.get_or_insert(now);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_host_timeout_degraded(addr: &str) -> bool {
|
||||
let now = tokio::time::Instant::now();
|
||||
let Ok(map) = HOST_TIMEOUT_DEGRADATION.lock() else {
|
||||
return false;
|
||||
};
|
||||
map.get(addr)
|
||||
.and_then(|state| state.degraded_until)
|
||||
.is_some_and(|until| now < until)
|
||||
}
|
||||
|
||||
fn clear_host_timeout_degradation(addr: &str) {
|
||||
if let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() {
|
||||
map.remove(addr);
|
||||
}
|
||||
}
|
||||
|
||||
fn host_timeout_fast_fail_should_bypass(addr: &str) -> bool {
|
||||
let now = tokio::time::Instant::now();
|
||||
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
|
||||
return false;
|
||||
};
|
||||
let Some(state) = map.get_mut(addr) else {
|
||||
return false;
|
||||
};
|
||||
let Some(until) = state.degraded_until else {
|
||||
return false;
|
||||
};
|
||||
if now >= until {
|
||||
state.degraded_until = None;
|
||||
state
|
||||
.timed_out_endpoints
|
||||
.retain(|_, ts| now.saturating_duration_since(*ts) <= HOST_TIMEOUT_CORRELATION_WINDOW);
|
||||
return false;
|
||||
}
|
||||
if state
|
||||
.last_probe_allowed
|
||||
.is_none_or(|last| now.saturating_duration_since(last) >= HOST_TIMEOUT_REPROBE_INTERVAL)
|
||||
{
|
||||
state.last_probe_allowed = Some(now);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn claim_control_channel_prewarm(addr: &str) -> bool {
|
||||
let Ok(mut prewarmed) = PREWARMED_PEERS.lock() else {
|
||||
return false;
|
||||
@@ -2354,6 +2462,7 @@ impl RemoteDisk {
|
||||
cancel_token: CancellationToken,
|
||||
) {
|
||||
let mut interval = time::interval(get_drive_returning_probe_interval());
|
||||
let initial_boot_epoch = crate::cluster::rpc::client::peer_authenticated_boot_epoch_for_addr(&addr);
|
||||
debug!(
|
||||
event = EVENT_REMOTE_DISK_HEALTH,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
@@ -2380,14 +2489,22 @@ impl RemoteDisk {
|
||||
}
|
||||
_ = interval.tick() => {
|
||||
if Self::perform_recovery_probe(&addr, &endpoint).await.is_ok() {
|
||||
clear_host_timeout_degradation(&addr);
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable(&addr);
|
||||
let became_online = health.mark_recovery_success(&endpoint, "disk_info_probe_success");
|
||||
let current_boot_epoch = crate::cluster::rpc::client::peer_authenticated_boot_epoch_for_addr(&addr);
|
||||
let peer_restarted = current_boot_epoch.is_some() && current_boot_epoch != initial_boot_epoch;
|
||||
let became_online = if peer_restarted {
|
||||
health.mark_peer_restarted_online(&endpoint, "peer_restarted_disk_info_probe_success")
|
||||
} else {
|
||||
health.mark_recovery_success(&endpoint, "disk_info_probe_success")
|
||||
};
|
||||
debug!(
|
||||
event = EVENT_REMOTE_DISK_HEALTH,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REMOTE_DISK,
|
||||
endpoint = %endpoint,
|
||||
addr,
|
||||
peer_restarted,
|
||||
state = "recovery_probe_succeeded",
|
||||
"Remote disk recovery probe succeeded"
|
||||
);
|
||||
@@ -2411,6 +2528,38 @@ impl RemoteDisk {
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a post-quorum straggler timeout observed during metadata fanout.
|
||||
/// Requires `HOST_TIMEOUT_MIN_DISTINCT_DISKS` (>= 2) distinct drives on the
|
||||
/// same host to time out within the correlation window, so a single slow HDD
|
||||
/// never engages host-level fast-fail while a `SIGSTOP`'d peer holding 4
|
||||
/// drives fast-fails immediately on subsequent requests.
|
||||
pub(crate) fn record_straggler_timeout_if_stalled(&self, host_completed_before: u64) {
|
||||
if host_completed_ops(&self.addr) > host_completed_before {
|
||||
return;
|
||||
}
|
||||
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
|
||||
}
|
||||
|
||||
pub(crate) fn host_completed_ops(&self) -> u64 {
|
||||
host_completed_ops(&self.addr)
|
||||
}
|
||||
|
||||
/// On-demand bounded recovery probe used only when a read is about to fail read quorum due to
|
||||
/// `FaultyDisk` remote drives (e.g., drives waiting in `Returning` right after a rolling restart).
|
||||
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
|
||||
if !self.health.is_faulty() {
|
||||
return false;
|
||||
}
|
||||
let Ok(Ok(())) = timeout(Duration::from_millis(1000), Self::perform_recovery_probe(&self.addr, &self.endpoint)).await
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
record_host_rpc_success(&self.addr);
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable(&self.addr);
|
||||
self.health
|
||||
.mark_peer_restarted_online(&self.endpoint, "on_demand_quorum_recovery_probe_success")
|
||||
}
|
||||
|
||||
async fn perform_recovery_probe(addr: &str, endpoint: &Endpoint) -> Result<()> {
|
||||
let mut evict_cached_connection = false;
|
||||
let result = match timeout(get_drive_active_check_timeout(), async {
|
||||
@@ -2508,6 +2657,7 @@ impl RemoteDisk {
|
||||
.unwrap_or_else(|| time::sleep(timeout_duration).deadline())
|
||||
});
|
||||
let max_retries = internode_idempotent_read_retries();
|
||||
let drive_completed_before = self.health.completed_ops();
|
||||
let mut attempt = 0usize;
|
||||
loop {
|
||||
let attempt_timeout = deadline
|
||||
@@ -2528,8 +2678,13 @@ impl RemoteDisk {
|
||||
.await
|
||||
{
|
||||
Err(err) if attempt < max_retries && is_network_like_disk_error(&err) => {
|
||||
if matches!(err, DiskError::Timeout) && is_host_timeout_degraded(&self.addr) {
|
||||
return Err(err);
|
||||
}
|
||||
if matches!(err, DiskError::Timeout) && deadline.is_some_and(|deadline| time::Instant::now() >= deadline) {
|
||||
self.mark_faulty("read_operation_deadline");
|
||||
if self.health.completed_ops() == drive_completed_before {
|
||||
self.mark_faulty("read_operation_deadline");
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
attempt += 1;
|
||||
@@ -2604,6 +2759,14 @@ impl RemoteDisk {
|
||||
return Err(DiskError::FaultyDisk);
|
||||
}
|
||||
|
||||
// Host-level grey-failure fast-fail: when multiple distinct drives on the
|
||||
// same peer host recently timed out, short-circuit sibling drives (including
|
||||
// idempotent read attempts whose attempt-0 health action is IgnoreFailure)
|
||||
// so quorum operations stay sub-second while allowing periodic self-healing probes.
|
||||
if host_timeout_fast_fail_should_bypass(&self.addr) {
|
||||
return Err(DiskError::Timeout);
|
||||
}
|
||||
|
||||
// Record operation start
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
@@ -2613,34 +2776,61 @@ impl RemoteDisk {
|
||||
let _waiting_guard = self.health.waiting_guard();
|
||||
|
||||
if timeout_duration == Duration::ZERO {
|
||||
let drive_completed_before = self.health.completed_ops();
|
||||
let host_completed_before = host_completed_ops(&self.addr);
|
||||
let operation_result = operation().await;
|
||||
if operation_result.is_ok() {
|
||||
record_host_rpc_success(&self.addr);
|
||||
self.health.record_operation_success(&self.endpoint, "operation_success");
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
|
||||
}
|
||||
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
|
||||
.await;
|
||||
let drive_stalled = self.health.completed_ops() == drive_completed_before;
|
||||
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
|
||||
self.handle_network_like_error(
|
||||
op,
|
||||
timeout_duration,
|
||||
&operation_result,
|
||||
failure_health_action,
|
||||
drive_stalled,
|
||||
host_stalled,
|
||||
)
|
||||
.await;
|
||||
return operation_result;
|
||||
}
|
||||
|
||||
// Execute operation with timeout
|
||||
let drive_completed_before = self.health.completed_ops();
|
||||
let host_completed_before = host_completed_ops(&self.addr);
|
||||
let result = time::timeout(timeout_duration, operation()).await;
|
||||
|
||||
match result {
|
||||
Ok(operation_result) => {
|
||||
// Log success; the waiting guard balances every exit path.
|
||||
if operation_result.is_ok() {
|
||||
record_host_rpc_success(&self.addr);
|
||||
self.health.record_operation_success(&self.endpoint, "operation_success");
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
|
||||
}
|
||||
self.handle_network_like_error(op, timeout_duration, &operation_result, failure_health_action)
|
||||
.await;
|
||||
let drive_stalled = self.health.completed_ops() == drive_completed_before;
|
||||
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
|
||||
self.handle_network_like_error(
|
||||
op,
|
||||
timeout_duration,
|
||||
&operation_result,
|
||||
failure_health_action,
|
||||
drive_stalled,
|
||||
host_stalled,
|
||||
)
|
||||
.await;
|
||||
operation_result
|
||||
}
|
||||
Err(_) => {
|
||||
self.record_timeout(op, timeout_duration);
|
||||
if failure_health_action == FailureHealthAction::MarkFailure {
|
||||
self.mark_faulty_and_evict("operation_timeout").await;
|
||||
let drive_stalled = self.health.completed_ops() == drive_completed_before;
|
||||
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
|
||||
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
|
||||
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
|
||||
self.mark_faulty_with_eviction("operation_timeout", host_stalled).await;
|
||||
}
|
||||
Err(DiskError::Timeout)
|
||||
}
|
||||
@@ -2661,17 +2851,32 @@ impl RemoteDisk {
|
||||
self.record_timeout(op, timeout_duration);
|
||||
return Err(DiskError::Timeout);
|
||||
}
|
||||
let drive_completed_before = self.health.completed_ops();
|
||||
let host_completed_before = host_completed_ops(&self.addr);
|
||||
match time::timeout(timeout_duration, operation()).await {
|
||||
Ok(operation_result) => {
|
||||
if operation_result.is_ok() {
|
||||
record_host_rpc_success(&self.addr);
|
||||
self.health.record_operation_success(&self.endpoint, "operation_success");
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
|
||||
}
|
||||
let evict = operation_result
|
||||
.as_ref()
|
||||
.err()
|
||||
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
|
||||
self.handle_network_like_error(op, timeout_duration, &operation_result, FailureHealthAction::IgnoreFailure)
|
||||
.await;
|
||||
let drive_stalled = self.health.completed_ops() == drive_completed_before;
|
||||
let host_stalled = host_completed_ops(&self.addr) == host_completed_before;
|
||||
let evict = drive_stalled
|
||||
&& host_stalled
|
||||
&& operation_result
|
||||
.as_ref()
|
||||
.err()
|
||||
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
|
||||
self.handle_network_like_error(
|
||||
op,
|
||||
timeout_duration,
|
||||
&operation_result,
|
||||
FailureHealthAction::IgnoreFailure,
|
||||
drive_stalled,
|
||||
host_stalled,
|
||||
)
|
||||
.await;
|
||||
if evict {
|
||||
evict_failed_connection_with_reason(
|
||||
&self.addr,
|
||||
@@ -2684,12 +2889,16 @@ impl RemoteDisk {
|
||||
}
|
||||
Err(_) => {
|
||||
self.record_timeout(op, timeout_duration);
|
||||
evict_failed_connection_with_reason(
|
||||
&self.addr,
|
||||
ChannelRebuildReason::OperationTimeout,
|
||||
ConnectionEvictionLogLevel::Debug,
|
||||
)
|
||||
.await;
|
||||
if self.health.completed_ops() == drive_completed_before
|
||||
&& host_completed_ops(&self.addr) == host_completed_before
|
||||
{
|
||||
evict_failed_connection_with_reason(
|
||||
&self.addr,
|
||||
ChannelRebuildReason::OperationTimeout,
|
||||
ConnectionEvictionLogLevel::Debug,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(DiskError::Timeout)
|
||||
}
|
||||
}
|
||||
@@ -2724,6 +2933,8 @@ impl RemoteDisk {
|
||||
timeout_duration: Duration,
|
||||
operation_result: &Result<T>,
|
||||
failure_health_action: FailureHealthAction,
|
||||
drive_stalled: bool,
|
||||
host_stalled: bool,
|
||||
) {
|
||||
if let Err(err) = operation_result
|
||||
&& !err.is_metacache_output_stream_closed()
|
||||
@@ -2749,8 +2960,8 @@ impl RemoteDisk {
|
||||
"Remote disk operation returned network-like error"
|
||||
);
|
||||
}
|
||||
if failure_health_action == FailureHealthAction::MarkFailure {
|
||||
self.mark_faulty_and_evict("operation_network_error").await;
|
||||
if failure_health_action == FailureHealthAction::MarkFailure && drive_stalled {
|
||||
self.mark_faulty_with_eviction("operation_network_error", host_stalled).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2796,8 +3007,8 @@ impl RemoteDisk {
|
||||
state != previous_state
|
||||
}
|
||||
|
||||
async fn mark_faulty_and_evict(&self, reason: &'static str) {
|
||||
if self.mark_faulty(reason) {
|
||||
async fn mark_faulty_with_eviction(&self, reason: &'static str, evict_connection: bool) {
|
||||
if self.mark_faulty(reason) && evict_connection {
|
||||
counter!(
|
||||
"rustfs_drive_connection_evict_total",
|
||||
"endpoint" => self.endpoint.to_string(),
|
||||
@@ -4110,7 +4321,8 @@ impl DiskAPI for RemoteDisk {
|
||||
"Remote disk RPC started"
|
||||
);
|
||||
|
||||
self.execute_with_timeout(
|
||||
self.execute_with_timeout_for_op(
|
||||
"stat_volume",
|
||||
|| async {
|
||||
let mut client = self.get_client().await?;
|
||||
let request = Request::new(StatVolumeRequest {
|
||||
@@ -14873,4 +15085,107 @@ mod tests {
|
||||
.await;
|
||||
peer.stop().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_timeout_fast_fail_requires_two_distinct_disks_and_clears_on_success() {
|
||||
let addr = "http://127.0.0.1:19390";
|
||||
clear_host_timeout_degradation(addr);
|
||||
|
||||
// Single disk timing out once (or repeatedly) must NOT engage host-level fast-fail.
|
||||
record_host_disk_timeout(addr, "http://127.0.0.1:19390/data1");
|
||||
record_host_disk_timeout(addr, "http://127.0.0.1:19390/data1");
|
||||
assert!(
|
||||
!host_timeout_fast_fail_should_bypass(addr),
|
||||
"single timed-out disk must not trip host-level fast-fail"
|
||||
);
|
||||
|
||||
// Second distinct disk on the same host timing out engages host-level fast-fail
|
||||
// immediately until the periodic re-probe interval elapses.
|
||||
record_host_disk_timeout(addr, "http://127.0.0.1:19390/data2");
|
||||
assert!(is_host_timeout_degraded(addr));
|
||||
assert!(
|
||||
host_timeout_fast_fail_should_bypass(addr),
|
||||
"sibling requests during degradation window must fast-fail immediately"
|
||||
);
|
||||
|
||||
// Any single successful RPC on the host clears degradation immediately.
|
||||
clear_host_timeout_degradation(addr);
|
||||
assert!(!is_host_timeout_degraded(addr));
|
||||
assert!(
|
||||
!host_timeout_fast_fail_should_bypass(addr),
|
||||
"host degradation must clear immediately after a successful RPC"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sibling_drive_progress_preserves_host_channel_without_suppressing_stalled_drive_fault() {
|
||||
async fn make_drive(port: u16, disk_idx: i32) -> RemoteDisk {
|
||||
let url = url::Url::parse(&format!("http://127.0.0.1:{port}/data{disk_idx}")).expect("endpoint url");
|
||||
let endpoint = Endpoint {
|
||||
url,
|
||||
is_local: false,
|
||||
pool_idx: 0,
|
||||
set_idx: 0,
|
||||
disk_idx,
|
||||
};
|
||||
RemoteDisk::new(
|
||||
&endpoint,
|
||||
&DiskOption {
|
||||
cleanup: false,
|
||||
health_check: false,
|
||||
},
|
||||
Arc::new(TcpHttpInternodeDataTransport),
|
||||
)
|
||||
.await
|
||||
.expect("remote disk handle")
|
||||
}
|
||||
|
||||
let stalled_drive = make_drive(59985, 0).await;
|
||||
let sibling_drive = make_drive(59985, 1).await;
|
||||
let addr = stalled_drive.addr.clone();
|
||||
clear_host_timeout_degradation(&addr);
|
||||
|
||||
let dummy_channel = tonic::transport::Endpoint::from_static("http://127.0.0.1:59985").connect_lazy();
|
||||
rustfs_common::cache_connection(addr.clone(), dummy_channel).await;
|
||||
assert!(rustfs_common::has_cached_connection(&addr).await);
|
||||
|
||||
// Start a slow operation on `stalled_drive` while `sibling_drive` on the same host
|
||||
// completes an RPC before `stalled_drive` times out.
|
||||
let sibling_ref = &sibling_drive;
|
||||
let err = stalled_drive
|
||||
.execute_with_timeout_for_op_and_health_action(
|
||||
"write_all",
|
||||
|| async move {
|
||||
sibling_ref
|
||||
.execute_with_timeout_for_op_and_health_action(
|
||||
"read_all",
|
||||
|| async { Ok::<(), Error>(()) },
|
||||
Duration::from_secs(1),
|
||||
FailureHealthAction::MarkFailure,
|
||||
)
|
||||
.await
|
||||
.expect("sibling drive RPC succeeds");
|
||||
tokio::time::sleep(Duration::from_millis(80)).await;
|
||||
Ok::<(), Error>(())
|
||||
},
|
||||
Duration::from_millis(20),
|
||||
FailureHealthAction::MarkFailure,
|
||||
)
|
||||
.await
|
||||
.expect_err("stalled drive must time out");
|
||||
|
||||
assert!(matches!(err, DiskError::Timeout));
|
||||
assert_ne!(
|
||||
stalled_drive.runtime_state(),
|
||||
RuntimeDriveHealthState::Online,
|
||||
"sibling drive progress must not suppress mark_faulty on the drive that actually timed out"
|
||||
);
|
||||
assert!(
|
||||
rustfs_common::has_cached_connection(&addr).await,
|
||||
"host-level progress from sibling drive must suppress shared-channel eviction"
|
||||
);
|
||||
|
||||
rustfs_protos::evict_failed_connection(&addr).await;
|
||||
clear_host_timeout_degradation(&addr);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -686,21 +686,34 @@ impl RemoteClient {
|
||||
}
|
||||
}
|
||||
|
||||
fn record_request_timeout(&self, op: &'static str, deadline: Duration) {
|
||||
fn record_request_timeout(&self, op: &'static str, deadline: Duration, admission: Option<LockRequestAdmission>) {
|
||||
if !is_request_breaker_operation(op) {
|
||||
return;
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
with_lock_peer_health(&self.addr, |health| {
|
||||
// Once request backoff is active (`request_backoff_until.is_some()`), only a timeout
|
||||
// from the currently admitted half-open probe generation may escalate or re-arm the
|
||||
// backoff window. Straggler timeouts from RPCs admitted before backoff opened
|
||||
// (`probe_generation: None`) or from a superseded probe generation must not compound
|
||||
// backoff even if they arrive after `until` has elapsed.
|
||||
if health.request_backoff_until.is_some() {
|
||||
let is_active_probe = admission
|
||||
.and_then(|token| token.probe_generation)
|
||||
.is_some_and(|generation| health.request_probe_generation == Some(generation));
|
||||
if !is_active_probe {
|
||||
return;
|
||||
}
|
||||
}
|
||||
health.request_consecutive_timeouts = health.request_consecutive_timeouts.saturating_add(1);
|
||||
if health.request_consecutive_timeouts < LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
|
||||
return;
|
||||
}
|
||||
|
||||
let initial = deadline / 2;
|
||||
let initial = (deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500));
|
||||
let next = if health.request_backoff.is_zero() {
|
||||
initial.max(Duration::from_millis(1))
|
||||
initial
|
||||
} else {
|
||||
health.request_backoff.saturating_mul(2)
|
||||
};
|
||||
@@ -1274,7 +1287,7 @@ impl RemoteClient {
|
||||
let reason = err.to_string();
|
||||
if err.code() == tonic::Code::DeadlineExceeded {
|
||||
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
|
||||
self.record_request_timeout(op, deadline);
|
||||
self.record_request_timeout(op, deadline, token);
|
||||
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
|
||||
if Self::is_scanner_leader_lock(resource_summary) {
|
||||
debug!(
|
||||
@@ -1324,7 +1337,7 @@ impl RemoteClient {
|
||||
// the offline threshold for no benefit. See issue #4567.
|
||||
let transport_failure = Self::is_transport_failure(&err);
|
||||
if transport_failure {
|
||||
self.record_request_timeout(op, deadline);
|
||||
self.record_request_timeout(op, deadline, token);
|
||||
}
|
||||
if Self::is_scanner_leader_lock(resource_summary) {
|
||||
debug!(
|
||||
@@ -1412,7 +1425,7 @@ impl RemoteClient {
|
||||
None => {
|
||||
let reason = format!("RPC timed out after {deadline:?}");
|
||||
rustfs_io_metrics::lock_metrics::record_remote_lock_rpc_timeout(&self.addr, op);
|
||||
self.record_request_timeout(op, deadline);
|
||||
self.record_request_timeout(op, deadline, token);
|
||||
let (log_timeout, suppressed_timeouts) = self.timeout_log_decision(op, deadline);
|
||||
if Self::is_scanner_leader_lock(resource_summary) {
|
||||
debug!(
|
||||
@@ -1541,7 +1554,7 @@ impl LockClient for RemoteClient {
|
||||
let mut client = match self.get_client().await {
|
||||
Ok(client) => client,
|
||||
Err(err) => {
|
||||
self.record_request_timeout("lock", rpc_timeout);
|
||||
self.record_request_timeout("lock", rpc_timeout, admission.admission);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
@@ -2209,7 +2222,7 @@ mod tests {
|
||||
reset_lock_peer_health_for_test(addr);
|
||||
|
||||
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
|
||||
client.record_request_timeout("lock", Duration::from_millis(100));
|
||||
client.record_request_timeout("lock", Duration::from_millis(100), None);
|
||||
}
|
||||
|
||||
assert!(
|
||||
@@ -2263,7 +2276,7 @@ mod tests {
|
||||
});
|
||||
|
||||
let first = client.admit_lock_request("lock").expect("first probe should be admitted");
|
||||
client.record_request_timeout("lock", Duration::from_millis(10));
|
||||
client.record_request_timeout("lock", Duration::from_millis(10), Some(first));
|
||||
with_lock_peer_health(addr, |health| {
|
||||
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(1));
|
||||
health.request_in_flight = 0;
|
||||
@@ -2279,6 +2292,46 @@ mod tests {
|
||||
reset_lock_peer_health_for_test(addr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_pre_backoff_timeout_after_expiry_does_not_escalate_without_failed_probe() {
|
||||
let addr = "http://breaker-late-timeout-test";
|
||||
let client = RemoteClient::new(addr.to_string());
|
||||
reset_lock_peer_health_for_test(addr);
|
||||
|
||||
let pre_backoff = client
|
||||
.admit_lock_request("lock")
|
||||
.expect("normal pre-backoff RPC should be admitted");
|
||||
assert!(!pre_backoff.is_probe());
|
||||
|
||||
for _ in 0..LOCK_RPC_REQUEST_BACKOFF_THRESHOLD {
|
||||
client.record_request_timeout("lock", Duration::from_millis(100), None);
|
||||
}
|
||||
let initial_backoff = lock_peer_health_for_test(addr).request_backoff;
|
||||
assert_eq!(initial_backoff, Duration::from_millis(25));
|
||||
|
||||
// Simulate backoff window expiry while the pre-backoff RPC is still finishing.
|
||||
with_lock_peer_health(addr, |health| {
|
||||
health.request_backoff_until = Some(Instant::now() - Duration::from_millis(5));
|
||||
});
|
||||
|
||||
// A late timeout from a non-probe RPC (`probe_generation: None`) arriving after `until`
|
||||
// must NOT double the backoff or block the upcoming half-open probe.
|
||||
client.record_request_timeout("lock", Duration::from_millis(100), Some(pre_backoff));
|
||||
client.release_lock_request("lock", Some(pre_backoff));
|
||||
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff);
|
||||
|
||||
let probe = client
|
||||
.admit_lock_request("lock")
|
||||
.expect("expired backoff must still admit a half-open probe");
|
||||
assert!(probe.is_probe());
|
||||
|
||||
// Only when the active probe itself times out does the backoff escalate.
|
||||
client.record_request_timeout("lock", Duration::from_millis(100), Some(probe));
|
||||
client.release_lock_request("lock", Some(probe));
|
||||
assert_eq!(lock_peer_health_for_test(addr).request_backoff, initial_backoff * 2);
|
||||
reset_lock_peer_health_for_test(addr);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_acquire_request_matches_transport_deadline() {
|
||||
let request = test_lock_request(Duration::from_secs(30));
|
||||
|
||||
@@ -2008,10 +2008,12 @@ fn sync_rendered_target_section(
|
||||
|
||||
fn encode_server_config_blob(cfg: &Config, seed: Option<&[u8]>) -> Result<Vec<u8>> {
|
||||
let mut root = seed.and_then(parse_object_seed).unwrap_or_default();
|
||||
root.insert(
|
||||
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
|
||||
super::vector_maintenance::encode(cfg)?,
|
||||
);
|
||||
if !super::vector_maintenance::is_default(cfg) || root.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS) {
|
||||
root.insert(
|
||||
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
|
||||
super::vector_maintenance::encode(cfg)?,
|
||||
);
|
||||
}
|
||||
|
||||
if !matches!(root.get("version"), Some(Value::String(v)) if !v.trim().is_empty()) {
|
||||
root.insert("version".to_string(), Value::String("33".to_string()));
|
||||
@@ -3595,6 +3597,7 @@ mod tests {
|
||||
replication_decision: String::new(),
|
||||
checksum: None,
|
||||
multipart_completion_replayed: false,
|
||||
put_usage: None,
|
||||
backfilled_old_current_size: None,
|
||||
ec_block_size: None,
|
||||
}
|
||||
@@ -6166,4 +6169,43 @@ mod tests {
|
||||
assert!(err.is_quorum_error(), "expected quorum error, got {err:?}");
|
||||
assert_eq!(store.heal_calls.load(Ordering::SeqCst), 1, "heal should still be attempted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encode_server_config_blob_omits_default_s3vectors_maintenance_and_preserves_explicit() {
|
||||
super::super::init();
|
||||
let default_cfg = Config::new();
|
||||
assert!(
|
||||
default_cfg.0.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
|
||||
"Config::new() after config::init() populates default KVS"
|
||||
);
|
||||
|
||||
let blob = encode_server_config_blob(&default_cfg, None).expect("encode default server config");
|
||||
let parsed: serde_json::Map<String, Value> = serde_json::from_slice(&blob).expect("parse encoded config");
|
||||
assert!(
|
||||
!parsed.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
|
||||
"unrelated config saves must not inject default s3vectors_maintenance"
|
||||
);
|
||||
|
||||
let mut enabled_cfg = Config::new();
|
||||
let mut kvs = super::super::vector_maintenance::DEFAULT_KVS.clone();
|
||||
kvs.insert(rustfs_config::ENABLE_KEY.into(), "on".into());
|
||||
kvs.insert(rustfs_config::S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT.into(), "vec-maint-user".into());
|
||||
super::super::vector_maintenance::install(&mut enabled_cfg, kvs);
|
||||
|
||||
let enabled_blob = encode_server_config_blob(&enabled_cfg, None).expect("encode enabled vector maintenance");
|
||||
let enabled_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&enabled_blob).expect("parse enabled config");
|
||||
assert_eq!(
|
||||
enabled_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
|
||||
Value::String("on".into())
|
||||
);
|
||||
|
||||
// Resetting back to defaults on an existing seed that already contains s3vectors_maintenance
|
||||
// must overwrite the existing entry back to "off".
|
||||
let reset_blob = encode_server_config_blob(&default_cfg, Some(&enabled_blob)).expect("encode reset config");
|
||||
let reset_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&reset_blob).expect("parse reset config");
|
||||
assert_eq!(
|
||||
reset_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
|
||||
Value::String("off".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,6 +174,20 @@ pub(super) fn encode(config: &Config) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn is_default(config: &Config) -> bool {
|
||||
let Some(targets) = config.0.get(S3VECTORS_MAINTENANCE_SUB_SYS) else {
|
||||
return true;
|
||||
};
|
||||
if targets.len() != 1 || !targets.contains_key(DEFAULT_DELIMITER) {
|
||||
return false;
|
||||
}
|
||||
let Ok(normalized) = normalize(&targets[DEFAULT_DELIMITER]) else {
|
||||
return false;
|
||||
};
|
||||
normalized.get(ENABLE_KEY) == DEFAULT_KVS.get(ENABLE_KEY)
|
||||
&& normalized.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT) == DEFAULT_KVS.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT)
|
||||
}
|
||||
|
||||
pub(super) fn equivalent(lhs: &Config, rhs: &Config) -> bool {
|
||||
matches!((encode(lhs), encode(rhs)), (Ok(lhs), Ok(rhs)) if lhs == rhs)
|
||||
}
|
||||
|
||||
@@ -164,7 +164,8 @@ async fn verified_shard(info: &FileInfo) -> Result<Vec<u8>> {
|
||||
}
|
||||
let mut reader = BitrotReader::new(Cursor::new(data.clone()), shard_size, HashAlgorithm::HighwayHash256S, false);
|
||||
if let Some(integrity) = &info.parts[0].integrity {
|
||||
let proof = PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT)?;
|
||||
let proof =
|
||||
PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT, None)?;
|
||||
reader.set_integrity(ShardVerifier::new(proof, info.erasure.index - 1, 0, None)?)?;
|
||||
}
|
||||
let mut shard = vec![0; shard_size];
|
||||
|
||||
@@ -142,7 +142,7 @@ const DECOMMISSION_ENTRY_CONCURRENCY_DEFAULT_CAP: usize = 8;
|
||||
const DECOMMISSION_ENTRY_CONCURRENCY_HARD_CAP: usize = 64;
|
||||
const DECOMMISSION_ENTRY_WORKERS_PER_SET: usize = 2;
|
||||
const DECOMMISSION_CAPACITY_SNAPSHOT_CONCURRENCY: usize = 4;
|
||||
const DECOMMISSION_META_PREFIXES: [&str; 3] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX];
|
||||
const DECOMMISSION_META_PREFIXES: [&str; 5] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX, "s3tables", "s3vectors"];
|
||||
const DECOMMISSION_CAPACITY_LEGACY_MODEL_VERSION: u16 = 1;
|
||||
const DECOMMISSION_CAPACITY_TARGET_FENCE_MODEL_VERSION: u16 = 2;
|
||||
#[cfg(test)]
|
||||
@@ -13684,17 +13684,6 @@ impl ECStore {
|
||||
target_pool_indices: &[usize],
|
||||
admission: DecommissionCapacityAdmission,
|
||||
) -> Result<rustfs_lock::NamespaceLockGuard> {
|
||||
Ok(self
|
||||
.acquire_external_decommission_capacity_fence_with_active_source(target_pool_indices, admission)
|
||||
.await?
|
||||
.0)
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_external_decommission_capacity_fence_with_active_source(
|
||||
&self,
|
||||
target_pool_indices: &[usize],
|
||||
admission: DecommissionCapacityAdmission,
|
||||
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
|
||||
let save_guard = self.pool_meta_save_gate.read().await;
|
||||
let (pool_meta_guard, snapshot) = self
|
||||
.acquire_pool_meta_read_guard(&save_guard, "target capacity admission failed")
|
||||
@@ -13715,9 +13704,7 @@ impl ECStore {
|
||||
for target_pool_index in target_pool_indices.iter().copied() {
|
||||
ensure_external_decommission_target_admission(&snapshot, target_pool_index, admission)?;
|
||||
}
|
||||
let has_active_source = pool_meta_has_active_decommission(&snapshot);
|
||||
drop(save_guard);
|
||||
Ok((pool_meta_guard, has_active_source))
|
||||
Ok(pool_meta_guard)
|
||||
}
|
||||
|
||||
/// Fence healing of the pool metadata object itself without recursively
|
||||
@@ -13745,16 +13732,12 @@ impl ECStore {
|
||||
Ok((pool_meta_guard, admissions, save_guard))
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_decommission_capacity_release_fence_with_active_source(
|
||||
&self,
|
||||
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
|
||||
pub(crate) async fn acquire_decommission_capacity_release_fence(&self) -> Result<rustfs_lock::NamespaceLockGuard> {
|
||||
let save_guard = self.pool_meta_save_gate.read().await;
|
||||
let (pool_meta_guard, snapshot) = self
|
||||
let (pool_meta_guard, _) = self
|
||||
.acquire_pool_meta_read_guard(&save_guard, "capacity release fence failed")
|
||||
.await?;
|
||||
let has_active_source = pool_meta_has_active_decommission(&snapshot);
|
||||
drop(save_guard);
|
||||
Ok((pool_meta_guard, has_active_source))
|
||||
Ok(pool_meta_guard)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_decommission_capacity_admitted_mutation<T, F, Fut>(
|
||||
@@ -22577,6 +22560,7 @@ mod tests {
|
||||
"buckets/.usage.v2.json",
|
||||
"buckets/.usage.v2.json.bkp",
|
||||
"buckets/.usage.observed.json",
|
||||
"buckets/.usage.buckets.json",
|
||||
"buckets/.usage-progress.json",
|
||||
"buckets/photos/.usage-progress.json.bkp",
|
||||
"buckets/photos/.usage-progress.json.extra",
|
||||
@@ -22657,6 +22641,7 @@ mod tests {
|
||||
let controls = [
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.v2.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.observed.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.buckets.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/photos/.usage-progress.json.bkp"),
|
||||
(RUSTFS_META_BUCKET, "buckets/photos/.usage-cache.bin.extra"),
|
||||
(user_bucket, "ordinary-object"),
|
||||
@@ -22906,6 +22891,7 @@ mod tests {
|
||||
"buckets/photos/.usage-cache.bin.bkp.extra",
|
||||
"buckets/.usage.v2.json",
|
||||
"buckets/.usage.observed.json",
|
||||
"buckets/.usage.buckets.json",
|
||||
"buckets/photos/.usage-progress.json.bkp",
|
||||
] {
|
||||
let source_set = store.pools[0].get_disks_by_key(object);
|
||||
@@ -28016,7 +28002,7 @@ mod tests {
|
||||
.expect("hold the namespace writer while the read-only admission waits");
|
||||
let admission = tokio::spawn({
|
||||
let store = store.clone();
|
||||
async move { store.acquire_decommission_capacity_release_fence_with_active_source().await }
|
||||
async move { store.acquire_decommission_capacity_release_fence().await }
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
@@ -28065,7 +28051,7 @@ mod tests {
|
||||
);
|
||||
|
||||
drop(writer);
|
||||
let (read_fence, _) = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
|
||||
let read_fence = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
|
||||
.await
|
||||
.expect("the read-only admission must finish after releasing the namespace writer")
|
||||
.expect("the admission task must not panic")
|
||||
@@ -43367,6 +43353,12 @@ mod pools_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decommission_meta_prefixes_include_s3tables_and_s3vectors() {
|
||||
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3tables"));
|
||||
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3vectors"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn test_path2_bucket_object_with_base_path_supports_windows_separators() {
|
||||
|
||||
@@ -4150,6 +4150,97 @@ mod decommission_lock_order_tests {
|
||||
.expect("decommission activation should commit after the probe release");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn waiting_put_does_not_hold_capacity_needed_by_conditional_commit_and_activation() {
|
||||
use crate::set_disk::{PutObjectCommitBarrier, PutObjectCommitPause};
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
run_large_stack_current_thread_async_test("staged-put-activation", || async {
|
||||
let (_dirs, store, _peer) = test_three_pool_stores_with_isolated_node_contexts(None).await;
|
||||
let bucket = test_bucket("staged-put-activation");
|
||||
let object = "entry";
|
||||
store.make_bucket(&bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
let seeded = store.pools[2]
|
||||
.put_object(
|
||||
&bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"before".to_vec()),
|
||||
&ObjectOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
|
||||
set_decommission_capacity_info_overrides_for_test(
|
||||
store.id,
|
||||
vec![vec![
|
||||
DecommissionPoolCapacityInfo::for_test(0, layout, 0, 1024, 1024),
|
||||
DecommissionPoolCapacityInfo::for_test(1, layout, 1024, 1024, 0),
|
||||
DecommissionPoolCapacityInfo::for_test(2, layout, 1024, 1024, 0),
|
||||
]],
|
||||
);
|
||||
|
||||
let after = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::AfterNamespace);
|
||||
let conditional_store = Arc::clone(&store);
|
||||
let conditional_bucket = bucket.clone();
|
||||
let conditional = tokio::spawn(async move {
|
||||
conditional_store
|
||||
.put_object(
|
||||
&conditional_bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"conditional".to_vec()),
|
||||
&ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: seeded.etag,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
after.wait_until_paused().await;
|
||||
let before = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::BeforeNamespace);
|
||||
let ordinary_store = Arc::clone(&store);
|
||||
let ordinary_bucket = bucket.clone();
|
||||
let ordinary = tokio::spawn(async move {
|
||||
ordinary_store.pools[2]
|
||||
.put_object(
|
||||
&ordinary_bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"ordinary".to_vec()),
|
||||
&ObjectOptions {
|
||||
decommission_capacity_admission: Some(Arc::clone(&ordinary_store)),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
before.wait_until_paused().await;
|
||||
before.release_and_wait_until_namespace_pending().await;
|
||||
assert!(!before.namespace_acquired());
|
||||
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
store.save_current_pool_meta_for_decommission_start(&[0], Vec::new()),
|
||||
)
|
||||
.await
|
||||
.expect("an object-lock waiter must leave capacity available to activation")
|
||||
.expect("activate decommission of a separate source");
|
||||
drop(after);
|
||||
drop(before);
|
||||
conditional
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("publish under the active capacity reservation");
|
||||
let written = ordinary.await.unwrap().expect("publish the queued PUT");
|
||||
let visible = store
|
||||
.get_object_info(&bucket, object, &ObjectOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(visible.etag, written.etag);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn staged_external_put_rechecks_retiring_source_on_another_node() {
|
||||
|
||||
@@ -1584,11 +1584,12 @@ impl Sets {
|
||||
version_id: &str,
|
||||
opts: &HealOpts,
|
||||
proof: crate::set_disk::AbsenceProofRequest<'_>,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<(HealResultItem, Option<Error>, Option<crate::set_disk::HealedObjectAbsence>)> {
|
||||
let mut absence = None;
|
||||
let (item, error) = self
|
||||
.get_disks_for_heal_object(object, opts)?
|
||||
.heal_object_with_retirement(bucket, object, version_id, opts, &mut absence, proof)
|
||||
.heal_object_for_store(bucket, object, version_id, opts, &mut absence, proof, capacity_store)
|
||||
.await?;
|
||||
// A caller-owned lock does not expose its lease to this boundary.
|
||||
// Keep cleanup unverified when that lease cannot be checked here.
|
||||
|
||||
@@ -369,6 +369,14 @@ fn data_movement_user_defined(object_info: &ObjectInfo) -> HashMap<String, Strin
|
||||
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
|
||||
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
|
||||
insert_data_movement_checksum(&mut user_defined, object_info);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
if let Some(logical_rev) = object_info.logical_body_revision() {
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut user_defined,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
logical_rev.to_string(),
|
||||
);
|
||||
}
|
||||
if !object_info.user_tags.is_empty() {
|
||||
user_defined.insert(AMZ_OBJECT_TAGGING.to_string(), (*object_info.user_tags).clone());
|
||||
}
|
||||
@@ -995,6 +1003,24 @@ fn data_movement_publication_marker_valid(object_info: &ObjectInfo) -> bool {
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn data_movement_logical_body_revision_marker_presence(object_info: &ObjectInfo) -> Option<bool> {
|
||||
let mut found: Option<uuid::Uuid> = None;
|
||||
for (key, value) in object_info.user_defined.iter() {
|
||||
if !is_data_movement_internal_metadata(key, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX) {
|
||||
continue;
|
||||
}
|
||||
let parsed = uuid::Uuid::parse_str(value.trim()).ok().filter(|id| !id.is_nil())?;
|
||||
if found.is_some_and(|existing| existing != parsed) {
|
||||
return None;
|
||||
}
|
||||
found = Some(parsed);
|
||||
}
|
||||
if found.is_some() && object_info.data_dir.is_none_or(|dir| dir.is_nil()) {
|
||||
return None;
|
||||
}
|
||||
Some(found.is_some())
|
||||
}
|
||||
|
||||
fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, normalize_compression_size: bool) -> bool {
|
||||
[
|
||||
SUFFIX_DATA_MOVED,
|
||||
@@ -1006,6 +1032,7 @@ fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, norm
|
||||
// Inline placement is local to each physical copy, like its data directory.
|
||||
rustfs_utils::http::SUFFIX_INLINE_DATA,
|
||||
crate::object_api::ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
]
|
||||
.iter()
|
||||
.any(|suffix| is_data_movement_internal_metadata(key, suffix))
|
||||
@@ -1061,6 +1088,16 @@ pub(crate) fn is_equivalent_data_movement_metadata(
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let source_logical_rev_marker = data_movement_logical_body_revision_marker_presence(source);
|
||||
let target_logical_rev_marker = data_movement_logical_body_revision_marker_presence(target);
|
||||
if !is_compatible_data_movement_marker_presence(source_logical_rev_marker, target_logical_rev_marker) {
|
||||
return false;
|
||||
}
|
||||
if (source_logical_rev_marker == Some(true) || target_logical_rev_marker == Some(true))
|
||||
&& source.logical_body_revision() != target.logical_body_revision()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
source
|
||||
.user_defined
|
||||
@@ -1074,6 +1111,13 @@ pub(crate) fn is_equivalent_data_movement_metadata(
|
||||
.all(|(key, value)| source.user_defined.get(key) == Some(value))
|
||||
}
|
||||
|
||||
/// A listing can encounter either physical copy first. Migration verification
|
||||
/// itself remains directional so it still detects metadata lost on the target.
|
||||
pub(crate) fn equivalent_listed_object_versions(left: &ObjectInfo, right: &ObjectInfo) -> bool {
|
||||
is_equivalent_data_movement_object_identity(left, right, true, true)
|
||||
|| is_equivalent_data_movement_object_identity(right, left, true, true)
|
||||
}
|
||||
|
||||
pub(crate) fn is_equivalent_data_movement_object_identity(
|
||||
source: &ObjectInfo,
|
||||
target: &ObjectInfo,
|
||||
@@ -5223,4 +5267,75 @@ mod tests {
|
||||
|
||||
assert!(!result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_movement_preserves_logical_body_revision_across_hops_and_passes_equivalence() {
|
||||
let d1 = Uuid::from_u128(0x1111);
|
||||
let d2 = Uuid::from_u128(0x2222);
|
||||
let d3 = Uuid::from_u128(0x3333);
|
||||
let source = ObjectInfo {
|
||||
bucket: "vec-bucket".to_string(),
|
||||
name: "manifest.json".to_string(),
|
||||
size: 64,
|
||||
actual_size: 64,
|
||||
etag: Some("etag-1".to_string()),
|
||||
mod_time: Some(OffsetDateTime::UNIX_EPOCH),
|
||||
data_dir: Some(d1),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(source.logical_body_revision(), Some(d1));
|
||||
|
||||
let hop1 = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(data_movement_user_defined(&source)),
|
||||
..source.clone()
|
||||
};
|
||||
assert_eq!(hop1.logical_body_revision(), Some(d1));
|
||||
assert!(is_equivalent_data_movement_object(&source, &hop1));
|
||||
|
||||
let hop2 = ObjectInfo {
|
||||
data_dir: Some(d3),
|
||||
user_defined: Arc::new(data_movement_user_defined(&hop1)),
|
||||
..hop1.clone()
|
||||
};
|
||||
assert_eq!(hop2.logical_body_revision(), Some(d1));
|
||||
assert!(is_equivalent_data_movement_object(&hop1, &hop2));
|
||||
assert!(is_equivalent_data_movement_object(&source, &hop2));
|
||||
|
||||
// Dropping the marker after the object has already been migrated must fail equivalence.
|
||||
let dropped_marker = ObjectInfo {
|
||||
data_dir: Some(d3),
|
||||
user_defined: Arc::new(HashMap::new()),
|
||||
..hop1.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&hop1, &dropped_marker));
|
||||
|
||||
// Mismatched or malformed logical body revision markers must fail equivalence.
|
||||
let mut wrong_meta = data_movement_user_defined(&source);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut wrong_meta, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut wrong_meta,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
Uuid::from_u128(0x9999).to_string(),
|
||||
);
|
||||
let wrong_rev = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(wrong_meta),
|
||||
..source.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&source, &wrong_rev));
|
||||
|
||||
let mut malformed_meta = HashMap::new();
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut malformed_meta,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
"not-a-valid-uuid".to_string(),
|
||||
);
|
||||
let malformed = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(malformed_meta),
|
||||
..source.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&source, &malformed));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,9 @@ 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;
|
||||
mod snapshot_view;
|
||||
pub use scan_progress::load_bucket_scan_progress_for_admin;
|
||||
pub use snapshot_view::{AdminUsageSnapshot, load_admin_usage_snapshot};
|
||||
|
||||
use crate::storage_api_contracts::{
|
||||
bucket::{BucketOperations as _, BucketOptions},
|
||||
@@ -637,7 +639,7 @@ fn stale_data_usage_persist_reason_for_source(
|
||||
/// Store data usage info to backend storage
|
||||
#[instrument(skip(store))]
|
||||
pub async fn store_data_usage_in_backend(data_usage_info: DataUsageInfo, store: Arc<ECStore>) -> Result<(), Error> {
|
||||
reject_admin_usage_projection(&data_usage_info)?;
|
||||
reject_display_only_usage(&data_usage_info)?;
|
||||
if data_usage_info.usage_snapshot_converged == Some(false) {
|
||||
return Err(Error::other(
|
||||
"nonconverged data usage observations cannot replace the quota-authoritative snapshot",
|
||||
@@ -667,7 +669,7 @@ async fn save_data_usage_in_backend(
|
||||
store: Arc<ECStore>,
|
||||
expected_publication_epoch: u64,
|
||||
) -> Result<(), Error> {
|
||||
reject_admin_usage_projection(&data_usage_info)?;
|
||||
reject_display_only_usage(&data_usage_info)?;
|
||||
let data =
|
||||
serde_json::to_vec(&data_usage_info).map_err(|e| Error::other(format!("Failed to serialize data usage info: {e}")))?;
|
||||
|
||||
@@ -1282,14 +1284,17 @@ fn parse_usage_snapshot(buf: &[u8]) -> Result<DataUsageInfo, Error> {
|
||||
e.column()
|
||||
))
|
||||
})?;
|
||||
reject_admin_usage_projection(&info)?;
|
||||
reject_display_only_usage(&info)?;
|
||||
for usage in info.buckets_usage.values_mut() {
|
||||
usage.normalize_usage_provenance();
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn reject_admin_usage_projection(info: &DataUsageInfo) -> Result<(), Error> {
|
||||
fn reject_display_only_usage(info: &DataUsageInfo) -> Result<(), Error> {
|
||||
if info.usage_snapshot_certified_buckets.is_some() {
|
||||
return Err(Error::other("completed-bucket sidecar is not a namespace baseline"));
|
||||
}
|
||||
if info.usage_snapshot_admin_projection {
|
||||
return Err(Error::other("admin usage projections cannot be persisted or used as a storage baseline"));
|
||||
}
|
||||
@@ -2121,6 +2126,9 @@ impl BucketUsageAccumulator {
|
||||
}
|
||||
|
||||
pub fn quota_object_size(object: &ObjectInfo) -> Result<u64, Error> {
|
||||
if crate::bucket::metadata::is_vector_pagination_session(&object.bucket, &object.name) {
|
||||
return Ok(0);
|
||||
}
|
||||
// A compressed object may carry -1 while the transformed size is unknown
|
||||
// (legacy streaming sentinel). In that case the persisted physical size
|
||||
// is still a valid accounting floor; every other negative value is corrupt.
|
||||
@@ -2460,54 +2468,84 @@ pub async fn seed_bucket_usage_memory_for_test(bucket: &str, size: u64) {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A successful PUT's change to logical bucket usage.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PutUsageReceipt {
|
||||
had_live_version: bool,
|
||||
replaced: ReplacedVersion,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum ReplacedVersion {
|
||||
Absent,
|
||||
DeleteMarker,
|
||||
Data(u64),
|
||||
}
|
||||
|
||||
impl PutUsageReceipt {
|
||||
pub(crate) fn from_predecessors(had_live_version: bool, replaced: Option<&ObjectInfo>) -> Result<Self, Error> {
|
||||
let replaced = match replaced {
|
||||
None => ReplacedVersion::Absent,
|
||||
Some(info) if info.delete_marker => ReplacedVersion::DeleteMarker,
|
||||
Some(info) => ReplacedVersion::Data(quota_object_size(info)?),
|
||||
};
|
||||
Ok(Self {
|
||||
had_live_version,
|
||||
replaced,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn replaced_size(&self) -> u64 {
|
||||
match self.replaced {
|
||||
ReplacedVersion::Data(size) => size,
|
||||
ReplacedVersion::Absent | ReplacedVersion::DeleteMarker => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply this committed version change to the bucket's immediate usage counters.
|
||||
pub async fn record(self, bucket: &str, new_size: u64) {
|
||||
ensure_bucket_usage_cached(bucket).await;
|
||||
let mut cache = memory_cache().write().await;
|
||||
let entry = cache
|
||||
.entry(bucket.to_owned())
|
||||
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
|
||||
entry.usage.size = entry.usage.size.saturating_sub(self.replaced_size()).saturating_add(new_size);
|
||||
if !self.had_live_version {
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
}
|
||||
if !matches!(self.replaced, ReplacedVersion::Data(_)) {
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
}
|
||||
if self.replaced == ReplacedVersion::DeleteMarker {
|
||||
entry.usage.delete_markers_count = entry.usage.delete_markers_count.saturating_sub(1);
|
||||
}
|
||||
let now = SystemTime::now();
|
||||
entry.refreshed_at = now;
|
||||
entry.usage_updated_at = now;
|
||||
entry.dirty = true;
|
||||
entry.stale_snapshot_pending = false;
|
||||
entry.pending_scanner_position = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fast in-memory update for immediate quota and admin usage consistency.
|
||||
pub async fn record_bucket_object_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
|
||||
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, false).await;
|
||||
PutUsageReceipt {
|
||||
had_live_version: previous_current_size.is_some(),
|
||||
replaced: previous_current_size.map_or(ReplacedVersion::Absent, ReplacedVersion::Data),
|
||||
}
|
||||
.record(bucket, new_size)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Fast in-memory update for versioned object writes.
|
||||
pub async fn record_bucket_object_version_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
|
||||
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, true).await;
|
||||
}
|
||||
|
||||
async fn record_bucket_object_write_memory_inner(
|
||||
bucket: &str,
|
||||
previous_current_size: Option<u64>,
|
||||
new_size: u64,
|
||||
creates_new_version: bool,
|
||||
) {
|
||||
ensure_bucket_usage_cached(bucket).await;
|
||||
|
||||
let mut cache = memory_cache().write().await;
|
||||
let entry = cache
|
||||
.entry(bucket.to_string())
|
||||
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
|
||||
|
||||
if creates_new_version {
|
||||
entry.usage.size = entry.usage.size.saturating_add(new_size);
|
||||
if previous_current_size.is_none() {
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
}
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
} else {
|
||||
match previous_current_size {
|
||||
Some(previous_size) => {
|
||||
entry.usage.size = entry.usage.size.saturating_sub(previous_size).saturating_add(new_size);
|
||||
}
|
||||
None => {
|
||||
entry.usage.size = entry.usage.size.saturating_add(new_size);
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
PutUsageReceipt {
|
||||
had_live_version: previous_current_size.is_some(),
|
||||
replaced: ReplacedVersion::Absent,
|
||||
}
|
||||
|
||||
let now = SystemTime::now();
|
||||
entry.refreshed_at = now;
|
||||
entry.usage_updated_at = now;
|
||||
entry.dirty = true;
|
||||
entry.stale_snapshot_pending = false;
|
||||
entry.pending_scanner_position = None;
|
||||
.record(bucket, new_size)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Degraded in-memory update for an object write whose previous current size
|
||||
@@ -5790,6 +5828,26 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_exempt_sessions_require_the_vector_storage_bucket_and_session_key() {
|
||||
let table = uuid::Uuid::new_v4();
|
||||
let session = "b".repeat(64);
|
||||
let key = format!(".rustfs-table/{table}/query-results/{session}.session");
|
||||
let size = |bucket: &str, name: &str| {
|
||||
quota_object_size(&ObjectInfo {
|
||||
bucket: bucket.to_owned(),
|
||||
name: name.to_owned(),
|
||||
size: 17,
|
||||
..Default::default()
|
||||
})
|
||||
.expect("quota size")
|
||||
};
|
||||
assert_eq!(size("rustfs-v-abc", &key), 0);
|
||||
assert_eq!(size("general-bucket", &key), 17);
|
||||
assert_eq!(size("rustfs-v-abc", &key.replace("/query-results/", "/dataset/")), 17);
|
||||
assert_eq!(size("rustfs-v-abc", &key.replace(&session, "other")), 17);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_object_size_accepts_compressed_unknown_actual_size_sentinel() {
|
||||
let mut metadata = HashMap::new();
|
||||
@@ -7438,6 +7496,46 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn put_usage_charges_the_replaced_version_and_counts_markers_separately() {
|
||||
let bucket = "put-usage-versions";
|
||||
let baseline = BucketUsageInfo {
|
||||
objects_count: 1,
|
||||
versions_count: 2,
|
||||
size: 90,
|
||||
..Default::default()
|
||||
};
|
||||
let null = ObjectInfo {
|
||||
size: 20,
|
||||
actual_size: 20,
|
||||
..Default::default()
|
||||
};
|
||||
let marker = ObjectInfo {
|
||||
delete_marker: true,
|
||||
..Default::default()
|
||||
};
|
||||
for (mut initial, had_live, replaced, expected) in [
|
||||
(baseline.clone(), true, Some(&null), (100, 1, 2, 0)),
|
||||
(baseline.clone(), true, None, (120, 1, 3, 0)),
|
||||
(baseline, true, Some(&marker), (120, 1, 3, 0)),
|
||||
(BucketUsageInfo::default(), false, Some(&marker), (30, 1, 1, 0)),
|
||||
] {
|
||||
initial.delete_markers_count = u64::from(replaced.is_some_and(|version| version.delete_marker));
|
||||
clear_usage_memory_cache_for_test().await;
|
||||
replace_bucket_usage_memory_from_authoritative(bucket, initial, SystemTime::now()).await;
|
||||
let receipt = PutUsageReceipt::from_predecessors(had_live, replaced).expect("valid version sizes");
|
||||
receipt.record(bucket, 30).await;
|
||||
let cache = memory_cache().read().await;
|
||||
let usage = &cache[bucket].usage;
|
||||
assert_eq!(
|
||||
(usage.size, usage.objects_count, usage.versions_count, usage.delete_markers_count),
|
||||
expected
|
||||
);
|
||||
}
|
||||
clear_usage_memory_cache_for_test().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn authoritative_versioned_refresh_replaces_stale_dirty_memory() {
|
||||
|
||||
@@ -40,7 +40,19 @@ pub async fn load_bucket_scan_progress_for_admin(
|
||||
) -> 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))
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, false))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) async fn load_initial_bucket_scan_progress(
|
||||
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, true))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -50,6 +62,7 @@ async fn bucket_progress_sources(
|
||||
bucket: String,
|
||||
sets: Arc<Vec<Arc<SetDisks>>>,
|
||||
movement_generation: u64,
|
||||
initial_baseline: Option<&DataUsageInfo>,
|
||||
) -> BoxStream<'static, ProgressEvent> {
|
||||
let Some(incarnation) = store
|
||||
.bucket_incarnation_id_from_disk(&bucket)
|
||||
@@ -59,6 +72,19 @@ async fn bucket_progress_sources(
|
||||
else {
|
||||
return futures::stream::empty().boxed();
|
||||
};
|
||||
if initial_baseline.as_ref().is_some_and(|baseline| {
|
||||
baseline
|
||||
.usage_snapshot_noninitial_buckets
|
||||
.get(&bucket)
|
||||
.is_some_and(|previous| {
|
||||
uuid::Uuid::parse_str(previous)
|
||||
.ok()
|
||||
.is_none_or(|previous| previous.is_nil() || previous == incarnation)
|
||||
})
|
||||
|| !super::snapshot_view::initial_progress_allowed(baseline.buckets_usage.get(&bucket), incarnation)
|
||||
}) {
|
||||
return futures::stream::empty().boxed();
|
||||
}
|
||||
let incarnation = incarnation.to_string();
|
||||
let path = bucket_scan_progress_path(&bucket);
|
||||
futures::stream::iter(0..sets.len())
|
||||
@@ -124,6 +150,7 @@ async fn load_progress(
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
read_deadline: tokio::time::Instant,
|
||||
initial_only: bool,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let Some(epoch) = store.scanner_data_usage_publication_epoch().await else {
|
||||
return HashMap::new();
|
||||
@@ -145,8 +172,9 @@ async fn load_progress(
|
||||
}
|
||||
// Emit each validated source immediately. A bucket waiting for another
|
||||
// source must not hide its healthy sample behind a whole-bucket future.
|
||||
let initial_baseline = initial_only.then_some(baseline);
|
||||
let work = futures::stream::iter(buckets.iter().cloned())
|
||||
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
|
||||
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation, initial_baseline))
|
||||
.buffer_unordered(4)
|
||||
.flatten_unordered(4);
|
||||
let samples = collect_progress_until(read_deadline, work).await;
|
||||
@@ -206,6 +234,7 @@ mod tests {
|
||||
},
|
||||
objects: Some(objects),
|
||||
size: Some(objects * 11),
|
||||
blocker: None,
|
||||
};
|
||||
let partial: BoxStream<'static, ProgressEvent> = futures::stream::iter([
|
||||
futures::future::ready(("partial".into(), sample("partial", 0, 7, false))).boxed(),
|
||||
@@ -271,6 +300,7 @@ mod tests {
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(71),
|
||||
blocker: None,
|
||||
};
|
||||
(dirs, store, sample)
|
||||
}
|
||||
@@ -285,6 +315,171 @@ mod tests {
|
||||
.expect("persist display sample on its source set");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_snapshot_allows_initial_progress_but_preserves_complete_values() {
|
||||
let (_dirs, store, sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let mut baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(10)),
|
||||
scanner_epoch: Some(9),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
..Default::default()
|
||||
};
|
||||
let primary = "buckets/.usage.v2.json";
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("initial marker"))
|
||||
.await
|
||||
.expect("persist initial marker");
|
||||
let initial = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("initial view");
|
||||
assert!(initial.usage.buckets_usage.is_empty());
|
||||
assert_eq!(initial.initial_scan_progress["progress"].objects, Some(7));
|
||||
baseline.usage_snapshot_bootstrap_pending = false;
|
||||
baseline.usage_snapshot_complete = true;
|
||||
baseline.scanner_cycle = Some(10);
|
||||
let mut complete = BucketUsageInfo {
|
||||
size: 900,
|
||||
objects_count: 90,
|
||||
bucket_incarnation: Some(sample.bucket_incarnation.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
complete.certify(rustfs_data_usage::BucketUsageCertification {
|
||||
epoch: 9,
|
||||
cycle: 10,
|
||||
certified_at: baseline.last_update.expect("measurement time"),
|
||||
});
|
||||
baseline.buckets_usage.insert("progress".into(), complete);
|
||||
baseline.buckets_count = 1;
|
||||
baseline.calculate_totals();
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("complete snapshot"))
|
||||
.await
|
||||
.expect("persist complete snapshot");
|
||||
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("complete view");
|
||||
assert_eq!(view.usage.buckets_usage["progress"].objects_count, 90);
|
||||
assert!(view.initial_scan_progress.is_empty());
|
||||
baseline.usage_snapshot_bootstrap_pending = true;
|
||||
baseline.usage_snapshot_initial_bootstrap = false;
|
||||
baseline.usage_snapshot_complete = false;
|
||||
baseline.buckets_usage.clear();
|
||||
baseline.buckets_count = 0;
|
||||
baseline.calculate_totals();
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("recovery marker"))
|
||||
.await
|
||||
.expect("persist recovery marker");
|
||||
let recovered = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("recovery view");
|
||||
assert!(
|
||||
recovered.initial_scan_progress.is_empty(),
|
||||
"same incarnation does not become a first scan after recovery"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn noninitial_barrier_survives_a_missing_completed_bucket_sidecar() {
|
||||
let (_dirs, store, mut sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
scanner_epoch: Some(9),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_noninitial_buckets: HashMap::from([("progress".into(), sample.bucket_incarnation.clone())]),
|
||||
..Default::default()
|
||||
};
|
||||
save_config(
|
||||
store.clone(),
|
||||
"buckets/.usage.v2.json",
|
||||
serde_json::to_vec(&baseline).expect("history marker"),
|
||||
)
|
||||
.await
|
||||
.expect("persist history marker");
|
||||
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("bounded missing view");
|
||||
assert!(
|
||||
view.initial_scan_progress.is_empty(),
|
||||
"a lost sidecar cannot reopen initial-statistics fallback"
|
||||
);
|
||||
assert_eq!(view.unmeasured_buckets, ["progress"]);
|
||||
|
||||
// A freshly created incarnation with the same name has its own first scan.
|
||||
store
|
||||
.delete_bucket("progress", &Default::default())
|
||||
.await
|
||||
.expect("delete old bucket");
|
||||
store
|
||||
.make_bucket("progress", &Default::default())
|
||||
.await
|
||||
.expect("recreate bucket");
|
||||
let current = store
|
||||
.bucket_incarnation_id_from_disk("progress")
|
||||
.await
|
||||
.expect("new incarnation");
|
||||
assert_ne!(sample.bucket_incarnation, current.to_string());
|
||||
// Restore the historical marker to model a stale read after recreate.
|
||||
save_config(store.clone(), "buckets/.usage.v2.json", serde_json::to_vec(&baseline).unwrap())
|
||||
.await
|
||||
.expect("history of the previous incarnation");
|
||||
sample.bucket_incarnation = current.to_string();
|
||||
save(&store, &sample).await;
|
||||
let recreated = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("recreated view");
|
||||
assert!(recreated.usage.buckets_usage.is_empty());
|
||||
assert_eq!(recreated.initial_scan_progress["progress"].objects, Some(7));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_snapshot_never_returns_a_persisted_observed_row_as_completed_usage() {
|
||||
let (_dirs, store, sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let mut observed = BucketUsageInfo {
|
||||
objects_count: 90,
|
||||
size: 900,
|
||||
bucket_incarnation: Some(sample.bucket_incarnation),
|
||||
..Default::default()
|
||||
};
|
||||
observed.mark_observed();
|
||||
let mut baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
scanner_epoch: Some(9),
|
||||
scanner_cycle: Some(10),
|
||||
usage_snapshot_complete: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_pending_bucket_count: 1,
|
||||
usage_snapshot_pending_buckets: vec!["progress".into()],
|
||||
buckets_count: 1,
|
||||
buckets_usage: HashMap::from([("progress".into(), observed)]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(baseline.checked_calculate_totals());
|
||||
save_config(
|
||||
store.clone(),
|
||||
"buckets/.usage.v2.json",
|
||||
serde_json::to_vec(&baseline).expect("observed root"),
|
||||
)
|
||||
.await
|
||||
.expect("persist old pending root");
|
||||
let view = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("strict view");
|
||||
assert!(view.usage.buckets_usage.is_empty());
|
||||
assert_eq!(view.unmeasured_buckets, ["progress"]);
|
||||
assert!(
|
||||
view.initial_scan_progress.is_empty(),
|
||||
"filtering an old row must not reopen initial fallback"
|
||||
);
|
||||
}
|
||||
|
||||
#[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 {
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
use super::*;
|
||||
use rustfs_data_usage::BucketScanProgress;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// Response-only view of persisted usage. Initial progress is never inserted
|
||||
/// into the authoritative map or used by quota admission.
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct AdminUsageSnapshot {
|
||||
#[serde(flatten)]
|
||||
pub usage: DataUsageInfo,
|
||||
pub snapshot_view: bool,
|
||||
pub initial_scan_progress: HashMap<String, BucketScanProgress>,
|
||||
pub unmeasured_buckets: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) fn initial_progress_allowed(previous: Option<&BucketUsageInfo>, incarnation: uuid::Uuid) -> bool {
|
||||
if incarnation.is_nil() {
|
||||
return false;
|
||||
}
|
||||
match previous {
|
||||
None => true,
|
||||
Some(previous) => previous
|
||||
.bucket_incarnation
|
||||
.as_deref()
|
||||
.and_then(|value| uuid::Uuid::parse_str(value).ok())
|
||||
.filter(|previous| !previous.is_nil())
|
||||
.is_some_and(|previous| previous != incarnation),
|
||||
}
|
||||
}
|
||||
|
||||
fn initial_snapshot_available(raw: &DataUsageInfo, source: UsageSnapshotSource) -> bool {
|
||||
source == UsageSnapshotSource::Primary
|
||||
&& raw.usage_snapshot_initial_view_version == Some(1)
|
||||
&& if raw.usage_snapshot_bootstrap_pending {
|
||||
raw.usage_snapshot_initial_bootstrap && raw.has_usage_bootstrap_marker_shape()
|
||||
} else {
|
||||
raw.is_completed_usage_baseline()
|
||||
}
|
||||
}
|
||||
|
||||
/// Read complete persisted values before considering initial progress.
|
||||
///
|
||||
/// The caller supplies only authorized bucket names. Primary/backup failures
|
||||
/// propagate; a filtered or unreadable historical value is not a first scan.
|
||||
/// Progress reads are bounded and optional, and never trigger object listing.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the persisted snapshot's read or decode error when neither copy
|
||||
/// supplies a usable baseline.
|
||||
pub async fn load_admin_usage_snapshot(store: Arc<ECStore>, buckets: &[String]) -> Result<AdminUsageSnapshot, Error> {
|
||||
let (raw, source) = load_data_usage_snapshot(store.clone()).await?;
|
||||
let certified = if source.is_authoritative() && (raw.is_completed_usage_baseline() || raw.has_usage_bootstrap_marker_shape())
|
||||
{
|
||||
load_certified_buckets(store.clone(), &raw).await
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
let history_available = certified.is_ok();
|
||||
let certified = certified.ok().flatten();
|
||||
let measured_names = buckets
|
||||
.iter()
|
||||
.filter(|bucket| {
|
||||
raw.buckets_usage.contains_key(*bucket)
|
||||
|| certified
|
||||
.as_ref()
|
||||
.is_some_and(|info| info.buckets_usage.contains_key(*bucket))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
let incarnations = current_admin_bucket_incarnations(
|
||||
store.clone(),
|
||||
measured_names,
|
||||
tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
// Check initial eligibility on unfiltered durable history. A timed-out or
|
||||
// unauthorized identity must never turn an existing row into a first scan.
|
||||
let mut initial_scan_progress = if history_available && initial_snapshot_available(&raw, source) {
|
||||
scan_progress::load_initial_bucket_scan_progress(store, buckets, &raw).await
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
let usage = project_completed_bucket_usage(raw, source, certified, &incarnations, buckets)?;
|
||||
initial_scan_progress.retain(|bucket, _| !usage.buckets_usage.contains_key(bucket));
|
||||
let mut unmeasured_buckets = buckets
|
||||
.iter()
|
||||
.filter(|bucket| !usage.buckets_usage.contains_key(*bucket))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
unmeasured_buckets.sort();
|
||||
unmeasured_buckets.dedup();
|
||||
Ok(AdminUsageSnapshot {
|
||||
usage,
|
||||
snapshot_view: true,
|
||||
initial_scan_progress,
|
||||
unmeasured_buckets,
|
||||
})
|
||||
}
|
||||
|
||||
/// Only a canonical complete root can vouch for a legacy row without an
|
||||
/// explicit certificate. A sidecar can vouch for a bucket independently of
|
||||
/// namespace completeness. Neither path admits observations or a memory overlay.
|
||||
fn project_completed_bucket_usage(
|
||||
mut usage: DataUsageInfo,
|
||||
source: UsageSnapshotSource,
|
||||
certified: Option<DataUsageInfo>,
|
||||
incarnations: &HashMap<String, String>,
|
||||
buckets: &[String],
|
||||
) -> Result<DataUsageInfo, Error> {
|
||||
use rustfs_data_usage::BucketUsageValueState::{Carried, Certified};
|
||||
let complete_root = source.is_authoritative() && usage.is_completed_usage_baseline();
|
||||
if !complete_root && !(source.is_authoritative() && usage.has_usage_bootstrap_marker_shape()) {
|
||||
return Ok(DataUsageInfo::default());
|
||||
}
|
||||
let allowed: HashSet<_> = buckets.iter().map(String::as_str).collect();
|
||||
let original_count = usage.buckets_usage.len();
|
||||
usage.buckets_usage.retain(|bucket, value| {
|
||||
incarnations
|
||||
.get(bucket)
|
||||
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
|
||||
&& complete_root
|
||||
&& match value.usage_value_state {
|
||||
Some(Certified | Carried) => value.usage_certification.is_some(),
|
||||
None => true,
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
let mut changed = usage.buckets_usage.len() != original_count;
|
||||
if let Some(certified) = certified {
|
||||
for (bucket, value) in certified.buckets_usage {
|
||||
if !incarnations
|
||||
.get(&bucket)
|
||||
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(next) = value.usage_certification else { continue };
|
||||
let previous = usage.buckets_usage.get(&bucket).and_then(|value| value.usage_certification);
|
||||
if previous.is_none_or(|old| (next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)) {
|
||||
usage.buckets_usage.insert(bucket, value);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Observations and legacy size-only maps cannot prove complete values for
|
||||
// the current incarnation. Never pass this derived view to quota admission.
|
||||
let pending_count = usage.usage_snapshot_pending_buckets.len();
|
||||
usage
|
||||
.usage_snapshot_pending_buckets
|
||||
.retain(|bucket| allowed.contains(bucket.as_str()));
|
||||
usage.usage_snapshot_pending_bucket_count =
|
||||
u64::try_from(usage.usage_snapshot_pending_buckets.len()).map_err(Error::other)?;
|
||||
changed |= pending_count != usage.usage_snapshot_pending_buckets.len()
|
||||
|| usage
|
||||
.bucket_sizes
|
||||
.keys()
|
||||
.any(|bucket| !usage.buckets_usage.contains_key(bucket))
|
||||
|| usage
|
||||
.usage_snapshot_bucket_observations
|
||||
.keys()
|
||||
.any(|bucket| !allowed.contains(bucket.as_str()));
|
||||
usage
|
||||
.usage_snapshot_noninitial_buckets
|
||||
.retain(|bucket, _| allowed.contains(bucket.as_str()));
|
||||
usage.usage_snapshot_bucket_observations.clear();
|
||||
refresh_completed_snapshot_totals(&mut usage, changed)?;
|
||||
Ok(usage)
|
||||
}
|
||||
|
||||
fn refresh_completed_snapshot_totals(usage: &mut DataUsageInfo, changed: bool) -> Result<(), Error> {
|
||||
if !usage.checked_calculate_totals() {
|
||||
return Err(Error::other("completed snapshot totals overflow"));
|
||||
}
|
||||
usage.buckets_count = u64::try_from(usage.buckets_usage.len()).map_err(Error::other)?;
|
||||
usage.bucket_sizes = usage
|
||||
.buckets_usage
|
||||
.iter()
|
||||
.map(|(name, bucket)| (name.clone(), bucket.size))
|
||||
.collect();
|
||||
if !changed {
|
||||
return Ok(());
|
||||
}
|
||||
usage.usage_snapshot_complete = false;
|
||||
usage.usage_snapshot_partial = true;
|
||||
usage.usage_snapshot_admin_projection = true;
|
||||
usage.usage_snapshot_converged = Some(false);
|
||||
usage.replication_info.clear();
|
||||
usage.tier_stats = None;
|
||||
usage.unknown_tier_stats = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_certified_buckets(store: Arc<ECStore>, baseline: &DataUsageInfo) -> Result<Option<DataUsageInfo>, Error> {
|
||||
let path = format!("buckets/{}", rustfs_data_usage::DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME);
|
||||
let bytes = match read_config_preserve_empty(store.clone(), &path).await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(Error::ConfigNotFound) => return Ok(None),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let info: DataUsageInfo = serde_json::from_slice(&bytes).map_err(|_| Error::other("invalid completed-bucket snapshot"))?;
|
||||
if !info.is_certified_buckets_snapshot() {
|
||||
return Err(Error::other("unsupported completed-bucket snapshot"));
|
||||
}
|
||||
if !info.certified_buckets_match_baseline(baseline) {
|
||||
return Ok(None);
|
||||
}
|
||||
let scope = info
|
||||
.usage_snapshot_certified_buckets
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::other("missing completed-bucket scope"))?;
|
||||
let movement = store.scanner_durable_data_movement_generation().await;
|
||||
if movement != Some(scope.movement_generation) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut sources = Vec::new();
|
||||
for set in store.all_set_disks() {
|
||||
let Some(disks) = set.format.erasure.sets.get(set.set_index) else { return Ok(None) };
|
||||
if set.format.id.is_nil() || disks.is_empty() || disks.iter().any(uuid::Uuid::is_nil) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(set.format.id.as_bytes());
|
||||
for disk in disks {
|
||||
digest.update(disk.as_bytes());
|
||||
}
|
||||
sources.push(rustfs_data_usage::CertifiedBucketsSource {
|
||||
pool_index: u64::try_from(set.pool_index).map_err(Error::other)?,
|
||||
set_index: u64::try_from(set.set_index).map_err(Error::other)?,
|
||||
layout: digest.finalize().into(),
|
||||
});
|
||||
}
|
||||
sources.sort_by_key(|source| (source.pool_index, source.set_index));
|
||||
if sources != scope.sources || store.scanner_durable_data_movement_generation().await != movement {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(info))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_projection_recalculates_all_totals_without_refreshing_time() {
|
||||
let measured_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
|
||||
let mut usage = DataUsageInfo {
|
||||
last_update: Some(measured_at),
|
||||
usage_snapshot_complete: true,
|
||||
buckets_usage: HashMap::from([
|
||||
(
|
||||
"old".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 2,
|
||||
size: 20,
|
||||
versions_count: 4,
|
||||
delete_markers_count: 1,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"small".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 3,
|
||||
size: 30,
|
||||
versions_count: 5,
|
||||
delete_markers_count: 2,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
refresh_completed_snapshot_totals(&mut usage, true).expect("valid complete buckets");
|
||||
assert_eq!(
|
||||
(
|
||||
usage.buckets_count,
|
||||
usage.objects_total_count,
|
||||
usage.objects_total_size,
|
||||
usage.versions_total_count,
|
||||
usage.delete_markers_total_count
|
||||
),
|
||||
(2, 5, 50, 9, 3)
|
||||
);
|
||||
assert_eq!(usage.bucket_sizes, HashMap::from([("old".into(), 20), ("small".into(), 30)]));
|
||||
assert_eq!(usage.last_update, Some(measured_at));
|
||||
assert!(!usage.usage_snapshot_complete);
|
||||
assert!(usage.usage_snapshot_admin_projection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_row_requires_a_healthy_persisted_namespace_baseline() {
|
||||
let time = SystemTime::UNIX_EPOCH;
|
||||
let id = uuid::Uuid::from_u128(1).to_string();
|
||||
let mut row = BucketUsageInfo {
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
size: 100,
|
||||
..Default::default()
|
||||
};
|
||||
row.certify(rustfs_data_usage::BucketUsageCertification {
|
||||
epoch: 0,
|
||||
cycle: 0,
|
||||
certified_at: time,
|
||||
});
|
||||
let raw = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_complete: true,
|
||||
buckets_usage: HashMap::from([("measured".into(), row)]),
|
||||
buckets_count: 1,
|
||||
objects_total_size: 100,
|
||||
..Default::default()
|
||||
};
|
||||
let current = HashMap::from([("measured".into(), id)]);
|
||||
for source in [UsageSnapshotSource::Primary, UsageSnapshotSource::Backup] {
|
||||
assert_eq!(
|
||||
project_completed_bucket_usage(raw.clone(), source, None, ¤t, &["measured".into()])
|
||||
.unwrap()
|
||||
.objects_total_size,
|
||||
100
|
||||
);
|
||||
}
|
||||
for invalid in [
|
||||
DataUsageInfo {
|
||||
usage_snapshot_complete: false,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_partial: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_observational: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_admin_projection: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
..raw.clone()
|
||||
},
|
||||
] {
|
||||
assert!(!initial_snapshot_available(&invalid, UsageSnapshotSource::Primary));
|
||||
let view =
|
||||
project_completed_bucket_usage(invalid, UsageSnapshotSource::Primary, None, ¤t, &["measured".into()])
|
||||
.unwrap();
|
||||
assert!(view.buckets_usage.is_empty());
|
||||
assert_eq!(view.objects_total_size, 0);
|
||||
}
|
||||
let legacy =
|
||||
project_completed_bucket_usage(raw, UsageSnapshotSource::LegacyPrimary, None, ¤t, &["measured".into()])
|
||||
.unwrap();
|
||||
assert!(legacy.buckets_usage.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_projection_rejects_counter_overflow() {
|
||||
let mut usage = DataUsageInfo {
|
||||
buckets_usage: HashMap::from([
|
||||
(
|
||||
"old".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: u64::MAX,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"small".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 1,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(refresh_completed_snapshot_totals(&mut usage, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_and_recovery_cannot_turn_missing_history_into_first_statistics() {
|
||||
let mut raw = DataUsageInfo {
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
|
||||
raw.usage_snapshot_initial_bootstrap = true;
|
||||
raw.usage_snapshot_initial_view_version = Some(1);
|
||||
assert!(initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
|
||||
for source in [
|
||||
UsageSnapshotSource::Backup,
|
||||
UsageSnapshotSource::LegacyPrimary,
|
||||
UsageSnapshotSource::LegacyBackup,
|
||||
UsageSnapshotSource::Missing,
|
||||
] {
|
||||
assert!(!initial_snapshot_available(&raw, source));
|
||||
}
|
||||
assert!(!initial_snapshot_available(&DataUsageInfo::default(), UsageSnapshotSource::Primary));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_progress_requires_absence_in_the_unfiltered_current_incarnation() {
|
||||
let incarnation = uuid::Uuid::from_u128(1);
|
||||
assert!(initial_progress_allowed(None, incarnation));
|
||||
let mut previous = BucketUsageInfo {
|
||||
bucket_incarnation: Some(incarnation.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
// Filtering this value, a new reader, or a leader handoff cannot make
|
||||
// the same persisted bucket a first scan again.
|
||||
previous.bucket_incarnation = None;
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some("invalid".into());
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some(uuid::Uuid::nil().to_string());
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some(uuid::Uuid::from_u128(2).to_string());
|
||||
assert!(initial_progress_allowed(Some(&previous), incarnation));
|
||||
assert!(!initial_progress_allowed(None, uuid::Uuid::nil()));
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
|
||||
let mut accidental_quota = HashMap::new();
|
||||
backfill_degraded_baseline_from_observed(&mut accidental_quota, &snapshot);
|
||||
assert!(accidental_quota.is_empty());
|
||||
assert!(reject_admin_usage_projection(&snapshot).is_err());
|
||||
assert!(reject_display_only_usage(&snapshot).is_err());
|
||||
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
|
||||
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
|
||||
assert_eq!(
|
||||
@@ -378,7 +378,7 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
|
||||
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!(reject_display_only_usage(&second).is_err());
|
||||
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
|
||||
assert_eq!(
|
||||
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
|
||||
|
||||
@@ -797,6 +797,8 @@ fn get_drive_timeout_health_policy() -> TimeoutHealthPolicy {
|
||||
pub struct DiskHealthTracker {
|
||||
/// Atomic timestamp of last successful operation
|
||||
pub last_success: AtomicI64,
|
||||
/// Monotonic count of operations that completed successfully on this handle
|
||||
pub completed_ops: AtomicU64,
|
||||
/// Atomic timestamp of last operation start
|
||||
pub last_started: AtomicI64,
|
||||
/// Atomic disk status (OK or Faulty)
|
||||
@@ -1239,6 +1241,7 @@ impl DiskHealthTracker {
|
||||
|
||||
Self {
|
||||
last_success: AtomicI64::new(now_nanos),
|
||||
completed_ops: AtomicU64::new(0),
|
||||
last_started: AtomicI64::new(now_nanos),
|
||||
status: AtomicU32::new(DISK_HEALTH_OK),
|
||||
waiting: AtomicU32::new(0),
|
||||
@@ -1261,6 +1264,11 @@ impl DiskHealthTracker {
|
||||
/// Log a successful operation
|
||||
pub fn log_success(&self) {
|
||||
self.last_success.store(current_unix_nanos(), Ordering::Relaxed);
|
||||
self.completed_ops.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
pub fn completed_ops(&self) -> u64 {
|
||||
self.completed_ops.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn record_capacity_probe(&self, total: u64, used: u64, free: u64) {
|
||||
@@ -1398,6 +1406,22 @@ impl DiskHealthTracker {
|
||||
became_offline
|
||||
}
|
||||
|
||||
/// Record a foreground timeout failure only when no sibling operation on this drive
|
||||
/// succeeded while the timed-out operation was in flight. Under heavy queue contention,
|
||||
/// tail-latency timeouts occur while the drive is actively completing other operations;
|
||||
/// marking such a drive `Suspect`/`Offline` cascades into synthetic write-quorum 503s.
|
||||
pub fn mark_failure_unless_progressed(
|
||||
&self,
|
||||
endpoint: &Endpoint,
|
||||
reason: &'static str,
|
||||
completed_before: u64,
|
||||
) -> Option<bool> {
|
||||
if self.completed_ops() > completed_before {
|
||||
return None;
|
||||
}
|
||||
Some(self.mark_failure(endpoint, reason))
|
||||
}
|
||||
|
||||
#[allow(dead_code, reason = "asserted by this file's tests (backlog#1823)")]
|
||||
pub fn mark_offline(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
|
||||
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
@@ -1430,6 +1454,7 @@ impl DiskHealthTracker {
|
||||
self.consecutive_successes.store(0, Ordering::Release);
|
||||
self.offline_since_unix_secs.store(0, Ordering::Release);
|
||||
self.waiting.store(0, Ordering::Release);
|
||||
self.completed_ops.store(0, Ordering::Release);
|
||||
self.last_success.store(now_nanos, Ordering::Relaxed);
|
||||
self.last_started.store(now_nanos, Ordering::Relaxed);
|
||||
self.last_transition_unix_secs.store(now_secs, Ordering::Release);
|
||||
@@ -1472,6 +1497,23 @@ impl DiskHealthTracker {
|
||||
became_online
|
||||
}
|
||||
|
||||
/// Promote an offline/returning/suspect drive directly to `Online` once an authenticated peer
|
||||
/// restart (`boot_epoch` change) or quorum-critical recovery probe succeeds, avoiding a multi-second
|
||||
/// `Returning` stall during rolling upgrades and rollbacks.
|
||||
pub fn mark_peer_restarted_online(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
|
||||
#[cfg(test)]
|
||||
if self.test_forced_offline.load(Ordering::Acquire) {
|
||||
return false;
|
||||
}
|
||||
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let current = self.runtime_state();
|
||||
self.consecutive_failures.store(0, Ordering::Release);
|
||||
self.consecutive_successes.store(0, Ordering::Release);
|
||||
self.transition_state(endpoint, current, RuntimeDriveHealthState::Online, reason);
|
||||
self.log_success();
|
||||
true
|
||||
}
|
||||
|
||||
pub fn record_operation_success(&self, endpoint: &Endpoint, reason: &'static str) {
|
||||
if self.runtime_state() == RuntimeDriveHealthState::Online {
|
||||
self.log_success();
|
||||
@@ -1884,6 +1926,38 @@ impl LocalDiskWrapper {
|
||||
.map_err(DiskError::Io)
|
||||
}
|
||||
|
||||
pub(crate) async fn advance_background_delete_discovery(
|
||||
&self,
|
||||
volume: String,
|
||||
session: Option<super::local::DiscoverySession>,
|
||||
limit: u32,
|
||||
cancel: CancellationToken,
|
||||
) -> Result<(Vec<super::DeleteTransactionId>, Option<super::local::DiscoverySession>)> {
|
||||
self.check_scanner_handle()?;
|
||||
let retired = self.retirement_token();
|
||||
// A queued bucket lease must not occupy the only background disk slot.
|
||||
let lease = self.disk.lock_delete_discovery_bucket(&volume).await?;
|
||||
let disk = Arc::clone(&self.disk);
|
||||
super::with_background_disk_io(
|
||||
cancel.clone(),
|
||||
self.track_disk_health_with_op_timeout_action_and_mutation_with_io_permit(
|
||||
"discover_delete_transactions",
|
||||
|permit| async move {
|
||||
super::io_admission::spawn_blocking_with_disk_io_permit(permit, move || {
|
||||
let _lease = lease;
|
||||
disk.advance_background_delete_discovery(&volume, session, limit, &cancel, &retired)
|
||||
})
|
||||
.await
|
||||
.map_err(DiskError::other)?
|
||||
},
|
||||
Duration::ZERO,
|
||||
TimeoutHealthAction::IgnoreFailure,
|
||||
DiskMetricMutation::None,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
|
||||
self.disk.get_object_path(volume, path)
|
||||
}
|
||||
@@ -2482,17 +2556,22 @@ impl LocalDiskWrapper {
|
||||
&& self.disk.has_clean_active_multipart_source(upload_or_part_path, part_path)
|
||||
}
|
||||
|
||||
pub(crate) fn has_active_multipart_source_matching(
|
||||
pub(crate) fn check_active_multipart_source_matching_and_clean_part(
|
||||
&self,
|
||||
upload_path: &str,
|
||||
expected_data_dir: Option<uuid::Uuid>,
|
||||
expected_mod_time: Option<::time::OffsetDateTime>,
|
||||
) -> bool {
|
||||
!self.health.is_faulty()
|
||||
&& !self.retired.is_cancelled()
|
||||
&& self
|
||||
.disk
|
||||
.has_active_multipart_source_matching(upload_path, expected_data_dir, expected_mod_time)
|
||||
part_number: usize,
|
||||
) -> (bool, bool) {
|
||||
if self.health.is_faulty() || self.retired.is_cancelled() {
|
||||
return (false, false);
|
||||
}
|
||||
self.disk.check_active_multipart_source_matching_and_clean_part(
|
||||
upload_path,
|
||||
expected_data_dir,
|
||||
expected_mod_time,
|
||||
part_number,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn try_publish_prepared_delete_local(
|
||||
@@ -2758,6 +2837,7 @@ impl LocalDiskWrapper {
|
||||
.expect("test timeout lock")
|
||||
.map_or(timeout_duration, |injected| timeout_duration.min(injected));
|
||||
// Execute the operation with timeout
|
||||
let completed_before = self.health.completed_ops();
|
||||
let result = tokio::time::timeout(timeout_duration, operation).await;
|
||||
|
||||
match result {
|
||||
@@ -2775,9 +2855,13 @@ impl LocalDiskWrapper {
|
||||
Err(_) => {
|
||||
self.metrics.record_operation_latency(op, started.elapsed());
|
||||
self.metrics.record_timeout_error();
|
||||
// Timeout occurred, mark disk as potentially faulty.
|
||||
// Timeout occurred; mark disk as potentially faulty only if no sibling I/O
|
||||
// completed while this operation was waiting.
|
||||
if timeout_health_action == TimeoutHealthAction::MarkFailure
|
||||
&& self.health.mark_failure(&self.endpoint(), "operation_timeout")
|
||||
&& self
|
||||
.health
|
||||
.mark_failure_unless_progressed(&self.endpoint(), "operation_timeout", completed_before)
|
||||
== Some(true)
|
||||
{
|
||||
self.spawn_recovery_monitor_if_needed();
|
||||
}
|
||||
@@ -6868,6 +6952,36 @@ mod tests {
|
||||
assert_eq!(wrapper.runtime_state(), RuntimeDriveHealthState::Suspect);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_progress_prevents_false_faulty_on_queue_timeout() {
|
||||
let endpoint = Endpoint::try_from("/tmp/concurrent-progress-disk").expect("endpoint should parse");
|
||||
let health = DiskHealthTracker::new();
|
||||
let before = health.completed_ops();
|
||||
|
||||
// Sibling operation completes while a queued operation is waiting.
|
||||
health.record_operation_success(&endpoint, "operation_success");
|
||||
assert!(health.completed_ops() > before);
|
||||
|
||||
// Timed-out straggler from the earlier batch must not degrade or fault the active drive.
|
||||
assert_eq!(health.mark_failure_unless_progressed(&endpoint, "operation_timeout", before), None);
|
||||
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Online);
|
||||
assert!(!health.is_faulty());
|
||||
|
||||
// When no sibling operation completes after `stalled_before`, timeouts degrade normally.
|
||||
let stalled_before = health.completed_ops();
|
||||
assert_eq!(
|
||||
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Suspect);
|
||||
assert_eq!(
|
||||
health.mark_failure_unless_progressed(&endpoint, "operation_timeout", stalled_before),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(health.runtime_state(), RuntimeDriveHealthState::Offline);
|
||||
assert!(health.is_faulty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn drive_timeout_health_policy_defaults_to_mark_failure() {
|
||||
|
||||
@@ -62,14 +62,15 @@ use crate::disk::{
|
||||
DeleteOptions, DeleteRecoveryAction, DeleteRecoveryCursor, DeleteRecoveryDigest, DeleteRecoveryInspection,
|
||||
DeleteRecoveryJournal, DeleteRecoveryPage, DeleteRecoverySettlementOutcome, DeleteRecoveryState,
|
||||
DeleteRecoveryVersionIdentity, DeleteTransactionId, Disk, DiskAPI, DiskInfo, DiskInfoOptions, DiskLocation, DiskStore,
|
||||
FORMAT_CONFIG_FILE, FileInfoVersions, FileReader, FileWriter, GuardedFileInfoVersions, OldCurrentSize, RUSTFS_META_BUCKET,
|
||||
FORMAT_CONFIG_FILE, FileInfoVersions, FileReader, FileWriter, GuardedFileInfoVersions, OldCurrentSize,
|
||||
PART_TRANSACTION_NEW_META, PART_TRANSACTION_OLD_META, PART_TRANSACTION_ROLLBACK, PartTransactionAction, RUSTFS_META_BUCKET,
|
||||
RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET, ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp,
|
||||
STORAGE_FORMAT_FILE, STORAGE_FORMAT_FILE_BACKUP, ScanGuard, UpdateMetadataOpts, VolumeInfo, WalkDirOptions,
|
||||
conv_part_err_to_int,
|
||||
endpoint::Endpoint,
|
||||
error::{DiskError, Error, Result},
|
||||
format::FormatV3,
|
||||
validate_delete_recovery_options, validate_format_control_path,
|
||||
part_transaction_path, validate_delete_recovery_options, validate_format_control_path,
|
||||
};
|
||||
use crate::erasure::coding::{self, bitrot_verify};
|
||||
use crate::runtime::instance::InstanceContext;
|
||||
@@ -226,6 +227,7 @@ pub struct DstSimDisk {
|
||||
delete_tx_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
cas_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
configured_capacity: Arc<RwLock<Option<u64>>>,
|
||||
multipart_proof_authority: Arc<RwLock<Option<crate::disk::multipart_source::ProofVerificationContext>>>,
|
||||
}
|
||||
|
||||
impl Debug for DstSimDisk {
|
||||
@@ -280,9 +282,19 @@ impl DstSimDisk {
|
||||
delete_tx_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
cas_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
configured_capacity: Arc::new(RwLock::new(None)),
|
||||
multipart_proof_authority: Arc::new(RwLock::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bind_multipart_proof_authority(
|
||||
&self,
|
||||
authority: &crate::disk::multipart_source::ProofVerificationContext,
|
||||
) -> Result<()> {
|
||||
let mut guard = self.multipart_proof_authority.write().unwrap_or_else(|p| p.into_inner());
|
||||
*guard = Some(authority.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn sim(&self) -> &SimDiskIo {
|
||||
&self.sim
|
||||
}
|
||||
@@ -1472,12 +1484,22 @@ impl DiskAPI for DstSimDisk {
|
||||
self.sim.create_dir_all(&src_dir).await.map_err(map_sim_err)?;
|
||||
self.sim.create_dir_all(&dst_dir).await.map_err(map_sim_err)?;
|
||||
|
||||
let has_external_parts = !file_info.inline_data() && file_info.data.is_none() && file_info.size > 0;
|
||||
let multipart_pub_identity = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
|
||||
crate::disk::multipart_source::publication_identity(&file_info)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let has_external_parts =
|
||||
!file_info.inline_data() && file_info.data.as_ref().is_none_or(|d| d.is_empty()) && file_info.size > 0;
|
||||
if has_external_parts
|
||||
&& let Some(data_dir) = file_info.data_dir
|
||||
&& !data_dir.is_nil()
|
||||
{
|
||||
let src_data = format!("{src_dir}/{data_dir}");
|
||||
let src_data_dir = multipart_pub_identity
|
||||
.as_ref()
|
||||
.map(|p| p.lineage.original_data_dir)
|
||||
.unwrap_or(data_dir);
|
||||
let src_data = format!("{src_dir}/{src_data_dir}");
|
||||
let dst_data = format!("{dst_dir}/{data_dir}");
|
||||
if self.sim.stat(&src_data).await.is_ok() {
|
||||
let staged_parts = self.sim.list_dir(&src_data).await.map_err(map_sim_err)?;
|
||||
@@ -1519,13 +1541,62 @@ impl DiskAPI for DstSimDisk {
|
||||
|
||||
self.fsync_parent_chain(&dst_dir).await?;
|
||||
let _ = self.sim.remove_file(&bkp_meta).await;
|
||||
let _ = self.sim.remove_dir_all(&src_dir).await;
|
||||
if src_volume == RUSTFS_META_TMP_BUCKET {
|
||||
let _ = self.sim.remove_dir_all(&src_dir).await;
|
||||
}
|
||||
|
||||
let multipart_source = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
|
||||
let publication = crate::disk::multipart_source::publication_identity(&file_info)?;
|
||||
let authority = self
|
||||
.multipart_proof_authority
|
||||
.read()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.clone();
|
||||
if let (Some(publication), Some(authority)) = (publication, authority) {
|
||||
let disk_id = self
|
||||
.disk_id
|
||||
.read()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.ok_or(DiskError::InconsistentDisk)?;
|
||||
let undo_capability = crate::disk::multipart_source::MultipartUndoCapability::new();
|
||||
let snapshot = crate::disk::multipart_source::MultipartSourceSnapshot {
|
||||
disk_id,
|
||||
physical_slot: self.disk_idx,
|
||||
lineage: publication.lineage.clone(),
|
||||
generation: publication.source_generation,
|
||||
revision: 1,
|
||||
phase: crate::disk::multipart_source::MultipartSourcePhase::ConsumedUnsealed,
|
||||
state_sha256: [0; 32],
|
||||
head_sha256: None,
|
||||
inventory_sha256: [0; 32],
|
||||
capability_sha256: Some(undo_capability.digest()),
|
||||
publication: Some(publication.clone()),
|
||||
};
|
||||
let proof = crate::disk::multipart_source::MultipartSourceProof::issue(
|
||||
&authority,
|
||||
crate::disk::multipart_source::MultipartProofKind::Published,
|
||||
Uuid::new_v4(),
|
||||
None,
|
||||
snapshot,
|
||||
)?;
|
||||
Some(Box::new(crate::disk::multipart_source::MultipartPublicationResult {
|
||||
publication,
|
||||
proof,
|
||||
undo_capability,
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(RenameDataResp {
|
||||
old_data_dir: has_old_data_dir,
|
||||
cleanup_data_dir: has_old_data_dir,
|
||||
old_current_size,
|
||||
old_current_source_checked: true,
|
||||
multipart_source,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
@@ -1632,20 +1703,149 @@ impl DiskAPI for DstSimDisk {
|
||||
self.fsync_parent_chain(dst_parent).await
|
||||
}
|
||||
|
||||
async fn prepare_part_transaction(
|
||||
&self,
|
||||
src_volume: &str,
|
||||
src_path: &str,
|
||||
dst_volume: &str,
|
||||
dst_path: &str,
|
||||
meta: Bytes,
|
||||
) -> Result<()> {
|
||||
self.ensure_online()?;
|
||||
let part = ObjectPartInfo::unmarshal(&meta)?;
|
||||
let src = join_vol_path(src_volume, src_path)?;
|
||||
let dst = join_vol_path(dst_volume, dst_path)?;
|
||||
let dst_meta = format!("{dst}.meta");
|
||||
let txn_dir = join_vol_path(dst_volume, &part_transaction_path(dst_path))?;
|
||||
self.sim.create_dir_all(&txn_dir).await.map_err(map_sim_err)?;
|
||||
|
||||
// Snapshot existing committed data/meta (or record explicit absence markers)
|
||||
match self.sim.read_file(&dst).await {
|
||||
Ok(old_data) => {
|
||||
self.write_durable_file(&format!("{txn_dir}/old.data"), old_data).await?;
|
||||
}
|
||||
Err(SimErr::NotFound(_)) => {
|
||||
self.write_durable_file(&format!("{txn_dir}/old.data.absent"), Bytes::new())
|
||||
.await?;
|
||||
}
|
||||
Err(e) => return Err(map_sim_err(e)),
|
||||
}
|
||||
match self.sim.read_file(&dst_meta).await {
|
||||
Ok(old_meta) => {
|
||||
self.write_durable_file(&format!("{txn_dir}/{PART_TRANSACTION_OLD_META}"), old_meta)
|
||||
.await?;
|
||||
}
|
||||
Err(SimErr::NotFound(_)) => {
|
||||
self.write_durable_file(&format!("{txn_dir}/old.meta.absent"), Bytes::new())
|
||||
.await?;
|
||||
}
|
||||
Err(e) => return Err(map_sim_err(e)),
|
||||
}
|
||||
|
||||
// Stage incoming part payload (and optional shard integrity proof) inside txn_dir
|
||||
let new_data = self.sim.read_file(&src).await.map_err(map_sim_err)?;
|
||||
self.write_durable_file(&format!("{txn_dir}/new.data"), new_data).await?;
|
||||
if let Some(integrity) = part.integrity {
|
||||
let proof_name = integrity.file_name();
|
||||
let src_parent = src.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
|
||||
let src_proof = if src_parent.is_empty() {
|
||||
proof_name.clone()
|
||||
} else {
|
||||
format!("{src_parent}/{proof_name}")
|
||||
};
|
||||
if let Ok(proof_bytes) = self.sim.read_file(&src_proof).await {
|
||||
self.write_durable_file(&format!("{txn_dir}/{proof_name}"), proof_bytes)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
self.write_durable_file(&format!("{txn_dir}/{PART_TRANSACTION_NEW_META}"), meta)
|
||||
.await?;
|
||||
self.fsync_parent_chain(&txn_dir).await
|
||||
}
|
||||
|
||||
async fn rename_part(&self, src_volume: &str, src_path: &str, dst_volume: &str, dst_path: &str, meta: Bytes) -> Result<()> {
|
||||
self.ensure_online()?;
|
||||
let part = ObjectPartInfo::unmarshal(&meta).ok();
|
||||
let src = join_vol_path(src_volume, src_path)?;
|
||||
let dst = join_vol_path(dst_volume, dst_path)?;
|
||||
let dst_parent = dst.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
|
||||
if !dst_parent.is_empty() {
|
||||
self.sim.create_dir_all(dst_parent).await.map_err(map_sim_err)?;
|
||||
}
|
||||
self.sim.fsync_file(&src).await.map_err(map_sim_err)?;
|
||||
self.sim.rename(&src, &dst).await.map_err(map_sim_err)?;
|
||||
let txn_dir = join_vol_path(dst_volume, &part_transaction_path(dst_path))?;
|
||||
let prepared_data = format!("{txn_dir}/new.data");
|
||||
if self.sim.stat(&prepared_data).await.is_ok() {
|
||||
self.sim.fsync_file(&prepared_data).await.map_err(map_sim_err)?;
|
||||
self.sim.rename(&prepared_data, &dst).await.map_err(map_sim_err)?;
|
||||
let _ = self.sim.remove_file(&src).await;
|
||||
} else {
|
||||
self.sim.fsync_file(&src).await.map_err(map_sim_err)?;
|
||||
self.sim.rename(&src, &dst).await.map_err(map_sim_err)?;
|
||||
}
|
||||
if let Some(integrity) = part.and_then(|p| p.integrity) {
|
||||
let proof_name = integrity.file_name();
|
||||
let dst_proof = if dst_parent.is_empty() {
|
||||
proof_name.clone()
|
||||
} else {
|
||||
format!("{dst_parent}/{proof_name}")
|
||||
};
|
||||
let txn_proof = format!("{txn_dir}/{proof_name}");
|
||||
if self.sim.stat(&txn_proof).await.is_ok() {
|
||||
let _ = self.sim.rename(&txn_proof, &dst_proof).await;
|
||||
} else {
|
||||
let src_parent = src.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
|
||||
let src_proof = if src_parent.is_empty() {
|
||||
proof_name
|
||||
} else {
|
||||
format!("{src_parent}/{proof_name}")
|
||||
};
|
||||
if self.sim.stat(&src_proof).await.is_ok() {
|
||||
let _ = self.sim.rename(&src_proof, &dst_proof).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
let meta_path = format!("{dst}.meta");
|
||||
self.write_durable_file(&meta_path, meta).await
|
||||
}
|
||||
|
||||
async fn settle_part_transaction(&self, volume: &str, path: &str, action: PartTransactionAction) -> Result<()> {
|
||||
self.ensure_online()?;
|
||||
let dst = join_vol_path(volume, path)?;
|
||||
let dst_meta = format!("{dst}.meta");
|
||||
let txn_dir = join_vol_path(volume, &part_transaction_path(path))?;
|
||||
if self.sim.stat(&txn_dir).await.is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
match action {
|
||||
PartTransactionAction::Commit => {}
|
||||
PartTransactionAction::Rollback => {
|
||||
let _ = self
|
||||
.write_durable_file(&format!("{txn_dir}/{PART_TRANSACTION_ROLLBACK}"), Bytes::new())
|
||||
.await;
|
||||
let old_data = format!("{txn_dir}/old.data");
|
||||
if self.sim.stat(&old_data).await.is_ok() {
|
||||
self.sim.rename(&old_data, &dst).await.map_err(map_sim_err)?;
|
||||
} else if self.sim.stat(&format!("{txn_dir}/old.data.absent")).await.is_ok() {
|
||||
let _ = self.sim.remove_file(&dst).await;
|
||||
}
|
||||
let old_meta = format!("{txn_dir}/{PART_TRANSACTION_OLD_META}");
|
||||
if self.sim.stat(&old_meta).await.is_ok() {
|
||||
self.sim.rename(&old_meta, &dst_meta).await.map_err(map_sim_err)?;
|
||||
} else if self.sim.stat(&format!("{txn_dir}/old.meta.absent")).await.is_ok() {
|
||||
let _ = self.sim.remove_file(&dst_meta).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
match self.sim.remove_dir_all(&txn_dir).await {
|
||||
Ok(()) | Err(SimErr::NotFound(_)) => {}
|
||||
Err(e) => return Err(map_sim_err(e)),
|
||||
}
|
||||
if let Some((parent, _)) = txn_dir.rsplit_once('/') {
|
||||
let _ = self.fsync_parent_chain(parent).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete(&self, volume: &str, path: &str, opt: DeleteOptions) -> Result<()> {
|
||||
self.ensure_online()?;
|
||||
self.ensure_volume_exists(volume).await?;
|
||||
|
||||
@@ -21,6 +21,7 @@ use self::commit::lock_rename_commit_directories;
|
||||
|
||||
mod commit;
|
||||
pub(super) mod delete_recovery;
|
||||
pub(crate) use delete_recovery::DiscoverySession;
|
||||
mod delete_reserve;
|
||||
#[cfg(all(unix, test))]
|
||||
#[path = "fd_cache_tests.rs"]
|
||||
@@ -1731,7 +1732,7 @@ async fn remove_windows_empty_directory(directory: LockedEmptyDirectory) -> std:
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use windows_sys::Win32::Storage::FileSystem::{FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle};
|
||||
|
||||
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
|
||||
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
|
||||
let disposition_size = u32::try_from(std::mem::size_of_val(&disposition))
|
||||
.map_err(|_| std::io::Error::other("FILE_DISPOSITION_INFO size exceeds the Win32 API limit"))?;
|
||||
let handle = directory.handle.as_raw_handle();
|
||||
@@ -18064,7 +18065,7 @@ impl DiskAPI for LocalDisk {
|
||||
|
||||
#[tracing::instrument(level = "trace", skip_all)]
|
||||
async fn update_metadata(&self, volume: &str, path: &str, fi: FileInfo, opts: &UpdateMetadataOpts) -> Result<()> {
|
||||
let status_only = super::usage_watch::status_only_metadata_update(&fi, opts);
|
||||
let status_only_candidate = super::usage_watch::status_only_metadata_candidate(&fi, opts);
|
||||
multipart_staging::reject_native_control_write(&self.root, self.io_root(), volume, path)?;
|
||||
pool_meta_native::reject_raw_path(&self.root, volume, path)?;
|
||||
let object_path = self.get_object_path(volume, path)?;
|
||||
@@ -18084,7 +18085,9 @@ impl DiskAPI for LocalDisk {
|
||||
.await;
|
||||
}
|
||||
let source_owner = self.multipart_source_owner(volume, path, false, true, None).await?;
|
||||
let source_owner = if status_only {
|
||||
// A status-only candidate takes usage ownership below, once the stored
|
||||
// version shows whether the update changes anything usage observes.
|
||||
let source_owner = if status_only_candidate {
|
||||
source_owner
|
||||
} else {
|
||||
self.usage_watch_binding.owner(volume, source_owner)
|
||||
@@ -18117,6 +18120,8 @@ impl DiskAPI for LocalDisk {
|
||||
let replace_user_metadata = opts.replace_user_metadata;
|
||||
let has_version_id = fi.version_id.is_some();
|
||||
let publication_root = self.publication_root.clone();
|
||||
let usage_watch_binding = Arc::clone(&self.usage_watch_binding);
|
||||
let usage_bucket = volume.to_string();
|
||||
let lease = os::acquire_namespace_mutation_lease_with_owner(&xl_file_path, namespace_owner).await;
|
||||
return os::run_blocking_namespace_operation_with_sync(
|
||||
lease,
|
||||
@@ -18132,13 +18137,20 @@ impl DiskAPI for LocalDisk {
|
||||
if !FileMeta::is_xl2_v1_format(&buf) {
|
||||
return Ok(Err(DiskError::FileVersionNotFound));
|
||||
}
|
||||
let wbuf = match FileMeta::load(&buf).and_then(|mut xl_meta| {
|
||||
let (wbuf, status_only) = match FileMeta::load(&buf).and_then(|mut xl_meta| {
|
||||
let stored = status_only_candidate.then(|| xl_meta.clone());
|
||||
xl_meta.update_object_version_with_opts(fi, replace_user_metadata)?;
|
||||
xl_meta.marshal_msg()
|
||||
let status_only =
|
||||
stored.is_some_and(|stored| super::usage_watch::status_only_metadata_change(&stored, &xl_meta));
|
||||
Ok((xl_meta.marshal_msg()?, status_only))
|
||||
}) {
|
||||
Ok(wbuf) => wbuf,
|
||||
Ok(update) => update,
|
||||
Err(err) => return Ok(Err(err.into())),
|
||||
};
|
||||
// Held until the rename below has finished.
|
||||
let _usage_owner = (status_only_candidate && !status_only)
|
||||
.then(|| usage_watch_binding.owner(&usage_bucket, None))
|
||||
.flatten();
|
||||
if let Some(parent) = tmp_file_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
@@ -18176,9 +18188,16 @@ impl DiskAPI for LocalDisk {
|
||||
}
|
||||
|
||||
let mut xl_meta = FileMeta::load(buf.as_ref())?;
|
||||
let stored = status_only_candidate.then(|| xl_meta.clone());
|
||||
|
||||
xl_meta.update_object_version_with_opts(fi, opts.replace_user_metadata)?;
|
||||
|
||||
let namespace_owner = match stored {
|
||||
Some(stored) if !super::usage_watch::status_only_metadata_change(&stored, &xl_meta) => {
|
||||
self.usage_watch_binding.owner(volume, namespace_owner)
|
||||
}
|
||||
_ => namespace_owner,
|
||||
};
|
||||
let wbuf = xl_meta.marshal_msg()?;
|
||||
|
||||
return self
|
||||
|
||||
@@ -31,13 +31,26 @@ pub(super) const PREPARED: &str = "delete-prepared";
|
||||
pub(super) const TARGET: &str = "delete-target";
|
||||
pub(super) const FINISHED: &str = "delete-commit-finished";
|
||||
const MAX_METADATA: u64 = 64 * 1024 * 1024;
|
||||
struct DiscoverySession {
|
||||
#[cfg(target_os = "linux")]
|
||||
type DiscoveryEntries = rustix::fs::Dir;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
type DiscoveryEntries = std::fs::ReadDir;
|
||||
|
||||
#[cfg(any(test, not(target_os = "linux")))]
|
||||
fn open_discovery_entries(path: &Path) -> std::io::Result<DiscoveryEntries> {
|
||||
#[cfg(target_os = "linux")]
|
||||
return rustix::fs::Dir::new(open_dir_fd(path)?).map_err(std::io::Error::from);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
std::fs::read_dir(path)
|
||||
}
|
||||
|
||||
pub(crate) struct DiscoverySession {
|
||||
disk_root: PathBuf,
|
||||
volume: String,
|
||||
object: Option<String>,
|
||||
root: PathBuf,
|
||||
_mount: std::fs::File,
|
||||
frames: Vec<(String, std::fs::ReadDir)>,
|
||||
frames: Vec<(String, DiscoveryEntries)>,
|
||||
touched: Instant,
|
||||
#[cfg(test)]
|
||||
metadata_stats: Arc<std::sync::atomic::AtomicUsize>,
|
||||
@@ -52,6 +65,7 @@ const PLAIN_CHILDREN_PER_BUDGET_ENTRY: u32 = 64;
|
||||
/// Entries one step of the resumable (background) discovery may visit. The
|
||||
/// foreground bounded protocol has its own, larger per-call allowance.
|
||||
const DISCOVERY_STEP_ENTRIES: u32 = 4096;
|
||||
const BACKGROUND_DISCOVERY_SLICE: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Wall-clock allowance of one bounded discovery call: a third of the drive
|
||||
/// timeout that wraps the call (including its wait for a lane worker), capped at
|
||||
@@ -90,8 +104,23 @@ impl DiscoverySession {
|
||||
max_entries: u32,
|
||||
should_stop: &dyn Fn() -> bool,
|
||||
) -> std::io::Result<(Vec<DeleteTransactionId>, Option<Self>, u32)> {
|
||||
if should_stop() {
|
||||
return Ok((Vec::new(), Some(self), 0));
|
||||
}
|
||||
if self.frames.is_empty() {
|
||||
match std::fs::read_dir(&self.root) {
|
||||
#[cfg(target_os = "linux")]
|
||||
let entries = {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
let mut relative = PathBuf::from(&self.volume);
|
||||
if let Some(object) = &self.object {
|
||||
relative.push(object);
|
||||
}
|
||||
os::open_linux_relative(&self._mount, &relative, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty())
|
||||
.and_then(|fd| rustix::fs::Dir::new(fd).map_err(std::io::Error::from))
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let entries = open_discovery_entries(&self.root);
|
||||
match entries {
|
||||
Ok(entries) => self.frames.push((String::new(), entries)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {
|
||||
return Ok((Vec::new(), None, 0));
|
||||
@@ -99,15 +128,14 @@ impl DiscoverySession {
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
let limit = usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?;
|
||||
let mut transactions = BTreeSet::new();
|
||||
let mut seen_candidates = HashSet::new();
|
||||
let mut visited = 0u32;
|
||||
let mut skipped_by_name = 0u32;
|
||||
while !self.frames.is_empty()
|
||||
&& transactions.len() < usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?
|
||||
&& visited < max_entries
|
||||
&& !should_stop()
|
||||
{
|
||||
while !self.frames.is_empty() && transactions.len() < limit && visited < max_entries && !should_stop() {
|
||||
// A valid 1024-byte key can exceed 256 one-byte components.
|
||||
let can_descend = self.frames.len() < 1024;
|
||||
let (parent, entries) = self
|
||||
.frames
|
||||
.last_mut()
|
||||
@@ -119,11 +147,17 @@ impl DiscoverySession {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let name = entry
|
||||
.file_name()
|
||||
.into_string()
|
||||
.map_err(|_| std::io::Error::from(ErrorKind::InvalidData))?;
|
||||
if !safe_path(&name, false) || name.contains('/') {
|
||||
let name = entry.file_name();
|
||||
#[cfg(target_os = "linux")]
|
||||
if matches!(name.to_bytes(), b"." | b"..") {
|
||||
continue;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
let name = name.to_str().ok();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let name = name.to_str();
|
||||
let name = name.ok_or_else(|| std::io::Error::from(ErrorKind::InvalidData))?;
|
||||
if !safe_path(name, false) || name.contains('/') {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
// An object-scoped scan only ever descends into transaction (UUID)
|
||||
@@ -136,9 +170,9 @@ impl DiscoverySession {
|
||||
// folder prefix with many children, UUID-named or not, can complete.
|
||||
if self.object.is_some()
|
||||
&& if parent.is_empty() {
|
||||
!canonical_uuid(&name).is_some_and(|id| !id.is_nil())
|
||||
!canonical_uuid(name).is_some_and(|id| !id.is_nil())
|
||||
} else {
|
||||
!may_be_delete_evidence(&name)
|
||||
!may_be_delete_evidence(name)
|
||||
}
|
||||
{
|
||||
skipped_by_name += 1;
|
||||
@@ -148,115 +182,186 @@ impl DiscoverySession {
|
||||
continue;
|
||||
}
|
||||
visited += 1;
|
||||
if self.object.is_none() && !may_be_delete_evidence(&name) {
|
||||
let ft = match entry.file_type() {
|
||||
Ok(ft) => ft,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
#[cfg(target_os = "linux")]
|
||||
let is_dir = {
|
||||
use rustix::fs::{AtFlags, FileType, statat};
|
||||
|
||||
let kind = entry.file_type();
|
||||
#[cfg(test)]
|
||||
let kind = if FORCE_RAW_DIR_DT_UNKNOWN.with(std::cell::Cell::get) {
|
||||
FileType::Unknown
|
||||
} else {
|
||||
kind
|
||||
};
|
||||
if ft.is_symlink() {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
if !ft.is_dir() && !ft.is_file() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
if ft.is_file() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let relative = if parent.is_empty() {
|
||||
name.clone()
|
||||
} else {
|
||||
format!("{parent}/{name}")
|
||||
};
|
||||
let path = self.root.join(&relative);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
let kind = match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if !kind.is_dir() && !kind.is_file() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
if kind.is_file() {
|
||||
let bound = match self.object.as_deref() {
|
||||
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
|
||||
Some(_) => None,
|
||||
None => parent.rsplit_once('/'),
|
||||
let kind = if kind == FileType::Unknown {
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
match statat(entries.fd()?, entry.file_name(), AtFlags::SYMLINK_NOFOLLOW) {
|
||||
Ok(stat) => FileType::from_raw_mode(stat.st_mode),
|
||||
Err(rustix::io::Errno::NOENT) => continue,
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
} else {
|
||||
kind
|
||||
};
|
||||
if let Some((object, id)) = bound {
|
||||
let transaction =
|
||||
if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name.as_str()) {
|
||||
canonical_uuid(id).filter(|id| !id.is_nil())
|
||||
} else {
|
||||
[
|
||||
DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
]
|
||||
.iter()
|
||||
.find_map(|prefix| delete_transaction_marker_id(&name, prefix))
|
||||
};
|
||||
if let Some(transaction) = transaction {
|
||||
if !seen_candidates.insert((object.to_owned(), transaction)) {
|
||||
continue;
|
||||
}
|
||||
let physical = match self.object.as_ref() {
|
||||
Some(_) => self.root.clone(),
|
||||
None => self.root.join(object),
|
||||
};
|
||||
if name == STORAGE_FORMAT_FILE_BACKUP
|
||||
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let proof_root = physical.join(transaction.to_string());
|
||||
if self.object.is_some() {
|
||||
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
|
||||
transactions.insert((object.to_owned(), transaction));
|
||||
continue;
|
||||
}
|
||||
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
// Only a fully bound journal can name a logical
|
||||
// key. Other records remain discoverable by their
|
||||
// physical key for canonical inspection to reject.
|
||||
let record = match prepared {
|
||||
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
|
||||
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
|
||||
.map_err(std::io::Error::from)?
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
|
||||
.map(|receipt| receipt.journal),
|
||||
};
|
||||
let logical = record
|
||||
.filter(|journal| {
|
||||
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
|
||||
&& journal.volume == self.volume
|
||||
&& journal.transaction == transaction
|
||||
&& safe_path(&journal.object, false)
|
||||
&& match self.object.as_ref() {
|
||||
Some(scope) => scope == &journal.object,
|
||||
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
|
||||
}
|
||||
})
|
||||
.map_or_else(|| object.to_owned(), |journal| journal.object);
|
||||
transactions.insert((logical, transaction));
|
||||
match kind {
|
||||
FileType::Directory => true,
|
||||
FileType::RegularFile => false,
|
||||
FileType::Symlink => return Err(std::io::Error::from(DiskError::InvalidPath)),
|
||||
_ => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let is_dir = {
|
||||
if self.object.is_none() && !may_be_delete_evidence(name) {
|
||||
let kind = match entry.file_type() {
|
||||
Ok(kind) => kind,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if kind.is_file() {
|
||||
continue;
|
||||
}
|
||||
if kind.is_symlink() {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
if !kind.is_dir() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(&name).is_some_and(|id| !id.is_nil())) {
|
||||
|
||||
let path = self.root.join(parent.as_str()).join(name);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.is_dir() => true,
|
||||
Ok(metadata) if metadata.is_file() => false,
|
||||
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
};
|
||||
|
||||
if is_dir {
|
||||
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(name).is_some_and(|id| !id.is_nil())) {
|
||||
continue;
|
||||
}
|
||||
// A valid 1024-byte key can exceed 256 one-byte path
|
||||
// components; allow its transaction/data directories too.
|
||||
if self.frames.len() >= 1024 {
|
||||
if !can_descend {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
self.frames.push((relative, std::fs::read_dir(path)?));
|
||||
let relative = if parent.is_empty() {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{parent}/{name}")
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
let child = {
|
||||
use rustix::fs::{Mode, OFlags, openat};
|
||||
match openat(
|
||||
entries.fd()?,
|
||||
entry.file_name(),
|
||||
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
) {
|
||||
Ok(fd) => rustix::fs::Dir::new(fd).map_err(std::io::Error::from),
|
||||
Err(rustix::io::Errno::NOTDIR | rustix::io::Errno::LOOP) => {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let child = open_discovery_entries(&self.root.join(&relative));
|
||||
match child {
|
||||
Ok(entries) => self.frames.push((relative, entries)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if !may_be_delete_evidence(name) {
|
||||
// Ordinary data and metadata files cannot contribute a recovery hint.
|
||||
continue;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// Keep canonical, live-path validation for the sparse proof candidates.
|
||||
let path = self.root.join(parent.as_str()).join(name);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.is_file() => {}
|
||||
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
let bound = match self.object.as_deref() {
|
||||
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
|
||||
Some(_) => None,
|
||||
None => parent.rsplit_once('/'),
|
||||
};
|
||||
if let Some((object, id)) = bound {
|
||||
let transaction = if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name) {
|
||||
canonical_uuid(id).filter(|id| !id.is_nil())
|
||||
} else {
|
||||
[
|
||||
DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
]
|
||||
.iter()
|
||||
.find_map(|prefix| delete_transaction_marker_id(name, prefix))
|
||||
};
|
||||
if let Some(transaction) = transaction {
|
||||
if !seen_candidates.insert((object.to_owned(), transaction)) {
|
||||
continue;
|
||||
}
|
||||
let physical = match self.object.as_ref() {
|
||||
Some(_) => self.root.clone(),
|
||||
None => self.root.join(object),
|
||||
};
|
||||
if name == STORAGE_FORMAT_FILE_BACKUP
|
||||
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let proof_root = physical.join(transaction.to_string());
|
||||
if self.object.is_some() {
|
||||
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
|
||||
transactions.insert((object.to_owned(), transaction));
|
||||
continue;
|
||||
}
|
||||
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
// Only a fully bound journal can name a logical
|
||||
// key. Other records remain discoverable by their
|
||||
// physical key for canonical inspection to reject.
|
||||
let record = match prepared {
|
||||
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
|
||||
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
|
||||
.map_err(std::io::Error::from)?
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
|
||||
.map(|receipt| receipt.journal),
|
||||
};
|
||||
let logical = record
|
||||
.filter(|journal| {
|
||||
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
|
||||
&& journal.volume == self.volume
|
||||
&& journal.transaction == transaction
|
||||
&& safe_path(&journal.object, false)
|
||||
&& match self.object.as_ref() {
|
||||
Some(scope) => scope == &journal.object,
|
||||
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
|
||||
}
|
||||
})
|
||||
.map_or_else(|| object.to_owned(), |journal| journal.object);
|
||||
transactions.insert((logical, transaction));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,10 +379,9 @@ impl DiscoverySession {
|
||||
if !transactions.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(mut next) = next else {
|
||||
let Some(next) = next else {
|
||||
return Ok(false);
|
||||
};
|
||||
next.touched = Instant::now();
|
||||
self = next;
|
||||
}
|
||||
}
|
||||
@@ -1926,23 +2030,40 @@ impl LocalDisk {
|
||||
.await
|
||||
.map_err(to_file_error)?
|
||||
}
|
||||
/// Local maintenance may pause a page behind recovery backpressure. It
|
||||
/// retains only its own bounded set of cursors; remote callers still have
|
||||
/// the ordinary idle deadline and every resumed page rechecks mount identity.
|
||||
pub(crate) fn renew_delete_recovery_cursor(&self, volume: &str, cursor: &DeleteRecoveryCursor) -> bool {
|
||||
let mut sessions = DISCOVERY_SESSIONS.lock();
|
||||
let Some(session) = sessions.get_mut(&cursor.token) else {
|
||||
return false;
|
||||
};
|
||||
if session.disk_root != self.io_root()
|
||||
|| session.volume != volume
|
||||
|| session.object.is_some()
|
||||
|| session.touched.elapsed() > Duration::from_secs(300)
|
||||
{
|
||||
return false;
|
||||
pub(crate) async fn lock_delete_discovery_bucket(&self, volume: &str) -> Result<Arc<os::NamespaceMutationLease>> {
|
||||
if !safe_path(volume, false) || volume.contains('/') {
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
session.touched = Instant::now();
|
||||
true
|
||||
let path = build_local_disk_bucket_path(self.io_root(), volume);
|
||||
Ok(os::acquire_namespace_mutation_lease_with_owner(&path, None).await)
|
||||
}
|
||||
|
||||
pub(in crate::disk) fn advance_background_delete_discovery(
|
||||
&self,
|
||||
volume: &str,
|
||||
session: Option<DiscoverySession>,
|
||||
limit: u32,
|
||||
cancel: &tokio_util::sync::CancellationToken,
|
||||
retired: &tokio_util::sync::CancellationToken,
|
||||
) -> Result<(Vec<DeleteTransactionId>, Option<DiscoverySession>)> {
|
||||
if retired.is_cancelled() {
|
||||
return Err(DiskError::DiskNotFound);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Ok((Vec::new(), session));
|
||||
}
|
||||
let path = self.delete_discovery_path(volume, None)?;
|
||||
let session = match session {
|
||||
Some(session) => session,
|
||||
None => self.new_delete_discovery_session(volume, None, &path)?,
|
||||
};
|
||||
self.validate_delete_discovery_owner(&session)?;
|
||||
let deadline = Instant::now() + BACKGROUND_DISCOVERY_SLICE;
|
||||
let should_stop = || cancel.is_cancelled() || retired.is_cancelled() || Instant::now() >= deadline;
|
||||
let (transactions, next, _) = session
|
||||
.advance_bounded(limit, DISCOVERY_STEP_ENTRIES, &should_stop)
|
||||
.map_err(to_file_error)?;
|
||||
Ok((transactions, next))
|
||||
}
|
||||
|
||||
fn delete_discovery_path(&self, volume: &str, object: Option<&str>) -> Result<PathBuf> {
|
||||
@@ -1998,7 +2119,7 @@ impl LocalDisk {
|
||||
}
|
||||
|
||||
fn validate_delete_discovery_owner(&self, session: &DiscoverySession) -> Result<()> {
|
||||
if session.disk_root != self.io_root() || session.touched.elapsed() > Duration::from_secs(300) {
|
||||
if session.disk_root != self.io_root() {
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
@@ -2092,7 +2213,10 @@ impl LocalDisk {
|
||||
.lock()
|
||||
.remove(&cursor.token)
|
||||
.ok_or(DiskError::FileNotFound)?;
|
||||
if session.volume != volume || session.object.as_deref() != object {
|
||||
if session.volume != volume
|
||||
|| session.object.as_deref() != object
|
||||
|| session.touched.elapsed() > Duration::from_secs(300)
|
||||
{
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
(cursor.token, session)
|
||||
@@ -7740,10 +7864,6 @@ mod tests {
|
||||
.expect("bounded discovery continues");
|
||||
found.extend(page.transactions.into_iter().map(|id| (id.object, id.transaction)));
|
||||
cursor = page.next;
|
||||
if let Some(cursor) = cursor.as_ref() {
|
||||
assert!(!disk.renew_delete_recovery_cursor("different-bucket", cursor));
|
||||
assert!(disk.renew_delete_recovery_cursor("recovery", cursor));
|
||||
}
|
||||
if cursor.is_none() {
|
||||
break;
|
||||
}
|
||||
@@ -8324,8 +8444,8 @@ mod tests {
|
||||
// Seed a valid DFS continuation so this assertion is independent of
|
||||
// filesystem directory ordering: the large empty frame runs first.
|
||||
session.frames = vec![
|
||||
(transaction.to_string(), std::fs::read_dir(&proof).expect("later evidence frame")),
|
||||
(filler_id, std::fs::read_dir(&filler).expect("empty intermediate frame")),
|
||||
(transaction.to_string(), open_discovery_entries(&proof).expect("later evidence frame")),
|
||||
(filler_id, open_discovery_entries(&filler).expect("empty intermediate frame")),
|
||||
];
|
||||
assert!(
|
||||
session
|
||||
@@ -8932,6 +9052,23 @@ mod tests {
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let prefix = temp.path().join("recovery/prefix");
|
||||
fs::create_dir_all(prefix.join("key")).await.expect("object directory");
|
||||
fs::create_dir(outside.path().join("key"))
|
||||
.await
|
||||
.expect("outside object directory");
|
||||
let path = disk
|
||||
.delete_discovery_path("recovery", Some("prefix/key"))
|
||||
.expect("validated key path");
|
||||
let session = disk
|
||||
.new_delete_discovery_session("recovery", Some("prefix/key"), &path)
|
||||
.expect("unopened key session");
|
||||
fs::remove_dir_all(&prefix).await.expect("remove original prefix");
|
||||
symlink(outside.path(), &prefix).expect("replace a parent after validation");
|
||||
assert!(session.advance(16).is_err(), "the real root open must reject a replaced ancestor");
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(outside.path().join("sentinel"))
|
||||
.await
|
||||
@@ -8965,13 +9102,36 @@ mod tests {
|
||||
assert!(transactions.is_empty());
|
||||
assert!(next.is_none());
|
||||
let stats = stats_counter.load(Ordering::Relaxed);
|
||||
// fixture() pre-creates recovery/object (1 directory + 1 xl.meta); with 32 obj-XX + 32 data_dir directories,
|
||||
// only the 65 directories reach symlink_metadata, while all 65 regular files (xl.meta and part.1) are skipped
|
||||
// via DirEntry::file_type() with 0 stats.
|
||||
assert_eq!(
|
||||
stats, 65,
|
||||
"bucket-wide discovery must skip inert regular files without symlink_metadata stats"
|
||||
);
|
||||
// The fixture has 65 directories and 65 regular files. An ordinary
|
||||
// Linux walk uses d_type and opens directories relative to the parent FD.
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let expected = match open_discovery_entries(&bucket_root).expect("read dirents").find_map(|entry| {
|
||||
let entry = entry.expect("dirent");
|
||||
(!matches!(entry.file_name().to_bytes(), b"." | b"..")).then(|| entry.file_type())
|
||||
}) {
|
||||
Some(rustix::fs::FileType::Unknown) => 130,
|
||||
Some(_) => 0,
|
||||
None => panic!("the fixture contains directories"),
|
||||
};
|
||||
assert_eq!(stats, expected, "known directory types must skip path-based metadata checks");
|
||||
|
||||
let session = disk
|
||||
.new_delete_discovery_session("recovery", None, &disc_path)
|
||||
.expect("discovery session with unknown dirent types");
|
||||
let fallback_stats = Arc::clone(&session.metadata_stats);
|
||||
let result = FORCE_RAW_DIR_DT_UNKNOWN.with(|flag| {
|
||||
let previous = flag.replace(true);
|
||||
let result = session.advance(16);
|
||||
flag.set(previous);
|
||||
result
|
||||
});
|
||||
let (transactions, next) = result.expect("unknown directory types use no-follow statat");
|
||||
assert!(transactions.is_empty() && next.is_none());
|
||||
assert_eq!(fallback_stats.load(Ordering::Relaxed), 130, "one parent-relative stat per unknown entry");
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
assert_eq!(stats, 65, "the portable walk skips metadata checks for ordinary files");
|
||||
|
||||
// A symlink with an inert file name ("part.1") inside a bucket-wide walk must still fail closed with InvalidPath.
|
||||
let outside = tempfile::tempdir().expect("outside dir");
|
||||
|
||||
@@ -426,6 +426,7 @@ pub(super) fn has_clean_active_multipart_source(source: &Path, part_number: Opti
|
||||
clean
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn has_active_multipart_source_matching(
|
||||
source: &Path,
|
||||
expected_data_dir: Option<Uuid>,
|
||||
@@ -447,6 +448,29 @@ pub(super) fn has_active_multipart_source_matching(
|
||||
matches
|
||||
}
|
||||
|
||||
pub(super) fn check_active_multipart_source_matching_and_clean_part(
|
||||
source: &Path,
|
||||
expected_data_dir: Option<Uuid>,
|
||||
expected_mod_time: Option<time::OffsetDateTime>,
|
||||
part_number: usize,
|
||||
) -> (bool, bool) {
|
||||
if part_number == 0 || expected_data_dir.is_none_or(|dir| dir.is_nil()) || expected_mod_time.is_none() {
|
||||
return (false, false);
|
||||
}
|
||||
let Some((head_stamp, matches, clean)) = ACTIVE_MULTIPART_SOURCE_HEADS.with_get(source, |entry| {
|
||||
let matches = !entry.fi.deleted && entry.fi.data_dir == expected_data_dir && entry.fi.mod_time == expected_mod_time;
|
||||
let clean = !entry.unsettled_parts.contains(&part_number);
|
||||
(entry.head_stamp, matches, clean)
|
||||
}) else {
|
||||
return (false, false);
|
||||
};
|
||||
if !stamp_matches_active_disk(source, head_stamp) {
|
||||
ACTIVE_MULTIPART_SOURCE_HEADS.remove(source);
|
||||
return (false, false);
|
||||
}
|
||||
(matches, matches && clean)
|
||||
}
|
||||
|
||||
pub(super) fn begin_active_multipart_part_transaction(source: &Path, part_number: usize) {
|
||||
ACTIVE_MULTIPART_SOURCE_HEADS.with_get_mut(source, |entry| {
|
||||
entry.unsettled_parts.insert(part_number);
|
||||
|
||||
@@ -375,6 +375,7 @@ impl LocalDisk {
|
||||
super::multipart_source_state::has_clean_active_multipart_source(&source, part_number)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn has_active_multipart_source_matching(
|
||||
&self,
|
||||
upload_path: &str,
|
||||
@@ -388,6 +389,25 @@ impl LocalDisk {
|
||||
super::multipart_source_state::has_active_multipart_source_matching(&source, expected_data_dir, expected_mod_time)
|
||||
}
|
||||
|
||||
pub(crate) fn check_active_multipart_source_matching_and_clean_part(
|
||||
&self,
|
||||
upload_path: &str,
|
||||
expected_data_dir: Option<Uuid>,
|
||||
expected_mod_time: Option<time::OffsetDateTime>,
|
||||
part_number: usize,
|
||||
) -> (bool, bool) {
|
||||
let root = upload_scope_root(upload_path, false);
|
||||
let Ok(source) = self.io_get_object_open_path(RUSTFS_META_MULTIPART_BUCKET, root) else {
|
||||
return (false, false);
|
||||
};
|
||||
super::multipart_source_state::check_active_multipart_source_matching_and_clean_part(
|
||||
&source,
|
||||
expected_data_dir,
|
||||
expected_mod_time,
|
||||
part_number,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn multipart_source_admission(
|
||||
&self,
|
||||
volume: &str,
|
||||
@@ -1502,6 +1522,18 @@ mod tests {
|
||||
assert!(!disk.has_active_multipart_source_matching(&upload, Some(Uuid::new_v4()), init_fi.mod_time));
|
||||
assert!(!disk.has_active_multipart_source_matching(&upload, Some(Uuid::nil()), init_fi.mod_time));
|
||||
assert!(!disk.has_active_multipart_source_matching(&upload, Some(data_dir), None));
|
||||
assert_eq!(
|
||||
disk.check_active_multipart_source_matching_and_clean_part(&upload, Some(data_dir), init_fi.mod_time, 1),
|
||||
(true, true)
|
||||
);
|
||||
assert_eq!(
|
||||
disk.check_active_multipart_source_matching_and_clean_part(&upload, Some(data_dir), init_fi.mod_time, 0),
|
||||
(false, false)
|
||||
);
|
||||
assert_eq!(
|
||||
disk.check_active_multipart_source_matching_and_clean_part(&upload, Some(Uuid::new_v4()), init_fi.mod_time, 1),
|
||||
(false, false)
|
||||
);
|
||||
|
||||
let read_fi = disk
|
||||
.read_version("", RUSTFS_META_MULTIPART_BUCKET, &upload, "", &ReadOptions::default())
|
||||
@@ -1585,6 +1617,16 @@ mod tests {
|
||||
!disk.has_clean_active_multipart_source(&destination2, true),
|
||||
"in-flight part 2 must report not clean for part 2"
|
||||
);
|
||||
assert_eq!(
|
||||
disk.check_active_multipart_source_matching_and_clean_part(&upload, Some(data_dir), init_fi.mod_time, 1),
|
||||
(true, true),
|
||||
"settled part 1 must report (head_matched=true, part_clean=true) while part 2 is in-flight"
|
||||
);
|
||||
assert_eq!(
|
||||
disk.check_active_multipart_source_matching_and_clean_part(&upload, Some(data_dir), init_fi.mod_time, 2),
|
||||
(true, false),
|
||||
"unsettled part 2 must report (head_matched=true, part_clean=false)"
|
||||
);
|
||||
for non_canonical in [
|
||||
format!("{upload}/{data_dir}/part.0"),
|
||||
format!("{upload}/{data_dir}/part.01"),
|
||||
|
||||
@@ -98,30 +98,81 @@ async fn usage_watch_stays_inflight_after_metadata_is_visible_and_waiter_is_canc
|
||||
);
|
||||
}
|
||||
|
||||
const REPLICATION_TARGET_ARN: &str = "arn:rustfs:replication::target:bucket";
|
||||
|
||||
/// Stores one version and returns it the way a status write-back starts: the
|
||||
/// whole version metadata read back from the disk.
|
||||
async fn stored_version(disk: &LocalDisk) -> FileInfo {
|
||||
let mut info =
|
||||
super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
|
||||
info.metadata.insert("etag".into(), "5d41402abc4b2a76b9719d911017c592".into());
|
||||
info.metadata.insert("content-type".into(), "application/octet-stream".into());
|
||||
let version_id = info.version_id.expect("fixture version id").to_string();
|
||||
disk.write_metadata("", "bucket", "object", info)
|
||||
.await
|
||||
.expect("initial counted version");
|
||||
disk.read_version("", "bucket", "object", &version_id, &ReadOptions::default())
|
||||
.await
|
||||
.expect("stored version")
|
||||
}
|
||||
|
||||
/// Mirrors what `put_object_metadata` hands the disk for a status write-back.
|
||||
fn apply_replication_writeback(fi: &mut FileInfo, status: &str) {
|
||||
insert_replication_writeback(&mut fi.metadata, status);
|
||||
fi.acknowledge_data_movement();
|
||||
}
|
||||
|
||||
fn insert_replication_writeback(metadata: &mut HashMap<String, String>, status: &str) {
|
||||
use rustfs_utils::http::metadata_compat::insert_str;
|
||||
use rustfs_utils::http::{
|
||||
SUFFIX_REPLICATION_RESET_ARN_PREFIX, SUFFIX_REPLICATION_STATUS, SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX,
|
||||
};
|
||||
insert_str(metadata, SUFFIX_REPLICATION_STATUS, format!("{REPLICATION_TARGET_ARN}={status};"));
|
||||
insert_str(
|
||||
metadata,
|
||||
&format!("{SUFFIX_REPLICATION_RESET_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
|
||||
"2026-01-01T00:00:00Z;reset".into(),
|
||||
);
|
||||
insert_str(
|
||||
metadata,
|
||||
&format!("{SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
|
||||
"target-version".into(),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
let info = super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
|
||||
disk.write_metadata("", "bucket", "object", info.clone())
|
||||
.await
|
||||
.expect("initial counted version");
|
||||
let info = stored_version(&disk).await;
|
||||
let before = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("idle watch");
|
||||
let mut status = info.clone();
|
||||
status.metadata.clear();
|
||||
rustfs_utils::http::metadata_compat::insert_str(
|
||||
&mut status.metadata,
|
||||
rustfs_utils::http::SUFFIX_REPLICATION_STATUS,
|
||||
"arn=COMPLETED;".into(),
|
||||
);
|
||||
disk.update_metadata("bucket", "object", status, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("status-class metadata update");
|
||||
// A write-back carries the whole version metadata, not only the status keys.
|
||||
for status in ["PENDING", "COMPLETED"] {
|
||||
let mut writeback = info.clone();
|
||||
apply_replication_writeback(&mut writeback, status);
|
||||
disk.update_metadata("bucket", "object", writeback, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("status-class metadata update");
|
||||
}
|
||||
let after = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("status result watch");
|
||||
assert!(after.unchanged_since(&before), "replication counters retain maintenance cadence");
|
||||
let stored = disk
|
||||
.read_version(
|
||||
"",
|
||||
"bucket",
|
||||
"object",
|
||||
&info.version_id.expect("version id").to_string(),
|
||||
&ReadOptions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("written status");
|
||||
assert_eq!(
|
||||
rustfs_utils::http::get_consistent_str(&stored.metadata, rustfs_utils::http::SUFFIX_REPLICATION_STATUS),
|
||||
Some(format!("{REPLICATION_TARGET_ARN}=COMPLETED;").as_str()),
|
||||
);
|
||||
let mut next = info;
|
||||
next.version_id = Some(Uuid::new_v4());
|
||||
disk.write_metadata("", "bucket", "object", next).await.expect("new version");
|
||||
@@ -132,6 +183,33 @@ async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
|
||||
assert_eq!(changed.inflight, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_status_write_with_other_metadata_change_revokes_proof() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
let info = stored_version(&disk).await;
|
||||
let mut seeded = info.clone();
|
||||
apply_replication_writeback(&mut seeded, "PENDING");
|
||||
disk.update_metadata("bucket", "object", seeded.clone(), &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("seed status keys");
|
||||
let before = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("idle watch");
|
||||
// Status keys ride along, but the same update also rewrites user metadata.
|
||||
let mut tagged = seeded;
|
||||
apply_replication_writeback(&mut tagged, "COMPLETED");
|
||||
tagged.metadata.insert("x-amz-meta-owner".into(), "changed".into());
|
||||
disk.update_metadata("bucket", "object", tagged, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("mixed metadata update");
|
||||
let after = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("mixed update watch");
|
||||
assert!(after.revision > before.revision);
|
||||
assert!(!after.unchanged_since(&before), "a non-status change must revoke the proof");
|
||||
assert_eq!(after.inflight, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_raw_live_stream_revokes_coverage_and_internal_staging_does_not() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
|
||||
@@ -493,17 +493,23 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn has_active_multipart_source_matching(
|
||||
pub(crate) fn check_active_multipart_source_matching_and_clean_part(
|
||||
&self,
|
||||
upload_path: &str,
|
||||
expected_data_dir: Option<Uuid>,
|
||||
expected_mod_time: Option<time::OffsetDateTime>,
|
||||
) -> bool {
|
||||
part_number: usize,
|
||||
) -> (bool, bool) {
|
||||
match self {
|
||||
Self::Local(disk) => disk.has_active_multipart_source_matching(upload_path, expected_data_dir, expected_mod_time),
|
||||
Self::Remote(_) => false,
|
||||
Self::Local(disk) => disk.check_active_multipart_source_matching_and_clean_part(
|
||||
upload_path,
|
||||
expected_data_dir,
|
||||
expected_mod_time,
|
||||
part_number,
|
||||
),
|
||||
Self::Remote(_) => (false, false),
|
||||
#[cfg(feature = "dst")]
|
||||
Self::Sim(_) => false,
|
||||
Self::Sim(_) => (false, false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1752,7 +1758,7 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_faulty(&self) -> bool {
|
||||
pub fn is_faulty(&self) -> bool {
|
||||
match self {
|
||||
Disk::Local(local_disk) => local_disk.is_faulty(),
|
||||
Disk::Remote(remote_disk) => remote_disk.is_faulty(),
|
||||
@@ -1761,6 +1767,15 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
|
||||
match self {
|
||||
Disk::Remote(remote_disk) => remote_disk.probe_quorum_recovery_if_faulty().await,
|
||||
Disk::Local(_) => false,
|
||||
#[cfg(feature = "dst")]
|
||||
Disk::Sim(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe a local wrapper's retirement. Remote handles have their own RPC lifecycle.
|
||||
/// Cancelling the returned child token does not retire the underlying wrapper.
|
||||
pub fn local_retirement_token(&self) -> Option<CancellationToken> {
|
||||
|
||||
@@ -186,6 +186,7 @@ pub(crate) fn bind_multipart_proof_snapshot(
|
||||
if sim.disk_index() != slot {
|
||||
return Err(DiskError::InconsistentDisk);
|
||||
}
|
||||
sim.bind_multipart_proof_authority(authority)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6252,7 +6252,7 @@ fn rename_into_existing_parent(
|
||||
// its header, the complete UTF-16 name, and trailing zeroed storage.
|
||||
// `dst_parent` and `source` remain live until the synchronous call returns.
|
||||
unsafe {
|
||||
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: true };
|
||||
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: 1 };
|
||||
(*rename_info).RootDirectory = dst_parent.as_raw_handle();
|
||||
(*rename_info).FileNameLength = file_name_length;
|
||||
std::ptr::copy_nonoverlapping(
|
||||
@@ -6583,7 +6583,7 @@ fn linux_relative_path_has_invalid_component(relative: &Path) -> bool {
|
||||
/// Open the actual IO handle with the same containment policy as path validation.
|
||||
/// Older kernels retain fd-relative traversal; only ENOSYS enables the fallback.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn open_linux_relative(
|
||||
pub(in crate::disk) fn open_linux_relative(
|
||||
directory: &std::fs::File,
|
||||
relative: &Path,
|
||||
flags: rustix::fs::OFlags,
|
||||
@@ -7753,7 +7753,9 @@ fn set_windows_file_delete_on_close(file: &winapi_util::Handle, delete_file: boo
|
||||
Win32::{Foundation::RtlNtStatusToDosError, System::IO::IO_STATUS_BLOCK},
|
||||
};
|
||||
|
||||
let mut disposition = FILE_DISPOSITION_INFORMATION { DeleteFile: delete_file };
|
||||
let mut disposition = FILE_DISPOSITION_INFORMATION {
|
||||
DeleteFile: u8::from(delete_file),
|
||||
};
|
||||
let length = u32::try_from(size_of::<FILE_DISPOSITION_INFORMATION>())
|
||||
.map_err(|_| io::Error::other("Windows file disposition size exceeds u32"))?;
|
||||
let mut io_status = IO_STATUS_BLOCK::default();
|
||||
|
||||
@@ -7,27 +7,61 @@
|
||||
use crate::runtime::usage_watch::{UsageWatchMutationGuard, UsageWatchRegistry};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
/// Existing-version replication status writes change neither size nor version
|
||||
/// membership. Replication aggregates keep their existing maintenance cadence.
|
||||
pub(crate) fn status_only_metadata_update(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
|
||||
fn replication_status_class_key(key: &str) -> bool {
|
||||
use rustfs_utils::http::*;
|
||||
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
|
||||
let suffix = suffix.to_ascii_lowercase();
|
||||
[
|
||||
SUFFIX_REPLICA_STATUS,
|
||||
SUFFIX_REPLICA_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_STATUS,
|
||||
SUFFIX_REPLICATION_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_GENERATION,
|
||||
SUFFIX_REPLICATION_RESET,
|
||||
SUFFIX_PURGESTATUS,
|
||||
]
|
||||
.contains(&suffix.as_str())
|
||||
// Per-target resync stamps and target-assigned version ids.
|
||||
|| suffix.starts_with(SUFFIX_REPLICATION_RESET_ARN_PREFIX)
|
||||
|| suffix.starts_with(SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a metadata update may turn out to be status-only. Callers hand the
|
||||
/// disk the whole version metadata, so the keys alone cannot settle it; the
|
||||
/// decision is made by [`status_only_metadata_change`] against the stored
|
||||
/// version once it has been read under the mutation lease.
|
||||
pub(crate) fn status_only_metadata_candidate(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
|
||||
!opts.replace_user_metadata
|
||||
&& opts.transition_reconcile.is_none()
|
||||
&& !fi.metadata.is_empty()
|
||||
&& fi.metadata.keys().all(|key| {
|
||||
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
|
||||
[
|
||||
SUFFIX_REPLICA_STATUS,
|
||||
SUFFIX_REPLICA_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_STATUS,
|
||||
SUFFIX_REPLICATION_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_GENERATION,
|
||||
SUFFIX_REPLICATION_RESET,
|
||||
SUFFIX_PURGESTATUS,
|
||||
]
|
||||
.iter()
|
||||
.any(|known| suffix.eq_ignore_ascii_case(known))
|
||||
})
|
||||
&& fi.metadata.keys().any(|key| replication_status_class_key(key))
|
||||
}
|
||||
|
||||
/// Existing-version replication status writes change neither size nor version
|
||||
/// membership. Replication aggregates keep their existing maintenance cadence.
|
||||
///
|
||||
/// True only when every stored version is unchanged apart from replication
|
||||
/// status-class internal keys. Anything that cannot be compared counts as a
|
||||
/// usage-relevant change.
|
||||
pub(crate) fn status_only_metadata_change(before: &rustfs_filemeta::FileMeta, after: &rustfs_filemeta::FileMeta) -> bool {
|
||||
fn without_status_keys(version: &rustfs_filemeta::FileMetaShallowVersion) -> Option<rustfs_filemeta::FileMetaVersion> {
|
||||
let mut parsed = version.parse_version_meta().ok()?;
|
||||
if let Some(object) = parsed.object.as_mut() {
|
||||
// Metadata updates also stamp an empty data-movement
|
||||
// acknowledgement; only a non-empty marker carries state.
|
||||
object.meta_sys.retain(|key, value| {
|
||||
!replication_status_class_key(key)
|
||||
&& !(value.is_empty() && rustfs_utils::http::has_internal_suffix(key, rustfs_utils::http::SUFFIX_DATA_MOVED))
|
||||
});
|
||||
}
|
||||
Some(parsed)
|
||||
}
|
||||
before.versions.len() == after.versions.len()
|
||||
&& before.versions.iter().zip(&after.versions).all(|(old, new)| {
|
||||
old.meta == new.meta
|
||||
|| without_status_keys(old)
|
||||
.zip(without_status_keys(new))
|
||||
.is_some_and(|(old, new)| old == new)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -110,6 +110,18 @@ fn small_ingest_capacity(erasure: &Erasure, size_hint: usize) -> usize {
|
||||
}
|
||||
}
|
||||
|
||||
fn inline_ingest_capacity(erasure: &Erasure, size_hint: usize) -> std::io::Result<usize> {
|
||||
let capacity = small_ingest_capacity(erasure, size_hint);
|
||||
if capacity == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
erasure
|
||||
.total_shard_count()
|
||||
.checked_mul(HashAlgorithm::HighwayHash256S.size())
|
||||
.and_then(|hash_bytes| capacity.checked_add(hash_bytes))
|
||||
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "inline ingest capacity exceeds usize"))
|
||||
}
|
||||
|
||||
/// Keeps the encoder producer scoped to its parent future. Tokio detaches a
|
||||
/// task when its `JoinHandle` is dropped, so the producer must be aborted when
|
||||
/// an upload is cancelled before the encode pipeline finishes.
|
||||
@@ -930,25 +942,27 @@ impl Erasure {
|
||||
{
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
let mut buf = Vec::with_capacity(small_ingest_capacity(&self, size_hint));
|
||||
let total = reader.read_to_end(&mut buf).await?;
|
||||
// Match read_to_end's minimum allocation; a zero-capacity BytesMut
|
||||
// otherwise grows to 64 bytes even when its first read reaches EOF.
|
||||
let mut buf = BytesMut::with_capacity(inline_ingest_capacity(&self, size_hint)?.max(32));
|
||||
loop {
|
||||
match reader.read_buf(&mut buf).await {
|
||||
Ok(0) => break,
|
||||
Ok(_) => {}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
let total = buf.len();
|
||||
if total == 0 {
|
||||
return Ok((reader, 0, Vec::new()));
|
||||
}
|
||||
|
||||
let block = self.encode_data_owned_block(buf)?;
|
||||
let block = self.encode_buffer_mut(buf, total)?;
|
||||
if let Some(integrity) = integrity {
|
||||
integrity.push(block.shards()).await?;
|
||||
}
|
||||
let shard_count = block.shards().len();
|
||||
let mut encoded = BytesMut::with_capacity(shard_count * 32 + block.queued_bytes());
|
||||
let mut inline_shards = Vec::with_capacity(shard_count);
|
||||
for shard in block.shards() {
|
||||
let hash = HashAlgorithm::HighwayHash256S.hash_encode(shard);
|
||||
encoded.extend_from_slice(hash.as_ref());
|
||||
encoded.extend_from_slice(shard);
|
||||
inline_shards.push(encoded.split().freeze());
|
||||
}
|
||||
let inline_shards = block.into_inline_shards()?;
|
||||
|
||||
Ok((reader, total, inline_shards))
|
||||
}
|
||||
@@ -3380,34 +3394,151 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn encode_inline_shards_matches_writer_bitrot_layout() {
|
||||
const DATA_SHARDS: usize = 2;
|
||||
const PARITY_SHARDS: usize = 2;
|
||||
const BLOCK_SIZE: usize = 64;
|
||||
let checksum_algo = HashAlgorithm::HighwayHash256S;
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Arc::new(Erasure::new_with_options(DATA_SHARDS, PARITY_SHARDS, BLOCK_SIZE, uses_legacy));
|
||||
for payload in [Vec::new(), vec![0xA5], vec![0x5A; BLOCK_SIZE - 1], vec![0xC3; BLOCK_SIZE]] {
|
||||
let reader = tokio::io::BufReader::new(Cursor::new(payload.clone()));
|
||||
let (_reader, total, inline_shards) = erasure
|
||||
.clone()
|
||||
.encode_inline_shards_with_size_hint(reader, payload.len())
|
||||
.await
|
||||
.expect("inline shards should encode");
|
||||
for (data_shards, parity_shards) in [(1, 0), (2, 2), (4, 2), (12, 4)] {
|
||||
let erasure = Arc::new(Erasure::new_with_options(data_shards, parity_shards, BLOCK_SIZE, uses_legacy));
|
||||
for payload in [
|
||||
Vec::new(),
|
||||
vec![0xA5],
|
||||
(0_u8..63).collect(),
|
||||
(0_u8..64).collect(),
|
||||
vec![0x5A; BLOCK_SIZE - 1],
|
||||
vec![0xC3; BLOCK_SIZE],
|
||||
] {
|
||||
for hint in [0, payload.len(), BLOCK_SIZE * 2] {
|
||||
let reader = tokio::io::BufReader::new(Cursor::new(payload.clone()));
|
||||
let (_reader, total, inline_shards) = erasure
|
||||
.clone()
|
||||
.encode_inline_shards_with_size_hint(reader, hint)
|
||||
.await
|
||||
.expect("inline shards should encode");
|
||||
|
||||
assert_eq!(total, payload.len());
|
||||
if payload.is_empty() {
|
||||
assert!(inline_shards.is_empty());
|
||||
continue;
|
||||
assert_eq!(total, payload.len());
|
||||
if payload.is_empty() {
|
||||
assert!(inline_shards.is_empty());
|
||||
continue;
|
||||
}
|
||||
|
||||
let raw_shards = erasure.encode_data(&payload).expect("reference shards should encode");
|
||||
assert_eq!(inline_shards.len(), data_shards + parity_shards);
|
||||
for (inline, raw) in inline_shards.iter().zip(raw_shards) {
|
||||
let mut writer =
|
||||
BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), raw.len(), checksum_algo.clone());
|
||||
writer.write(&raw).await.expect("reference writer should accept shard");
|
||||
writer.shutdown().await.expect("reference writer should shutdown");
|
||||
assert_eq!(inline.as_ref(), writer.into_inline_data().expect("reference writer should retain bytes"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let raw_shards = erasure.encode_data(&payload).expect("reference shards should encode");
|
||||
assert_eq!(inline_shards.len(), DATA_SHARDS + PARITY_SHARDS);
|
||||
for (inline, raw) in inline_shards.iter().zip(raw_shards) {
|
||||
let mut writer =
|
||||
BitrotWriterWrapper::new(CustomWriter::new_inline_buffer(), raw.len(), checksum_algo.clone());
|
||||
writer.write(&raw).await.expect("reference writer should accept shard");
|
||||
writer.shutdown().await.expect("reference writer should shutdown");
|
||||
assert_eq!(inline.as_ref(), writer.into_inline_data().expect("reference writer should retain bytes"));
|
||||
#[tokio::test]
|
||||
async fn inline_framing_keeps_integrity_over_raw_shards() {
|
||||
use rustfs_filemeta::shard_integrity::IntegrityLayout;
|
||||
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Arc::new(Erasure::new_with_options(2, 2, 128 * 1024, uses_legacy));
|
||||
let payload: Vec<_> = (0_u8..=250).cycle().take(128 * 1024).collect();
|
||||
let raw_shards = erasure.encode_data(&payload).expect("reference data must encode");
|
||||
let layout = IntegrityLayout::new(2, 2, erasure.block_size, uses_legacy).expect("valid layout");
|
||||
|
||||
let (_, total, inline, proof) = Arc::clone(&erasure)
|
||||
.encode_with_shard_integrity(
|
||||
Cursor::new(payload.clone()),
|
||||
&mut [],
|
||||
ShardWritePolicy::object(3),
|
||||
1,
|
||||
IntegrityEncodeMode::Inline(payload.len()),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.expect("protected inline data must encode");
|
||||
let proof = proof.expect("protected encode must retain its proof");
|
||||
|
||||
assert_eq!(total, payload.len());
|
||||
assert_eq!(inline.expect("inline payload").len(), 4);
|
||||
proof.part.validate().expect("the prepared part must be valid");
|
||||
assert_eq!(proof.part.layout, layout);
|
||||
assert_eq!(proof.part.size, u64::try_from(payload.len()).expect("payload length fits u64"));
|
||||
assert_eq!(proof.part.stripes, 1);
|
||||
let index = proof.inline_bytes().expect("inline proof");
|
||||
assert_eq!(index.len(), proof.part.index_size().expect("valid proof length"));
|
||||
assert!(index.starts_with(&proof.part.index_header()));
|
||||
let offset = proof.part.record_offset(0).expect("first stripe exists");
|
||||
let record = &index[offset..offset + proof.part.record_size()];
|
||||
for (coding_index, raw_shard) in raw_shards.iter().enumerate() {
|
||||
proof
|
||||
.part
|
||||
.verify_shard(0, coding_index, raw_shard, record)
|
||||
.expect("the authenticated proof must cover the raw shard without its bitrot prefix");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inline_framing_preserves_eof_digest_validation() {
|
||||
use crate::io_support::rio::HashReader;
|
||||
|
||||
let erasure = Arc::new(Erasure::new(2, 2, 64));
|
||||
let payload = vec![0xA5; 64];
|
||||
for (md5, sha256) in [(Some("0".repeat(32)), None), (None, Some("0".repeat(64)))] {
|
||||
let reader = HashReader::from_stream(Cursor::new(payload.clone()), 64, 64, md5, sha256, false)
|
||||
.expect("valid digest input shape");
|
||||
let err = Arc::clone(&erasure)
|
||||
.encode_inline_shards_with_size_hint(reader, payload.len())
|
||||
.await
|
||||
.err()
|
||||
.expect("a failed EOF digest must prevent inline publication");
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inline_ingest_retries_interrupted_and_preserves_other_errors() {
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::io::ReadBuf;
|
||||
|
||||
struct ErrorAfterPrefix {
|
||||
prefix: Cursor<Vec<u8>>,
|
||||
error: Option<std::io::ErrorKind>,
|
||||
}
|
||||
|
||||
impl AsyncRead for ErrorAfterPrefix {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
if self.prefix.position() < u64::try_from(self.prefix.get_ref().len()).expect("small test reader length") {
|
||||
return Pin::new(&mut self.prefix).poll_read(cx, buf);
|
||||
}
|
||||
if let Some(kind) = self.error.take() {
|
||||
return Poll::Ready(Err(std::io::Error::new(kind, "inline reader failed")));
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
let erasure = Arc::new(Erasure::new(2, 2, 64));
|
||||
for payload in [Vec::new(), (0_u8..7).collect()] {
|
||||
for kind in [
|
||||
std::io::ErrorKind::Interrupted,
|
||||
std::io::ErrorKind::InvalidData,
|
||||
std::io::ErrorKind::BrokenPipe,
|
||||
] {
|
||||
let reader = ErrorAfterPrefix {
|
||||
prefix: Cursor::new(payload.clone()),
|
||||
error: Some(kind),
|
||||
};
|
||||
let result = Arc::clone(&erasure).encode_inline_shards_with_size_hint(reader, 0).await;
|
||||
if kind == std::io::ErrorKind::Interrupted {
|
||||
let (_, total, shards) = result.expect("Interrupted must be retried through the final EOF");
|
||||
assert_eq!(total, payload.len());
|
||||
assert_eq!(shards.len(), if payload.is_empty() { 0 } else { 4 });
|
||||
} else {
|
||||
let err = result.err().expect("the original read error must prevent inline publication");
|
||||
assert_eq!(err.kind(), kind, "partial reads must preserve the error kind");
|
||||
assert_eq!(err.to_string(), "inline reader failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ use crate::erasure::codec::shard_buf::ShardBytes;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use reed_solomon_simd;
|
||||
use rustfs_erasure_codec::galois_8::ReedSolomon;
|
||||
use rustfs_utils::HashAlgorithm;
|
||||
use smallvec::SmallVec;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
@@ -37,14 +38,12 @@ pub(crate) struct EncodedBlock {
|
||||
shard_size: usize,
|
||||
}
|
||||
|
||||
impl EncodedBlock {
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
data: Bytes::new(),
|
||||
shard_size: 0,
|
||||
}
|
||||
}
|
||||
pub(crate) struct MutableEncodedBlock {
|
||||
data: BytesMut,
|
||||
shard_size: usize,
|
||||
}
|
||||
|
||||
impl EncodedBlock {
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
@@ -79,6 +78,58 @@ impl EncodedBlock {
|
||||
}
|
||||
}
|
||||
|
||||
impl MutableEncodedBlock {
|
||||
fn freeze(self) -> EncodedBlock {
|
||||
EncodedBlock {
|
||||
data: self.data.freeze(),
|
||||
shard_size: self.shard_size,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn shards(&self) -> impl ExactSizeIterator<Item = &[u8]> {
|
||||
debug_assert!(self.shard_size > 0, "only non-empty encoded blocks reach shard writers");
|
||||
debug_assert_eq!(self.data.len() % self.shard_size, 0);
|
||||
self.data.chunks_exact(self.shard_size)
|
||||
}
|
||||
|
||||
pub(crate) fn into_inline_shards(self) -> io::Result<Vec<Bytes>> {
|
||||
if self.data.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
debug_assert!(self.shard_size > 0, "non-empty encoded blocks have a shard size");
|
||||
debug_assert_eq!(self.data.len() % self.shard_size, 0);
|
||||
let shard_count = self.data.len() / self.shard_size;
|
||||
let hash_algorithm = HashAlgorithm::HighwayHash256S;
|
||||
let hash_size = hash_algorithm.size();
|
||||
let frame_size = self
|
||||
.shard_size
|
||||
.checked_add(hash_size)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "inline shard frame size overflows usize"))?;
|
||||
let framed_size = shard_count
|
||||
.checked_mul(frame_size)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "inline shard frames exceed usize"))?;
|
||||
let mut data = self.data;
|
||||
data.resize(framed_size, 0);
|
||||
|
||||
// Expand from the last shard so each move only overwrites raw shards
|
||||
// whose payload has already reached its final, hash-prefixed location.
|
||||
for index in (0..shard_count).rev() {
|
||||
let source = index * self.shard_size;
|
||||
let frame = index * frame_size;
|
||||
data.copy_within(source..source + self.shard_size, frame + hash_size);
|
||||
let (hash, payload) = data[frame..frame + frame_size].split_at_mut(hash_size);
|
||||
hash.copy_from_slice(hash_algorithm.hash_encode(payload).as_ref());
|
||||
}
|
||||
|
||||
let mut shards = Vec::with_capacity(shard_count);
|
||||
for _ in 0..shard_count {
|
||||
shards.push(data.split_to(frame_size).freeze());
|
||||
}
|
||||
Ok(shards)
|
||||
}
|
||||
}
|
||||
|
||||
const MODERN_MAX_TOTAL_SHARDS: usize = <rustfs_erasure_codec::galois_8::Field as rustfs_erasure_codec::Field>::ORDER;
|
||||
const MODERN_REED_SOLOMON_CACHE_MAX_ENTRIES: usize = 64;
|
||||
const LEGACY_REED_SOLOMON_CACHE_MAX_ENTRIES: usize = 16;
|
||||
@@ -1077,7 +1128,12 @@ impl Erasure {
|
||||
self.encode_buffer(data_buffer, data_len)
|
||||
}
|
||||
|
||||
fn encode_buffer(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<EncodedBlock> {
|
||||
fn encode_buffer(&self, data_buffer: BytesMut, data_len: usize) -> io::Result<EncodedBlock> {
|
||||
self.encode_buffer_mut(data_buffer, data_len).map(MutableEncodedBlock::freeze)
|
||||
}
|
||||
|
||||
#[hotpath::measure(impl_type = "Erasure")]
|
||||
pub(crate) fn encode_buffer_mut(&self, mut data_buffer: BytesMut, data_len: usize) -> io::Result<MutableEncodedBlock> {
|
||||
let shard_size_fn = if self.uses_legacy {
|
||||
calc_shard_size_legacy
|
||||
} else {
|
||||
@@ -1085,7 +1141,10 @@ impl Erasure {
|
||||
};
|
||||
let per_shard_size = shard_size_fn(data_len, self.data_shards);
|
||||
if per_shard_size == 0 {
|
||||
return Ok(EncodedBlock::empty());
|
||||
return Ok(MutableEncodedBlock {
|
||||
data: BytesMut::new(),
|
||||
shard_size: 0,
|
||||
});
|
||||
}
|
||||
let need_total_size = per_shard_size * self.total_shard_count();
|
||||
|
||||
@@ -1112,8 +1171,8 @@ impl Erasure {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(EncodedBlock {
|
||||
data: data_buffer.freeze(),
|
||||
Ok(MutableEncodedBlock {
|
||||
data: data_buffer,
|
||||
shard_size: per_shard_size,
|
||||
})
|
||||
}
|
||||
@@ -1315,17 +1374,16 @@ impl Erasure {
|
||||
calc_shard_size(self.block_size, self.data_shards)
|
||||
}
|
||||
}
|
||||
/// Calculate the total erasure file size for a given original size.
|
||||
// Returns the final erasure size from the original size
|
||||
/// Calculate the logical shard file size before bitrot framing.
|
||||
pub fn shard_file_size(&self, total_length: i64) -> i64 {
|
||||
if total_length == 0 {
|
||||
return 0;
|
||||
}
|
||||
if total_length < 0 {
|
||||
if total_length <= 0 {
|
||||
return total_length;
|
||||
}
|
||||
let total_length = usize::try_from(total_length).unwrap_or(usize::MAX);
|
||||
i64::try_from(self.shard_file_size_bytes(total_length)).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
let total_length = total_length as usize;
|
||||
fn shard_file_size_bytes(&self, total_length: usize) -> usize {
|
||||
let shard_size_fn = if self.uses_legacy {
|
||||
calc_shard_size_legacy
|
||||
} else {
|
||||
@@ -1335,21 +1393,24 @@ impl Erasure {
|
||||
let num_shards = total_length / self.block_size;
|
||||
let last_block_size = total_length % self.block_size;
|
||||
let last_shard_size = shard_size_fn(last_block_size, self.data_shards);
|
||||
(num_shards * self.shard_size() + last_shard_size) as i64
|
||||
num_shards.saturating_mul(self.shard_size()).saturating_add(last_shard_size)
|
||||
}
|
||||
|
||||
/// Calculate the offset in the erasure file where reading begins.
|
||||
// Returns the offset in the erasure file where reading begins
|
||||
/// Return the exclusive logical shard offset for the requested object bytes.
|
||||
/// Only stripes touched by the range are included, clipped to the final partial stripe.
|
||||
/// An empty range ends at the start of its stripe.
|
||||
pub fn shard_file_offset(&self, start_offset: usize, length: usize, total_length: usize) -> usize {
|
||||
let shard_size = self.shard_size();
|
||||
let shard_file_size = self.shard_file_size(total_length as i64) as usize;
|
||||
let end_shard = (start_offset + length) / self.block_size;
|
||||
let mut till_offset = end_shard * shard_size + shard_size;
|
||||
if till_offset > shard_file_size {
|
||||
till_offset = shard_file_size;
|
||||
let end = start_offset.saturating_add(length).min(total_length);
|
||||
let end_stripe = if length == 0 {
|
||||
end / self.block_size
|
||||
} else {
|
||||
end.div_ceil(self.block_size)
|
||||
};
|
||||
if end_stripe <= total_length / self.block_size {
|
||||
end_stripe.saturating_mul(self.shard_size())
|
||||
} else {
|
||||
self.shard_file_size_bytes(total_length)
|
||||
}
|
||||
|
||||
till_offset
|
||||
}
|
||||
|
||||
/// Encode all data from a reader in blocks, calling an async callback for each encoded block.
|
||||
@@ -2041,6 +2102,27 @@ mod tests {
|
||||
assert!(err.to_string().contains("invalid shard count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_shards_reuse_the_bytesmut_ingest_allocation() {
|
||||
for uses_legacy in [false, true] {
|
||||
let erasure = Erasure::new_with_options(2, 2, 128 * 1024, uses_legacy);
|
||||
let payload: Vec<_> = (0_u8..=250).cycle().take(128 * 1024).collect();
|
||||
let frame_size = erasure.encoded_capacity_for_data_len(payload.len())
|
||||
+ erasure.total_shard_count() * HashAlgorithm::HighwayHash256S.size();
|
||||
let mut buffer = BytesMut::with_capacity(frame_size);
|
||||
buffer.extend_from_slice(&payload);
|
||||
let allocation = buffer.as_ptr();
|
||||
let block = erasure
|
||||
.encode_buffer_mut(buffer, payload.len())
|
||||
.expect("preallocated data must encode");
|
||||
let shards = block.into_inline_shards().expect("inline framing must succeed");
|
||||
|
||||
assert_eq!(shards.len(), erasure.total_shard_count());
|
||||
assert_eq!(shards[0].as_ptr(), allocation, "inline framing must retain the encoded allocation");
|
||||
assert_eq!(shards.iter().map(Bytes::len).sum::<usize>(), frame_size);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_data_owned_matches_borrowed_path() {
|
||||
for uses_legacy in [false, true] {
|
||||
@@ -2830,14 +2912,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_shard_file_offset() {
|
||||
let erasure = Erasure::new(8, 8, 1024 * 1024);
|
||||
let offset = erasure.shard_file_offset(0, 86, 86);
|
||||
println!("offset={offset}");
|
||||
assert!(offset > 0);
|
||||
|
||||
let total_length = erasure.shard_file_size(86);
|
||||
println!("total_length={total_length}");
|
||||
assert!(total_length > 0);
|
||||
const BLOCK: usize = 256 * 1024;
|
||||
const TOTAL: usize = 3 * BLOCK + 19;
|
||||
for legacy in [false, true] {
|
||||
let erasure = Erasure::try_new_with_options(3, 3, BLOCK, legacy).expect("supported erasure layout");
|
||||
let shard_size = erasure.shard_size();
|
||||
let tail = if legacy { 8 } else { 7 };
|
||||
assert_eq!(erasure.shard_file_offset(0, 0, TOTAL), 0);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 1, 0, TOTAL), shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 7, TOTAL), 2 * shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 6, TOTAL), 3 * shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(3 * BLOCK, 1, TOTAL), 3 * shard_size + tail);
|
||||
assert_eq!(erasure.shard_file_offset(0, TOTAL, TOTAL), 3 * shard_size + tail);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -213,11 +213,9 @@ fn buffer_local_shard_stream(reader: ShardReader, length: usize) -> disk::error:
|
||||
// enlarge that reservation and allocate a second, unaccounted buffer.
|
||||
return Ok(ShardReader::Stream(Box::new(reader.take(limit))));
|
||||
}
|
||||
// Small layout stripes otherwise dispatch a blocking file read per frame.
|
||||
// Short ranges keep direct reads: the caller's conservative stream span
|
||||
// can include an extra stripe beyond the final requested block. Long
|
||||
// streams stay bounded to that span; prefetched frames still authenticate
|
||||
// individually when consumed by the bitrot reader.
|
||||
// Buffer long reads of small frames to avoid a blocking dispatch per frame.
|
||||
// Prefetch stays within the requested span, and each frame authenticates
|
||||
// when consumed by the bitrot reader.
|
||||
Ok(ShardReader::Stream(Box::new(tokio::io::BufReader::with_capacity(
|
||||
256 * 1024,
|
||||
reader.take(limit),
|
||||
@@ -1135,15 +1133,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_local_shard_stream_does_not_prefetch_conservative_short_range_tail() {
|
||||
async fn buffered_local_shard_stream_keeps_short_range_reads_direct() {
|
||||
const BLOCK: usize = 256 * 1024;
|
||||
const SHARD: usize = BLOCK / 2;
|
||||
let algo = HashAlgorithm::HighwayHash256S;
|
||||
let erasure = crate::erasure::coding::Erasure::new(2, 2, BLOCK);
|
||||
// An aligned 1 MiB Range consumes four data-shard frames, while the
|
||||
// existing reader planner conservatively opens five logical shards.
|
||||
let logical_window = erasure.shard_file_offset(0, 4 * BLOCK, 6 * BLOCK);
|
||||
assert_eq!(logical_window, 5 * SHARD);
|
||||
// A short stream may be consumed only in part before cancellation.
|
||||
let logical_window = 5 * SHARD;
|
||||
let (_, wire_window) = adjust_shard_read_params(0, logical_window, SHARD, &algo);
|
||||
let payload = vec![73; SHARD];
|
||||
let mut encoded = Vec::new();
|
||||
@@ -1152,10 +1147,7 @@ mod tests {
|
||||
for _ in 0..4 {
|
||||
writer.write(&payload).await.expect("encode requested range frames");
|
||||
}
|
||||
writer
|
||||
.write(&vec![99; SHARD])
|
||||
.await
|
||||
.expect("encode unrequested conservative tail frame");
|
||||
writer.write(&vec![99; SHARD]).await.expect("encode unread tail frame");
|
||||
}
|
||||
assert_eq!(encoded.len(), wire_window);
|
||||
let reads = Arc::new(AtomicUsize::new(0));
|
||||
@@ -1168,7 +1160,7 @@ mod tests {
|
||||
})),
|
||||
wire_window,
|
||||
)
|
||||
.expect("open conservative short range stream");
|
||||
.expect("open short range stream");
|
||||
let mut reader = BitrotReader::new(source, SHARD, algo.clone(), false);
|
||||
let mut output = Vec::new();
|
||||
for _ in 0..4 {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use crate::disk::{DiskAPI, DiskStore};
|
||||
use crate::disk::{DiskAPI, DiskStore, FileReader};
|
||||
use crate::erasure::codec::shard_buf::ShardBytes;
|
||||
use bytes::Bytes;
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
@@ -302,6 +302,18 @@ impl PreparedIntegrity {
|
||||
volume: &str,
|
||||
directory: &str,
|
||||
) -> io::Result<PartIntegrity> {
|
||||
self.write_with_quorum(disks, original_volume, volume, directory, None).await
|
||||
}
|
||||
|
||||
pub(crate) async fn write_with_quorum(
|
||||
self,
|
||||
disks: &mut [Option<DiskStore>],
|
||||
original_volume: &str,
|
||||
volume: &str,
|
||||
directory: &str,
|
||||
post_quorum_quorum: Option<usize>,
|
||||
) -> io::Result<PartIntegrity> {
|
||||
const INTEGRITY_POST_QUORUM_GRACE: std::time::Duration = std::time::Duration::from_millis(300);
|
||||
let length = self.part.index_size().map_err(|_| corrupt())?;
|
||||
let length_i64 = i64::try_from(length).map_err(|_| corrupt())?;
|
||||
let path = format!("{directory}/{}", self.part.file_name());
|
||||
@@ -316,6 +328,71 @@ impl PreparedIntegrity {
|
||||
}
|
||||
let payload = Bytes::from(bytes);
|
||||
let prewritten_disks = &self.prewritten_disks;
|
||||
if let Some(quorum) = post_quorum_quorum {
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
let mut succeeded = vec![false; disks.len()];
|
||||
let mut ok_count = 0usize;
|
||||
let mut pending = FuturesUnordered::new();
|
||||
for (idx, disk_opt) in disks.iter().enumerate() {
|
||||
if prewritten_disks.get(idx).copied().unwrap_or(false) && disk_opt.is_some() {
|
||||
succeeded[idx] = true;
|
||||
ok_count = ok_count.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
let Some(disk) = disk_opt.clone() else {
|
||||
continue;
|
||||
};
|
||||
let path = path.clone();
|
||||
let payload = payload.clone();
|
||||
pending.push(async move {
|
||||
let res = tokio::time::timeout(std::time::Duration::from_secs(60), async {
|
||||
let mut writer = disk
|
||||
.create_file(original_volume, volume, &path, length_i64)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
if let Some(local) = crate::disk::as_lazy_local_file_writer_mut(&mut *writer) {
|
||||
local.write_all_bytes(payload).await?;
|
||||
} else {
|
||||
writer.write_all(&payload).await?;
|
||||
}
|
||||
writer.shutdown().await
|
||||
})
|
||||
.await;
|
||||
(idx, matches!(res, Ok(Ok(()))))
|
||||
});
|
||||
}
|
||||
let mut grace_deadline = (ok_count >= quorum && !pending.is_empty())
|
||||
.then(|| tokio::time::Instant::now() + INTEGRITY_POST_QUORUM_GRACE);
|
||||
loop {
|
||||
let next = if let Some(deadline) = grace_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = pending.next() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => None,
|
||||
}
|
||||
} else {
|
||||
pending.next().await
|
||||
};
|
||||
let Some((idx, ok)) = next else {
|
||||
break;
|
||||
};
|
||||
if ok {
|
||||
succeeded[idx] = true;
|
||||
ok_count = ok_count.saturating_add(1);
|
||||
if grace_deadline.is_none() && ok_count >= quorum && !pending.is_empty() {
|
||||
grace_deadline = Some(tokio::time::Instant::now() + INTEGRITY_POST_QUORUM_GRACE);
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(pending);
|
||||
for (idx, disk_opt) in disks.iter_mut().enumerate() {
|
||||
if !succeeded[idx] {
|
||||
*disk_opt = None;
|
||||
}
|
||||
}
|
||||
return Ok(self.part);
|
||||
}
|
||||
futures::future::join_all(disks.iter_mut().enumerate().map(|(idx, disk_opt)| {
|
||||
let path = &path;
|
||||
let payload = payload.clone();
|
||||
@@ -350,21 +427,64 @@ impl PreparedIntegrity {
|
||||
}
|
||||
Spool::File(file) => file,
|
||||
};
|
||||
let mut writers = futures::future::join_all(disks.iter().map(|disk| async {
|
||||
match disk {
|
||||
Some(disk) => disk
|
||||
.create_file(original_volume, volume, &path, length_i64)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(io::Error::other),
|
||||
None => Ok(None),
|
||||
let mut writers = if let Some(quorum) = post_quorum_quorum {
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
let mut out: Vec<Option<_>> = std::iter::repeat_with(|| None).take(disks.len()).collect();
|
||||
let mut pending: FuturesUnordered<_> = disks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, disk)| {
|
||||
let disk = disk.clone()?;
|
||||
let path = path.clone();
|
||||
Some(async move {
|
||||
let w = disk.create_file(original_volume, volume, &path, length_i64).await.ok();
|
||||
(idx, w)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut ok_count = 0usize;
|
||||
let mut grace_deadline: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let next = if let Some(deadline) = grace_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = pending.next() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => None,
|
||||
}
|
||||
} else {
|
||||
pending.next().await
|
||||
};
|
||||
let Some((idx, writer)) = next else {
|
||||
break;
|
||||
};
|
||||
if writer.is_some() {
|
||||
ok_count = ok_count.saturating_add(1);
|
||||
}
|
||||
out[idx] = writer;
|
||||
if grace_deadline.is_none() && ok_count >= quorum && !pending.is_empty() {
|
||||
grace_deadline = Some(tokio::time::Instant::now() + INTEGRITY_POST_QUORUM_GRACE);
|
||||
}
|
||||
}
|
||||
}))
|
||||
.await
|
||||
.into_iter()
|
||||
.map(Result::ok)
|
||||
.map(Option::flatten)
|
||||
.collect::<Vec<_>>();
|
||||
drop(pending);
|
||||
out
|
||||
} else {
|
||||
futures::future::join_all(disks.iter().map(|disk| async {
|
||||
match disk {
|
||||
Some(disk) => disk
|
||||
.create_file(original_volume, volume, &path, length_i64)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(io::Error::other),
|
||||
None => Ok(None),
|
||||
}
|
||||
}))
|
||||
.await
|
||||
.into_iter()
|
||||
.map(Result::ok)
|
||||
.map(Option::flatten)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// The file has a single owner; duplicated descriptors share offsets.
|
||||
file = tokio::task::spawn_blocking(move || {
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
@@ -412,49 +532,58 @@ impl PreparedIntegrity {
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared, two-stripe cache coalesces the N readers' proof fetches. The only
|
||||
/// async lock is held across a bounded read from at most N replicas; it never
|
||||
/// nests another lock. A missing local index may use any authenticated replica.
|
||||
/// A shared, two-stripe cache coalesces the N readers' external proof fetches.
|
||||
/// A missing local index may use any authenticated replica.
|
||||
pub(crate) struct PartProofReader {
|
||||
pub(crate) part: PartIntegrity,
|
||||
sources: Vec<(DiskStore, String)>,
|
||||
volume: String,
|
||||
inline: Option<Bytes>,
|
||||
read_end: Option<u32>,
|
||||
cached: Mutex<ProofCache>,
|
||||
}
|
||||
|
||||
struct ProofWindow {
|
||||
next: u32,
|
||||
end: u32,
|
||||
reader: FileReader,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProofCache {
|
||||
records: std::collections::VecDeque<(u32, Bytes)>,
|
||||
preferred: usize,
|
||||
window: Option<ProofWindow>,
|
||||
}
|
||||
|
||||
type VerifiedStripeKey = (uuid::Uuid, [u8; 32], u32);
|
||||
// The root is checked against the complete descriptor during authentication.
|
||||
// A cache hit must carry the same geometry, part number, size and stripe count.
|
||||
type VerifiedStripeKey = (PartIntegrity, u32);
|
||||
const MAX_SHARED_CACHE_STRIPES: u32 = 4;
|
||||
const PROOF_WINDOW_STRIPES: u32 = 16;
|
||||
|
||||
static VERIFIED_STRIPE_RECORDS: std::sync::LazyLock<parking_lot::Mutex<std::collections::HashMap<VerifiedStripeKey, Bytes>>> =
|
||||
std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
|
||||
|
||||
fn get_verified_stripe_record(part: &PartIntegrity, stripe: u32) -> Option<Bytes> {
|
||||
VERIFIED_STRIPE_RECORDS
|
||||
.lock()
|
||||
.get(&(part.generation, part.root, stripe))
|
||||
.cloned()
|
||||
VERIFIED_STRIPE_RECORDS.lock().get(&(part.clone(), stripe)).cloned()
|
||||
}
|
||||
|
||||
fn put_verified_stripe_record(part: &PartIntegrity, stripe: u32, record: Bytes) {
|
||||
let mut map = VERIFIED_STRIPE_RECORDS.lock();
|
||||
let key = (part.clone(), stripe);
|
||||
if map.len() >= 4096
|
||||
&& let Some(evict_key) = map.keys().next().copied()
|
||||
&& let Some(evict_key) = map.keys().next().cloned()
|
||||
{
|
||||
map.remove(&evict_key);
|
||||
}
|
||||
map.insert((part.generation, part.root, stripe), record);
|
||||
map.insert(key, record);
|
||||
}
|
||||
|
||||
pub(crate) fn invalidate_verified_stripe_records(generation: uuid::Uuid) {
|
||||
VERIFIED_STRIPE_RECORDS
|
||||
.lock()
|
||||
.retain(|(stored_gen, _, _), _| *stored_gen != generation);
|
||||
.retain(|(part, _), _| part.generation != generation);
|
||||
}
|
||||
|
||||
impl PartProofReader {
|
||||
@@ -487,6 +616,7 @@ impl PartProofReader {
|
||||
disks: &[Option<DiskStore>],
|
||||
volume: &str,
|
||||
object: &str,
|
||||
read_end: Option<u32>,
|
||||
) -> io::Result<Arc<Self>> {
|
||||
part.validate().map_err(|_| corrupt())?;
|
||||
let mut sources = Vec::with_capacity(disks.len());
|
||||
@@ -528,73 +658,51 @@ impl PartProofReader {
|
||||
sources,
|
||||
volume: volume.to_owned(),
|
||||
inline,
|
||||
read_end,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) async fn record(&self, stripe: u32) -> io::Result<Bytes> {
|
||||
let offset = self.part.record_offset(stripe).map_err(|_| corrupt())?;
|
||||
if let Some(bytes) = get_verified_stripe_record(&self.part, stripe) {
|
||||
return Ok(bytes);
|
||||
let size = self.part.record_size();
|
||||
let end = self.read_end.unwrap_or(self.part.stripes).min(self.part.stripes);
|
||||
if stripe >= end {
|
||||
return Err(corrupt());
|
||||
}
|
||||
// Inline records are immutable and authenticated at construction.
|
||||
if let Some(inline) = &self.inline {
|
||||
return Ok(inline.slice(offset..offset + size));
|
||||
}
|
||||
let mut cached = self.cached.lock().await;
|
||||
if let Some((_, bytes)) = cached.records.iter().find(|(number, _)| *number == stripe) {
|
||||
return Ok(bytes.clone());
|
||||
}
|
||||
let size = self.part.record_size();
|
||||
let record = if let Some(inline) = &self.inline {
|
||||
inline.slice(offset..offset + size)
|
||||
let share = self.part.stripes <= MAX_SHARED_CACHE_STRIPES;
|
||||
let shared = if share {
|
||||
get_verified_stripe_record(&self.part, stripe)
|
||||
} else {
|
||||
let read = |index: usize| async move {
|
||||
let (disk, path) = &self.sources[index];
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||
let mut reader = disk
|
||||
.read_file_stream(&self.volume, path, offset, size)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let mut bytes = vec![0; size];
|
||||
reader.read_exact(&mut bytes).await?;
|
||||
self.part.verify_record(stripe, &bytes).map_err(|_| corrupt())?;
|
||||
io::Result::Ok(Bytes::from(bytes))
|
||||
})
|
||||
.await;
|
||||
(index, result)
|
||||
};
|
||||
if self.sources.is_empty() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let preferred = cached.preferred % self.sources.len();
|
||||
let mut pending = FuturesUnordered::new();
|
||||
pending.push(read(preferred));
|
||||
let first = tokio::select! {
|
||||
result = pending.next() => result,
|
||||
() = tokio::time::sleep(std::time::Duration::from_millis(50)) => None,
|
||||
};
|
||||
let mut found = match first {
|
||||
Some((index, Ok(Ok(bytes)))) => Some((index, bytes)),
|
||||
_ => None,
|
||||
};
|
||||
if found.is_none() {
|
||||
for index in 0..self.sources.len() {
|
||||
if index != preferred {
|
||||
pending.push(read(index));
|
||||
}
|
||||
}
|
||||
while let Some((index, result)) = pending.next().await {
|
||||
if let Ok(Ok(bytes)) = result {
|
||||
found = Some((index, bytes));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (index, bytes) = found.ok_or_else(corrupt)?;
|
||||
cached.preferred = index;
|
||||
bytes
|
||||
None
|
||||
};
|
||||
let record = if let Some(record) = shared {
|
||||
record
|
||||
} else {
|
||||
let window = cached.window.take().filter(|window| window.next == stripe);
|
||||
let end = if share {
|
||||
stripe + 1
|
||||
} else {
|
||||
end.min(stripe.saturating_add(PROOF_WINDOW_STRIPES))
|
||||
};
|
||||
let (replica, record, next_window) = self
|
||||
.read_verified_record(stripe, offset, size, end, cached.preferred, window)
|
||||
.await?;
|
||||
cached.preferred = replica;
|
||||
cached.window = next_window;
|
||||
if share {
|
||||
put_verified_stripe_record(&self.part, stripe, record.clone());
|
||||
}
|
||||
record
|
||||
};
|
||||
self.part.verify_record(stripe, &record).map_err(|_| corrupt())?;
|
||||
if self.part.stripes <= 4 {
|
||||
put_verified_stripe_record(&self.part, stripe, record.clone());
|
||||
}
|
||||
if cached.records.len() == 2 {
|
||||
cached.records.pop_front();
|
||||
}
|
||||
@@ -602,6 +710,92 @@ impl PartProofReader {
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
async fn read_verified_record(
|
||||
&self,
|
||||
stripe: u32,
|
||||
offset: usize,
|
||||
size: usize,
|
||||
end: u32,
|
||||
preferred: usize,
|
||||
window: Option<ProofWindow>,
|
||||
) -> io::Result<(usize, Bytes, Option<ProofWindow>)> {
|
||||
if self.sources.is_empty() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let read = |index: usize, window: Option<ProofWindow>| async move {
|
||||
let (disk, path) = &self.sources[index];
|
||||
tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||
let open = async |end: u32, bytes: &mut [u8]| {
|
||||
let count = usize::try_from(end - stripe).map_err(|_| corrupt())?;
|
||||
let length = size.checked_mul(count).ok_or_else(corrupt)?;
|
||||
#[cfg(test)]
|
||||
crate::set_disk::disk_call_counters::record_proof_stream_open(path, index);
|
||||
let reader = disk
|
||||
.read_file_stream(&self.volume, path, offset, length)
|
||||
.await
|
||||
.map_err(crate::disk::error::terminal_read_error_to_io)?;
|
||||
let mut reader = if count > 1 && disk.is_local() {
|
||||
Box::new(tokio::io::BufReader::with_capacity(length, reader)) as FileReader
|
||||
} else {
|
||||
reader
|
||||
};
|
||||
reader.read_exact(bytes).await?;
|
||||
io::Result::Ok(reader)
|
||||
};
|
||||
let mut bytes = vec![0; size];
|
||||
let next = stripe + 1;
|
||||
let continued = window.is_some();
|
||||
let (end, result) = if let Some(mut window) = window {
|
||||
let result = window.reader.read_exact(&mut bytes).await.map(|_| window.reader);
|
||||
(window.end, result)
|
||||
} else {
|
||||
(end, open(end, &mut bytes).await)
|
||||
};
|
||||
let (end, reader) = match result {
|
||||
Ok(reader) => (end, reader),
|
||||
// A truncated window or broken continuation can leave the
|
||||
// current record readable through a fresh exact request.
|
||||
Err(error)
|
||||
if (continued || end > next)
|
||||
&& !matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) =>
|
||||
{
|
||||
(next, open(next, &mut bytes).await?)
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
self.part.verify_record(stripe, &bytes).map_err(|_| corrupt())?;
|
||||
let window = (next < end).then_some(ProofWindow { next, end, reader });
|
||||
io::Result::Ok((index, Bytes::from(bytes), window))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?
|
||||
};
|
||||
let primary = read(preferred, window);
|
||||
tokio::pin!(primary);
|
||||
let mut primary_pending = match tokio::time::timeout(std::time::Duration::from_millis(50), primary.as_mut()).await {
|
||||
Ok(Ok(record)) => return Ok(record),
|
||||
Ok(_) => false,
|
||||
Err(_) => true,
|
||||
};
|
||||
let mut replicas: FuturesUnordered<_> = (0..self.sources.len())
|
||||
.filter(|&index| index != preferred)
|
||||
.map(|index| read(index, None))
|
||||
.collect();
|
||||
while primary_pending || !replicas.is_empty() {
|
||||
let result = tokio::select! {
|
||||
result = &mut primary, if primary_pending => {
|
||||
primary_pending = false;
|
||||
result
|
||||
}
|
||||
Some(result) = replicas.next() => result,
|
||||
};
|
||||
if let Ok(record) = result {
|
||||
return Ok(record);
|
||||
}
|
||||
}
|
||||
Err(corrupt())
|
||||
}
|
||||
|
||||
pub(crate) async fn verify(&self, stripe: u32, index: usize, payload: &[u8]) -> io::Result<()> {
|
||||
let record = self.record(stripe).await?;
|
||||
// Authentication of the shared record is cached; payload digests are
|
||||
@@ -715,7 +909,7 @@ pub(crate) async fn verify_deep_parts(
|
||||
let read_timeout = crate::disk::disk_store::get_object_disk_read_timeout();
|
||||
for (part_index, part) in expected.parts.iter().enumerate() {
|
||||
let commitment = part.integrity.as_ref().ok_or(DiskError::FileCorrupt)?;
|
||||
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object).map_err(DiskError::from)?;
|
||||
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object, None).map_err(DiskError::from)?;
|
||||
if commitment.stripes == 0 && commitment.root != commitment.root_digest(&commitment.padding_digest(0)) {
|
||||
return Err(DiskError::FileCorrupt);
|
||||
}
|
||||
@@ -855,6 +1049,7 @@ pub(crate) async fn restore_proof_replicas(
|
||||
sources: disks.iter().flatten().map(|disk| (disk.clone(), path.clone())).collect(),
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let prepared = PreparedIntegrity::copy_from(&proof).await.map_err(DiskError::from)?;
|
||||
@@ -939,6 +1134,7 @@ mod tests {
|
||||
sources: vec![],
|
||||
volume: "bucket".to_owned(),
|
||||
inline: Some(bytes),
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
});
|
||||
let mut verifier = ShardVerifier::new(proof, 0, 0, None).expect("verifier");
|
||||
@@ -959,6 +1155,7 @@ mod tests {
|
||||
let proof = PartProofReader {
|
||||
part: prepared.part,
|
||||
inline: Some(index),
|
||||
read_end: None,
|
||||
sources: Vec::new(),
|
||||
volume: String::new(),
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
@@ -998,36 +1195,36 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn verified_stripe_record_cache_serves_verified_record_and_still_verifies_payload() {
|
||||
async fn verified_stripe_record_cache_requires_exact_part_descriptor_and_verifies_payload() {
|
||||
let layout = IntegrityLayout::new(2, 2, 8, false).expect("layout");
|
||||
let mut builder = IntegrityBuilder::new(layout, 1).expect("builder");
|
||||
let shards = [b"ABCD".as_slice(), b"EFGH", b"IJKL", b"MNOP"];
|
||||
builder.push(shards.into_iter()).await.expect("stripe");
|
||||
let prepared = builder.finish(8).await.expect("index");
|
||||
let inline_bytes = prepared.inline_bytes().expect("inline bytes");
|
||||
builder.push(shards.into_iter()).await.expect("next stripe");
|
||||
let prepared = builder.finish(16).await.expect("index");
|
||||
let bytes = prepared.inline_bytes().expect("index bytes");
|
||||
let part = prepared.part;
|
||||
let offset = part.record_offset(0).expect("record offset");
|
||||
let record = bytes.slice(offset..offset + part.record_size());
|
||||
part.verify_record(0, &record)
|
||||
.expect("cache admission requires the exact descriptor");
|
||||
put_verified_stripe_record(&part, 0, record);
|
||||
|
||||
let warm_reader = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: Vec::new(),
|
||||
volume: "bucket".to_owned(),
|
||||
inline: Some(inline_bytes),
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
warm_reader.verify(0, 0, shards[0]).await.expect("warm verify");
|
||||
let mut shortened = part.clone();
|
||||
shortened.size = 8;
|
||||
shortened.stripes = 1;
|
||||
let mismatched_reader = PartProofReader::new(shortened, &[], &[], "bucket", "object", None)
|
||||
.expect("the altered descriptor is structurally valid");
|
||||
assert!(
|
||||
get_verified_stripe_record(&part, 0).is_some(),
|
||||
"small verified stripe record should populate the verified stripe cache"
|
||||
mismatched_reader.verify(0, 0, shards[0]).await.is_err(),
|
||||
"a matching generation and root must not admit a shortened part"
|
||||
);
|
||||
|
||||
let cached_reader = Arc::new(PartProofReader {
|
||||
part,
|
||||
sources: Vec::new(),
|
||||
volume: "bucket".to_owned(),
|
||||
inline: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
});
|
||||
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object", None).expect("matching descriptor");
|
||||
cached_reader.verify(0, 0, shards[0]).await.expect("cached verify");
|
||||
invalidate_verified_stripe_records(part.generation);
|
||||
assert!(get_verified_stripe_record(&part, 0).is_none());
|
||||
cached_reader.verify(0, 0, shards[0]).await.expect("request-local verify");
|
||||
assert!(
|
||||
cached_reader.verify(0, 0, shards[1]).await.is_err(),
|
||||
"cached record must still reject corrupt or mismatched shard payloads"
|
||||
@@ -1047,6 +1244,7 @@ mod tests {
|
||||
sources: Vec::new(),
|
||||
volume: "bucket".to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
});
|
||||
|
||||
@@ -1067,6 +1265,128 @@ mod tests {
|
||||
assert!(err.to_string().contains("shard integrity verification failed"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proof_stream_reuses_bounded_windows_and_recovers_from_damaged_replicas() {
|
||||
use crate::set_disk::disk_call_counters;
|
||||
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
|
||||
let disks = store.pools[0].disk_set[0].get_local_disks().await;
|
||||
let volume = "proof-window";
|
||||
let path = "part.integrity";
|
||||
let mut builder = IntegrityBuilder::new(IntegrityLayout::new(1, 1, 8, false).expect("layout"), 1).expect("builder");
|
||||
for _ in 0..20 {
|
||||
builder.push([b"abcdefgh".as_slice(); 2].into_iter()).await.expect("stripe");
|
||||
}
|
||||
let prepared = builder.finish(160).await.expect("index");
|
||||
let bytes = prepared.inline_bytes().expect("small proof index");
|
||||
let part = prepared.part;
|
||||
let sources: Vec<_> = disks.into_iter().flatten().map(|disk| (disk, path.to_owned())).collect();
|
||||
assert_eq!(sources.len(), 2);
|
||||
for (disk, path) in &sources {
|
||||
disk.make_volume(volume).await.expect("create volume");
|
||||
disk.write_all(volume, path, bytes.clone())
|
||||
.await
|
||||
.expect("write full proof index");
|
||||
}
|
||||
|
||||
let proof = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: vec![sources[0].clone()],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: Some(19),
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let calls = disk_call_counters::observe(path);
|
||||
for stripe in 2..19 {
|
||||
proof.verify(stripe, 0, b"abcdefgh").await.expect("verify requested stripe");
|
||||
}
|
||||
assert!(proof.cached.lock().await.window.is_none(), "the range ends inside the part");
|
||||
assert!(proof.record(19).await.is_err(), "the request must not fetch a stripe outside its range");
|
||||
assert_eq!(calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN), 2, "17 stripes need two streams");
|
||||
drop(calls);
|
||||
|
||||
let (mut stalled_writer, stalled_reader) = tokio::io::duplex(64);
|
||||
let hedged = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: sources.clone(),
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache {
|
||||
window: Some(ProofWindow {
|
||||
next: 2,
|
||||
end: 18,
|
||||
reader: Box::new(stalled_reader),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
hedged
|
||||
.verify(2, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("a healthy replica must replace a stalled continuation");
|
||||
assert_eq!(hedged.cached.lock().await.preferred, 1);
|
||||
assert_eq!(
|
||||
stalled_writer
|
||||
.write_u8(0)
|
||||
.await
|
||||
.expect_err("the losing continuation must be dropped")
|
||||
.kind(),
|
||||
io::ErrorKind::BrokenPipe
|
||||
);
|
||||
|
||||
let missing_path = "missing-part.integrity";
|
||||
let missing = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: vec![(sources[0].0.clone(), missing_path.to_owned())],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let calls = disk_call_counters::observe(missing_path);
|
||||
assert!(missing.record(2).await.is_err(), "a missing sidecar cannot authenticate the record");
|
||||
assert_eq!(
|
||||
calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN),
|
||||
1,
|
||||
"a shorter read cannot open a missing file"
|
||||
);
|
||||
drop(calls);
|
||||
|
||||
let short_end = part.record_offset(4).expect("end of shortened index");
|
||||
let corrupt_offset = part.record_offset(3).expect("record offset");
|
||||
let mut damaged = bytes[..short_end].to_vec();
|
||||
damaged[corrupt_offset] ^= 1;
|
||||
sources[0]
|
||||
.0
|
||||
.write_all(volume, path, Bytes::from(damaged))
|
||||
.await
|
||||
.expect("damage preferred replica");
|
||||
let degraded = PartProofReader {
|
||||
part,
|
||||
sources: vec![sources[0].clone()],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
degraded
|
||||
.verify(2, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("intact record in a truncated replica");
|
||||
{
|
||||
let cached = degraded.cached.lock().await;
|
||||
assert_eq!(cached.preferred, 0, "a truncated suffix must not reject a valid requested record");
|
||||
assert!(cached.window.is_none());
|
||||
}
|
||||
let degraded = PartProofReader { sources, ..degraded };
|
||||
degraded
|
||||
.verify(3, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("recover the corrupt record from another replica");
|
||||
assert_eq!(degraded.cached.lock().await.preferred, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spilled_index_write_verify_and_restore_proof_replicas_round_trip() {
|
||||
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
|
||||
|
||||
@@ -26,6 +26,10 @@ use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use tokio::sync::{Mutex, Notify, OwnedRwLockReadGuard};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Internal metadata suffix preserving an object's initial logical body revision
|
||||
/// across pool data movement (`rebalance` / `decommission`).
|
||||
pub const LOGICAL_BODY_REVISION_SUFFIX: &str = "logical-body-revision-v1";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NamespaceLockFence {
|
||||
signals: Arc<Vec<Arc<rustfs_lock::distributed_lock::LockLostSignal>>>,
|
||||
@@ -1130,6 +1134,7 @@ impl std::fmt::Debug for GetObjectSinkSegments {
|
||||
struct GetObjectSinkInner {
|
||||
writer: Option<GetObjectSinkWriter>,
|
||||
segments: Option<GetObjectSinkSegments>,
|
||||
max_bytes: Option<u64>,
|
||||
taken: bool,
|
||||
}
|
||||
|
||||
@@ -1148,6 +1153,7 @@ impl GetObjectSink {
|
||||
inner: Arc::new(std::sync::Mutex::new(GetObjectSinkInner {
|
||||
writer: Some(writer),
|
||||
segments: None,
|
||||
max_bytes: None,
|
||||
taken: false,
|
||||
})),
|
||||
}
|
||||
@@ -1159,11 +1165,24 @@ impl GetObjectSink {
|
||||
inner: Arc::new(std::sync::Mutex::new(GetObjectSinkInner {
|
||||
writer: Some(writer),
|
||||
segments: Some(segments),
|
||||
max_bytes: None,
|
||||
taken: false,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounds the resolved response byte count accepted before the sink is taken.
|
||||
#[must_use]
|
||||
pub fn with_max_bytes(self, max_bytes: u64) -> Self {
|
||||
self.lock().max_bytes = Some(max_bytes);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum response byte count this sink can hold, when bounded.
|
||||
pub fn max_bytes(&self) -> Option<u64> {
|
||||
self.lock().max_bytes
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, GetObjectSinkInner> {
|
||||
self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
@@ -1628,6 +1647,14 @@ impl ObjectOptions {
|
||||
self.version_id.is_some() || !self.versioned || self.version_suspended
|
||||
}
|
||||
|
||||
/// Version slot replaced by a PUT. A fresh named version has no predecessor.
|
||||
pub(crate) fn replaced_version_id(&self) -> crate::error::Result<Option<Uuid>> {
|
||||
if let Some(id) = self.version_id.as_deref() {
|
||||
return Ok(Some(Uuid::parse_str(id)?));
|
||||
}
|
||||
Ok(self.overwrites_existing_version().then(Uuid::nil))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn add_namespace_lock_lost_signal(&mut self, signal: Arc<rustfs_lock::distributed_lock::LockLostSignal>) {
|
||||
#[cfg(test)]
|
||||
@@ -1730,6 +1757,10 @@ impl ObjectOptions {
|
||||
.unwrap_or(ReplicationStatusType::Empty)
|
||||
}
|
||||
|
||||
pub(crate) fn is_inbound_multipart_replica(&self) -> bool {
|
||||
self.replication_request || self.delete_marker_replication_status() == ReplicationStatusType::Replica
|
||||
}
|
||||
|
||||
pub fn put_replication_state(&self) -> ReplicationState {
|
||||
if self
|
||||
.delete_replication
|
||||
@@ -1868,6 +1899,8 @@ pub struct ObjectInfo {
|
||||
/// published by the same upload. Callers must not repeat quota, replication,
|
||||
/// lifecycle, or object-created side effects for that response.
|
||||
pub multipart_completion_replayed: bool,
|
||||
/// Logical usage observed under the object locks for this PUT.
|
||||
pub put_usage: Option<crate::data_usage::PutUsageReceipt>,
|
||||
/// Previous current version's size observed during `rename_data` commit.
|
||||
pub backfilled_old_current_size: Option<crate::disk::OldCurrentSize>,
|
||||
/// Persisted EC block size of a local version, projected from its erasure
|
||||
@@ -1918,6 +1951,7 @@ impl Default for ObjectInfo {
|
||||
replication_decision: String::new(),
|
||||
checksum: None,
|
||||
multipart_completion_replayed: false,
|
||||
put_usage: None,
|
||||
backfilled_old_current_size: None,
|
||||
ec_block_size: None,
|
||||
}
|
||||
@@ -1963,6 +1997,7 @@ impl Clone for ObjectInfo {
|
||||
replication_decision: self.replication_decision.clone(),
|
||||
checksum: self.checksum.clone(),
|
||||
multipart_completion_replayed: self.multipart_completion_replayed,
|
||||
put_usage: self.put_usage,
|
||||
backfilled_old_current_size: self.backfilled_old_current_size,
|
||||
ec_block_size: self.ec_block_size,
|
||||
expires: self.expires,
|
||||
@@ -2283,6 +2318,16 @@ impl ObjectInfo {
|
||||
.unwrap_or_else(|_| self.size.max(0))
|
||||
}
|
||||
|
||||
/// Logical body revision preserved across pool data movement (`rebalance` /
|
||||
/// `decommission`), falling back to physical `data_dir` when no internal
|
||||
/// logical revision marker is present.
|
||||
pub fn logical_body_revision(&self) -> Option<Uuid> {
|
||||
rustfs_utils::http::get_consistent_str(&self.user_defined, LOGICAL_BODY_REVISION_SUFFIX)
|
||||
.and_then(|value| Uuid::parse_str(value.trim()).ok())
|
||||
.filter(|id| !id.is_nil())
|
||||
.or_else(|| self.data_dir.filter(|id| !id.is_nil()))
|
||||
}
|
||||
|
||||
pub fn from_file_info(fi: &FileInfo, bucket: &str, object: &str, versioned: bool) -> ObjectInfo {
|
||||
let mut version_id = fi.version_id;
|
||||
|
||||
|
||||
@@ -22,22 +22,27 @@ use std::time::Duration;
|
||||
///
|
||||
/// Callers cannot fabricate a guard without acquiring its namespace lock.
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// ```compile_fail,E0451
|
||||
/// use rustfs_ecstore::api::object::WriteCommitGuard;
|
||||
/// use std::sync::Arc;
|
||||
///
|
||||
/// let guard = WriteCommitGuard {
|
||||
/// bucket: "bucket".into(),
|
||||
/// object: "object".into(),
|
||||
/// guards: Arc::new(Vec::new()),
|
||||
/// };
|
||||
/// fn fabricate(guard: Arc<rustfs_lock::NamespaceLockGuard>) -> WriteCommitGuard {
|
||||
/// WriteCommitGuard { bucket: "bucket".into(), object: "object".into(), guard, backend: None }
|
||||
/// }
|
||||
/// ```
|
||||
#[doc(hidden)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WriteCommitGuard {
|
||||
bucket: Arc<str>,
|
||||
object: Arc<str>,
|
||||
guards: Arc<Vec<Arc<rustfs_lock::NamespaceLockGuard>>>,
|
||||
guard: Arc<rustfs_lock::NamespaceLockGuard>,
|
||||
backend: Option<BorrowedWriteBackend>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum BorrowedWriteBackend {
|
||||
Object(rustfs_lock::namespace::WriteLockBackend),
|
||||
Version,
|
||||
}
|
||||
|
||||
impl WriteCommitGuard {
|
||||
@@ -46,27 +51,42 @@ impl WriteCommitGuard {
|
||||
lock: &rustfs_lock::NamespaceLockWrapper,
|
||||
timeout: Duration,
|
||||
) -> std::result::Result<Self, rustfs_lock::LockError> {
|
||||
let guard = Arc::new(lock.get_write_lock(timeout).await?);
|
||||
let guard = Arc::new(lock.get_write_lock_extending(timeout, &[]).await?);
|
||||
let key = lock.resource();
|
||||
Ok(Self::from_guard(guard, &key.bucket, &key.object))
|
||||
let mut owner = Self::from_guard(guard, &key.bucket, &key.object);
|
||||
owner.backend = Some(if key.version.is_none() {
|
||||
BorrowedWriteBackend::Object(lock.write_backend())
|
||||
} else {
|
||||
BorrowedWriteBackend::Version
|
||||
});
|
||||
Ok(owner)
|
||||
}
|
||||
|
||||
pub(crate) fn from_guard(guard: Arc<rustfs_lock::NamespaceLockGuard>, bucket: &str, object: &str) -> Self {
|
||||
Self {
|
||||
bucket: bucket.into(),
|
||||
object: object_name_disk_identity(object).as_ref().into(),
|
||||
guards: Arc::new(vec![guard]),
|
||||
guard,
|
||||
backend: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the loss signal of the namespace owner retained by acquisition.
|
||||
#[doc(hidden)]
|
||||
pub fn lock_lost_signal(&self) -> Option<Arc<rustfs_lock::distributed_lock::LockLostSignal>> {
|
||||
self.guards.first().and_then(|guard| guard.lock_lost_signal())
|
||||
self.guard.lock_lost_signal()
|
||||
}
|
||||
|
||||
pub fn is_lock_lost(&self) -> bool {
|
||||
self.guards.iter().any(|guard| guard.is_lock_lost() || guard.is_released())
|
||||
self.guard.is_lock_lost() || self.guard.is_released()
|
||||
}
|
||||
|
||||
fn owners_for(guards: &[Self], bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
guards
|
||||
.iter()
|
||||
.filter(|guard| guard.matches(bucket, object))
|
||||
.map(|guard| Arc::clone(&guard.guard))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Namespace locks key the disk identity of the name (see `new_ns_lock`),
|
||||
@@ -150,6 +170,13 @@ impl WriteCommitContext {
|
||||
matches!(self, Self::Borrowed(_))
|
||||
}
|
||||
|
||||
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
match self {
|
||||
Self::Borrowed(guards) => WriteCommitGuard::owners_for(guards, bucket, object),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_lock_lost(&self) -> bool {
|
||||
matches!(self, Self::Borrowed(guards) if guards.iter().any(WriteCommitGuard::is_lock_lost))
|
||||
}
|
||||
@@ -160,24 +187,62 @@ impl WriteCommitContext {
|
||||
}
|
||||
|
||||
impl ObjectOptions {
|
||||
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
|
||||
for owner in guard.guards.iter() {
|
||||
self.add_namespace_lock_guard(owner);
|
||||
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
match self.write_lock_context.as_ref().map(|context| &context.mode) {
|
||||
Some(WriteLockMode::Borrowed(guards)) => WriteCommitGuard::owners_for(guards, bucket, object),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn borrows_fixed_write_lock(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
lock: &rustfs_lock::NamespaceLockWrapper,
|
||||
) -> Result<bool> {
|
||||
let Some(WriteLockContext {
|
||||
mode: WriteLockMode::Borrowed(guards),
|
||||
}) = self.write_lock_context.as_ref()
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let mut borrowed = false;
|
||||
for guard in guards.iter().filter(|guard| guard.matches(bucket, object)) {
|
||||
if let Some(backend) = &guard.backend {
|
||||
if !matches!(backend, BorrowedWriteBackend::Object(held) if held.matches(lock)) {
|
||||
return Err(Error::InvalidArgument(
|
||||
bucket.to_owned(),
|
||||
object.to_owned(),
|
||||
"borrowed write guard does not own the fixed object namespace".to_owned(),
|
||||
));
|
||||
}
|
||||
if guard.is_lock_lost() {
|
||||
return Err(Error::NamespaceLockQuorumUnavailable {
|
||||
mode: "put_object_outer_lock",
|
||||
bucket: bucket.to_owned(),
|
||||
object: object.to_owned(),
|
||||
required: 1,
|
||||
achieved: 0,
|
||||
});
|
||||
}
|
||||
borrowed = true;
|
||||
}
|
||||
}
|
||||
Ok(borrowed)
|
||||
}
|
||||
|
||||
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
|
||||
self.add_namespace_lock_guard(&guard.guard);
|
||||
let mut guards = match self.write_lock_context.as_ref() {
|
||||
Some(WriteLockContext {
|
||||
mode: WriteLockMode::Borrowed(existing),
|
||||
}) => existing.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if let Some(existing) = guards.iter_mut().find(|held| held.matches(&guard.bucket, &guard.object)) {
|
||||
let owners = Arc::make_mut(&mut existing.guards);
|
||||
for owner in guard.guards.iter() {
|
||||
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
|
||||
owners.push(Arc::clone(owner));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if !guards
|
||||
.iter()
|
||||
.any(|held| Arc::ptr_eq(&held.guard, &guard.guard) && held.matches(&guard.bucket, &guard.object))
|
||||
{
|
||||
guards.push(guard.clone());
|
||||
}
|
||||
self.no_lock = true;
|
||||
|
||||
@@ -207,13 +207,16 @@ impl ListReadBudget {
|
||||
}
|
||||
}
|
||||
|
||||
fn weight(&self, fanout: usize) -> usize {
|
||||
// Admit a full walk even when its fanout exceeds the configured budget.
|
||||
fanout.max(1).min(self.capacity)
|
||||
}
|
||||
|
||||
async fn acquire(&self, fanout: usize) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
|
||||
if self.capacity == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
// A single walk must remain admissible even when the topology exceeds
|
||||
// the configured budget. Tokio accepts at most u32::MAX in one grant.
|
||||
let weight = u32::try_from(fanout.max(1).min(self.capacity)).unwrap_or(u32::MAX);
|
||||
let weight = u32::try_from(self.weight(fanout)).unwrap_or(u32::MAX);
|
||||
self.permits
|
||||
.clone()
|
||||
.acquire_many_owned(weight)
|
||||
@@ -420,6 +423,8 @@ pub struct InstanceContext {
|
||||
/// caller (for example, an S3 client disconnect) cannot stop them between
|
||||
/// their on-disk steps. Shutdown waits for them after the HTTP drain.
|
||||
detached_mutations: TaskTracker,
|
||||
/// Limits v1 settlements that may outlive a successful object response.
|
||||
pub(crate) v1_quota_settlement_slots: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl InstanceContext {
|
||||
@@ -491,6 +496,12 @@ impl InstanceContext {
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn list_read_budget_has_capacity(&self, fanout: usize) -> Option<bool> {
|
||||
self.list_read_budget
|
||||
.get()
|
||||
.map(|budget| budget.permits.available_permits() >= budget.weight(fanout))
|
||||
}
|
||||
|
||||
/// Build a context bound to a specific lock manager.
|
||||
///
|
||||
/// [`bootstrap_ctx`] uses this to alias the process-global lock manager so
|
||||
@@ -553,6 +564,7 @@ impl InstanceContext {
|
||||
transition_transaction_recovery_stores: std::sync::Mutex::new(HashSet::new()),
|
||||
tier_delete_journal_recovery_wakeup: tokio::sync::Notify::new(),
|
||||
detached_mutations: TaskTracker::new(),
|
||||
v1_quota_settlement_slots: Arc::new(Semaphore::new(64)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -576,6 +588,14 @@ impl InstanceContext {
|
||||
/// the mutation, together with the locks and guards it owns, never stops
|
||||
/// between two of its on-disk steps because its caller went away.
|
||||
pub(crate) async fn run_detached_mutation<F>(&self, mutation: F) -> Result<F::Output, tokio::task::JoinError>
|
||||
where
|
||||
F: std::future::Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
{
|
||||
self.spawn_detached_mutation(mutation).await
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_detached_mutation<F>(&self, mutation: F) -> tokio::task::JoinHandle<F::Output>
|
||||
where
|
||||
F: std::future::Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
@@ -590,7 +610,7 @@ impl InstanceContext {
|
||||
let context = rustfs_io_metrics::s3_http_metrics::current_s3_http_operation_context();
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
let mutation = rustfs_io_metrics::s3_http_metrics::with_s3_http_operation_context(context, mutation);
|
||||
self.detached_mutations.spawn(mutation.in_current_span()).await
|
||||
self.detached_mutations.spawn(mutation.in_current_span())
|
||||
}
|
||||
|
||||
/// Wait up to `timeout` for every detached mutation to finish. Returns
|
||||
@@ -1575,8 +1595,16 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_read_budget_zero_preserves_unbounded_configuration() {
|
||||
let budget = ListReadBudget::new(0);
|
||||
assert!(budget.acquire(usize::MAX).await.expect("disabled budget").is_none());
|
||||
let ctx = InstanceContext::new();
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(1), None);
|
||||
ctx.list_read_budget.set(ListReadBudget::new(0)).expect("fresh context");
|
||||
assert!(
|
||||
ctx.acquire_list_read_budget(usize::MAX)
|
||||
.await
|
||||
.expect("disabled budget")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(usize::MAX), Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1611,6 +1639,8 @@ mod tests {
|
||||
let other = InstanceContext::new();
|
||||
other.list_read_budget.set(ListReadBudget::new(4)).expect("fresh context");
|
||||
let held = first.acquire_list_read_budget(4).await.expect("first context");
|
||||
assert_eq!(same.list_read_budget_has_capacity(4), Some(false));
|
||||
assert_eq!(other.list_read_budget_has_capacity(4), Some(true));
|
||||
let mut waiter = std::pin::pin!(same.acquire_list_read_budget(1));
|
||||
assert!(futures::poll!(&mut waiter).is_pending());
|
||||
assert!(
|
||||
@@ -1622,6 +1652,18 @@ mod tests {
|
||||
);
|
||||
drop(held);
|
||||
assert!(waiter.await.expect("shared context resumed").is_some());
|
||||
assert_eq!(same.list_read_budget_has_capacity(4), Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_read_budget_reports_capacity_for_the_requested_fanout() {
|
||||
let ctx = InstanceContext::new();
|
||||
ctx.list_read_budget.set(ListReadBudget::new(64)).expect("fresh context");
|
||||
let held = ctx.acquire_list_read_budget(48).await.expect("first walk");
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(16), Some(true));
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(false));
|
||||
drop(held);
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -833,11 +833,13 @@ impl BitrotReaderSetup {
|
||||
disks: &[Option<DiskStore>],
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
first_stripe: usize,
|
||||
stripes: std::ops::Range<usize>,
|
||||
) -> std::io::Result<()> {
|
||||
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
|
||||
let Some(expected) = expected else { return Ok(()) };
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
|
||||
let first_stripe = stripes.start;
|
||||
let end_stripe = u32::try_from(stripes.end).map_err(std::io::Error::other)?;
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(end_stripe))?;
|
||||
for (index, reader) in self.readers.iter_mut().enumerate() {
|
||||
if let Some(reader) = reader {
|
||||
let advanced = self.deferred_stripe_handles[index]
|
||||
@@ -4421,19 +4423,60 @@ impl SetDisks {
|
||||
object: &str,
|
||||
write_quorum: usize,
|
||||
) -> Result<(Vec<Option<DiskStore>>, Vec<Option<SnapshotLeaseToken>>)> {
|
||||
const QUOTA_FENCE_POST_QUORUM_GRACE: Duration = Duration::from_millis(300);
|
||||
let fence_path = disk::quota_mutation_fence_path(bucket, object);
|
||||
let results = join_all(disks.iter().map(|disk| {
|
||||
let disk = disk.clone();
|
||||
let fence_path = fence_path.clone();
|
||||
async move {
|
||||
let disk = disk?;
|
||||
match disk.acquire_snapshot_lease(RUSTFS_META_BUCKET, &fence_path).await {
|
||||
Ok(token) => Some((disk, token)),
|
||||
Err(_) => None,
|
||||
let mut results: Vec<Option<(DiskStore, SnapshotLeaseToken)>> = vec![None; disks.len()];
|
||||
let mut pending: futures::stream::FuturesUnordered<_> = disks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, disk)| {
|
||||
let disk = disk.clone()?;
|
||||
let fence_path = fence_path.clone();
|
||||
Some(async move {
|
||||
let lease = disk
|
||||
.acquire_snapshot_lease(RUSTFS_META_BUCKET, &fence_path)
|
||||
.await
|
||||
.ok()
|
||||
.map(|token| (disk, token));
|
||||
(idx, lease)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut acquired = 0usize;
|
||||
let mut grace_deadline: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let next = if let Some(deadline) = grace_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = futures::StreamExt::next(&mut pending) => item,
|
||||
_ = tokio::time::sleep_until(deadline) => None,
|
||||
}
|
||||
} else {
|
||||
futures::StreamExt::next(&mut pending).await
|
||||
};
|
||||
let Some((idx, lease)) = next else {
|
||||
break;
|
||||
};
|
||||
if lease.is_some() {
|
||||
acquired = acquired.saturating_add(1);
|
||||
}
|
||||
}))
|
||||
.await;
|
||||
results[idx] = lease;
|
||||
if grace_deadline.is_none() && acquired >= write_quorum && !pending.is_empty() {
|
||||
grace_deadline = Some(tokio::time::Instant::now() + QUOTA_FENCE_POST_QUORUM_GRACE);
|
||||
}
|
||||
}
|
||||
if !pending.is_empty() {
|
||||
let cleanup_fence_path = fence_path.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some((_, lease)) = futures::StreamExt::next(&mut pending).await {
|
||||
if let Some((disk, token)) = lease {
|
||||
let _ = disk
|
||||
.release_snapshot_lease(RUSTFS_META_BUCKET, &cleanup_fence_path, token)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if results.iter().flatten().count() < write_quorum {
|
||||
for (disk, token) in results.iter().flatten() {
|
||||
let _ = disk.release_snapshot_lease(RUSTFS_META_BUCKET, &fence_path, *token).await;
|
||||
@@ -5581,16 +5624,22 @@ impl SetDisks {
|
||||
let plan = producers.plan();
|
||||
let mut results = Vec::with_capacity(disk_count);
|
||||
let mut successful = 0;
|
||||
let mut accept = |outcome: SlotRenameOutcome| {
|
||||
if let Some(tx) = dispatch_deadline_tx.as_ref()
|
||||
&& matches!(&outcome.completion, Ok(Ok(_)))
|
||||
{
|
||||
let mut post_quorum_completion_deadline: Option<tokio::time::Instant> = None;
|
||||
let mut post_quorum_detached = false;
|
||||
const PUT_RENAME_POST_QUORUM_COMPLETION_GRACE: Duration = Duration::from_millis(500);
|
||||
let mut accept = |outcome: SlotRenameOutcome| -> Option<tokio::time::Instant> {
|
||||
let mut armed_deadline = None;
|
||||
if matches!(&outcome.completion, Ok(Ok(_))) {
|
||||
successful += 1;
|
||||
if successful == write_quorum {
|
||||
if let Some(tx) = dispatch_deadline_tx.as_ref()
|
||||
&& successful == write_quorum
|
||||
{
|
||||
tx.send_replace(Some(tokio::time::Instant::now() + PUT_RENAME_POST_QUORUM_DISPATCH_GRACE));
|
||||
armed_deadline = Some(tokio::time::Instant::now() + PUT_RENAME_POST_QUORUM_COMPLETION_GRACE);
|
||||
}
|
||||
}
|
||||
results.push(outcome);
|
||||
armed_deadline
|
||||
};
|
||||
// Publication-scoped and protected multipart renames retain the
|
||||
// streamed path. A pure unary plan returns one outcome per task.
|
||||
@@ -5613,25 +5662,77 @@ impl SetDisks {
|
||||
tasks.spawn(crate::disk::with_detached_disk_io_context(producer));
|
||||
}
|
||||
drop((producers, resource_unit, successful_completion_rank));
|
||||
while let Some(joined) = tasks.join_next().await {
|
||||
loop {
|
||||
let joined = if let Some(deadline) = post_quorum_completion_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = tasks.join_next() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
if !tasks.is_empty() {
|
||||
post_quorum_detached = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tasks.join_next().await
|
||||
};
|
||||
let Some(joined) = joined else { break };
|
||||
// A missing outcome still has the original conservative rollback state.
|
||||
if let Ok(outcome) = joined {
|
||||
accept(outcome);
|
||||
if let Ok(outcome) = joined
|
||||
&& let Some(deadline) = accept(outcome)
|
||||
{
|
||||
post_quorum_completion_deadline = Some(deadline);
|
||||
}
|
||||
}
|
||||
if post_quorum_detached {
|
||||
let detached_scope = _fanout_publication_scope.clone();
|
||||
let detached_guard = _namespace_commit_guard.clone();
|
||||
tokio::spawn(async move {
|
||||
let _scope = detached_scope;
|
||||
let _guard = detached_guard;
|
||||
while tasks.join_next().await.is_some() {}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let RenameOutcomeProducers {
|
||||
outcomes: mut outcome_rx,
|
||||
mut tasks,
|
||||
} = Self::spawn_rename_outcome_producers(producers, plan);
|
||||
while let Some(outcome) = outcome_rx.recv().await {
|
||||
accept(outcome);
|
||||
loop {
|
||||
let received = if let Some(deadline) = post_quorum_completion_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = outcome_rx.recv() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
post_quorum_detached = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
outcome_rx.recv().await
|
||||
};
|
||||
let Some(outcome) = received else { break };
|
||||
if let Some(deadline) = accept(outcome) {
|
||||
post_quorum_completion_deadline = Some(deadline);
|
||||
}
|
||||
}
|
||||
if post_quorum_detached {
|
||||
let detached_scope = _fanout_publication_scope.clone();
|
||||
let detached_guard = _namespace_commit_guard.clone();
|
||||
tokio::spawn(async move {
|
||||
let _scope = detached_scope;
|
||||
let _guard = detached_guard;
|
||||
while outcome_rx.recv().await.is_some() {}
|
||||
while tasks.join_next().await.is_some() {}
|
||||
});
|
||||
} else {
|
||||
while tasks.join_next().await.is_some() {}
|
||||
}
|
||||
while tasks.join_next().await.is_some() {}
|
||||
}
|
||||
#[cfg(test)]
|
||||
rollback_fault_injection::after_fanout(&fanout_paths.dst_object);
|
||||
(results, fanout_file_infos)
|
||||
(results, fanout_file_infos, post_quorum_detached)
|
||||
};
|
||||
let fanout_future = crate::disk::with_detached_disk_io_context(fanout_future);
|
||||
let fanout = if protected_multipart {
|
||||
@@ -5661,7 +5762,7 @@ impl SetDisks {
|
||||
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_QUORUM_WAIT,
|
||||
quorum_wait_started,
|
||||
);
|
||||
let (results, file_infos) = match fanout_result {
|
||||
let (results, file_infos, post_quorum_detached) = match fanout_result {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
drop(disk_snapshot);
|
||||
@@ -5749,6 +5850,13 @@ impl SetDisks {
|
||||
}
|
||||
}
|
||||
}
|
||||
if post_quorum_detached {
|
||||
for (idx, seen) in seen_slots.iter().enumerate() {
|
||||
if !*seen {
|
||||
errs[idx] = Some(DiskError::Timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if issue3031_diag_enabled() {
|
||||
let success_count = errs.iter().filter(|err| err.is_none()).count();
|
||||
@@ -6635,6 +6743,7 @@ impl SetDisks {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[tracing::instrument(level = "trace", skip(self, disks, meta), fields(pool_index = self.pool_index, set_index = self.set_index))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::set_disk) async fn rename_part(
|
||||
@@ -6647,13 +6756,43 @@ impl SetDisks {
|
||||
meta: Bytes,
|
||||
write_quorum: usize,
|
||||
quorum_context: Option<MultipartWriteQuorumContext<'_>>,
|
||||
) -> disk::error::Result<Vec<Option<DiskStore>>> {
|
||||
self.rename_part_with_clean_hint(
|
||||
disks,
|
||||
src_bucket,
|
||||
src_object,
|
||||
dst_bucket,
|
||||
dst_object,
|
||||
meta,
|
||||
write_quorum,
|
||||
quorum_context,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "trace", skip(self, disks, meta), fields(pool_index = self.pool_index, set_index = self.set_index))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in crate::set_disk) async fn rename_part_with_clean_hint(
|
||||
&self,
|
||||
disks: &[Option<DiskStore>],
|
||||
src_bucket: &str,
|
||||
src_object: &str,
|
||||
dst_bucket: &str,
|
||||
dst_object: &str,
|
||||
meta: Bytes,
|
||||
write_quorum: usize,
|
||||
quorum_context: Option<MultipartWriteQuorumContext<'_>>,
|
||||
skip_recover_before_rename: bool,
|
||||
) -> disk::error::Result<Vec<Option<DiskStore>>> {
|
||||
let part = ObjectPartInfo::unmarshal(&meta)?;
|
||||
let integrity = part.integrity.map(Arc::new);
|
||||
|
||||
let recover_started = rustfs_io_metrics::put_stage_timer();
|
||||
self.recover_part_transaction(dst_object, write_quorum).await?;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from("rename_part_recover_before", recover_started);
|
||||
if !skip_recover_before_rename {
|
||||
let recover_started = rustfs_io_metrics::put_stage_timer();
|
||||
self.recover_part_transaction(dst_object, write_quorum).await?;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from("rename_part_recover_before", recover_started);
|
||||
}
|
||||
|
||||
let src_bucket: Arc<str> = Arc::from(src_bucket);
|
||||
let src_object: Arc<str> = Arc::from(src_object);
|
||||
@@ -7834,7 +7973,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
pub(crate) fn evaluate_write_precondition(
|
||||
oi: Result<ObjectInfo>,
|
||||
oi: Result<impl std::borrow::Borrow<ObjectInfo>>,
|
||||
http_preconditions: &HTTPPreconditions,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
@@ -7842,6 +7981,7 @@ impl SetDisks {
|
||||
) -> Option<StorageError> {
|
||||
match oi {
|
||||
Ok(oi) => {
|
||||
let oi = oi.borrow();
|
||||
// Ordinary writes may proceed past a top-level delete marker;
|
||||
// data movement and guarded internal writes must preserve it.
|
||||
if oi.delete_marker {
|
||||
@@ -7855,8 +7995,8 @@ impl SetDisks {
|
||||
object,
|
||||
);
|
||||
}
|
||||
if should_prevent_write(&oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
|
||||
&& !crate::data_movement::can_replace_stale_data_movement_target(&oi, opts)
|
||||
if should_prevent_write(oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
|
||||
&& !crate::data_movement::can_replace_stale_data_movement_target(oi, opts)
|
||||
{
|
||||
return Some(StorageError::PreconditionFailed);
|
||||
}
|
||||
@@ -8243,6 +8383,7 @@ pub(crate) mod disk_call_counters {
|
||||
pub const KIND_METADATA_SLOWTAIL_FAULT: &str = "metadata_slowtail_fault";
|
||||
pub const KIND_INLINE_SHARD_OPEN: &str = "inline_shard_open";
|
||||
pub const KIND_DISK_SHARD_OPEN: &str = "disk_shard_open";
|
||||
pub const KIND_PROOF_STREAM_OPEN: &str = "proof_stream_open";
|
||||
/// Body verification, direct shard assembly, and erasure decoder entry points.
|
||||
pub const KIND_BODY_DECODE: &str = "body_decode";
|
||||
|
||||
@@ -8316,6 +8457,10 @@ pub(crate) mod disk_call_counters {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_proof_stream_open(path: &str, replica: usize) {
|
||||
record(path, KIND_PROOF_STREAM_OPEN, replica);
|
||||
}
|
||||
|
||||
/// RAII scope that observes call counts for a single `object`. Counts recorded
|
||||
/// while the scope is alive — including those recorded inside spawned tasks —
|
||||
/// are queryable; the scope clears its own counts on drop.
|
||||
@@ -11012,6 +11157,82 @@ mod tests {
|
||||
drop(dirs);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn metadata_read_hedges_and_completes_sub_second_when_four_of_twelve_drives_hang() {
|
||||
const DISKS: usize = 12;
|
||||
const PARITY: usize = 4;
|
||||
let bucket = "metadata-sigstop-3x4-bucket";
|
||||
let object = "objects/sigstop-3x4-object";
|
||||
let (dirs, disks) = call_counter_local_disks(bucket, DISKS).await;
|
||||
|
||||
// Install a 12-disk (8 data + 4 parity) non-inline object matching a 3x4 set.
|
||||
let version_id = Uuid::new_v4();
|
||||
let data_dir = Uuid::from_u128(0x3390_0000_0000_0001);
|
||||
let mod_time = OffsetDateTime::now_utc();
|
||||
let distribution = FileInfo::new(&metadata_distribution_key(bucket, object), 8, 4)
|
||||
.erasure
|
||||
.distribution;
|
||||
for (slot, disk) in disks.iter().enumerate() {
|
||||
let disk = disk.as_ref().expect("local disk");
|
||||
disk.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from_static(b"x"))
|
||||
.await
|
||||
.expect("seed 12-disk part.1");
|
||||
let mut fi = FileInfo::new(object, 8, 4);
|
||||
fi.volume = bucket.to_string();
|
||||
fi.name = object.to_string();
|
||||
fi.size = 256 * 1024;
|
||||
fi.version_id = Some(version_id);
|
||||
fi.is_latest = true;
|
||||
fi.mod_time = Some(mod_time);
|
||||
fi.erasure.index = distribution[slot];
|
||||
fi.erasure.distribution = distribution.clone();
|
||||
fi.erasure.block_size = 1024 * 1024;
|
||||
fi.data_dir = Some(data_dir);
|
||||
fi.metadata.insert("etag".to_string(), "deadbeef".to_string());
|
||||
fi.add_object_part(1, "deadbeef".to_string(), 256 * 1024, fi.mod_time, 256 * 1024, None, None);
|
||||
disk.write_metadata(bucket, bucket, object, fi)
|
||||
.await
|
||||
.expect("seed 12-disk metadata");
|
||||
}
|
||||
|
||||
// Simulate 1 SIGSTOP'd node in 3x4 owning 4 drives (indices 0, 1, 2, 3) hanging for 5000ms.
|
||||
temp_env::async_with_vars(
|
||||
[
|
||||
(ENV_RUSTFS_GET_METADATA_TWO_PHASE_READ_PLAN_ENABLE, Some("true")),
|
||||
(ENV_RUSTFS_GET_METADATA_EARLY_STOP_ENABLE, Some("true")),
|
||||
(ENV_RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE, Some("true")),
|
||||
(ENV_RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT, Some("true")),
|
||||
(ENV_RUSTFS_GET_METADATA_SLOWTAIL_FAULT_DELAY_MS, Some("5000")),
|
||||
(ENV_RUSTFS_GET_METADATA_SLOWTAIL_FAULT_DISKS, Some("0,1,2,3")),
|
||||
(ENV_RUSTFS_GET_METADATA_SLOWTAIL_FAULT_BUCKET, Some(bucket)),
|
||||
(ENV_RUSTFS_GET_METADATA_SLOWTAIL_FAULT_OBJECT_PREFIX, Some("objects/")),
|
||||
],
|
||||
async {
|
||||
let started = Instant::now();
|
||||
let (parts_metadata, errs, _diagnostics) = tokio::time::timeout(
|
||||
Duration::from_millis(1200),
|
||||
SetDisks::read_all_fileinfo_observed(&disks, bucket, bucket, object, "", true, false, false, true, PARITY),
|
||||
)
|
||||
.await
|
||||
.expect("3x4 metadata read with 4 hung drives must NOT stall for 5s")
|
||||
.expect("metadata fanout should succeed on 8 surviving drives");
|
||||
let elapsed = started.elapsed();
|
||||
assert!(
|
||||
elapsed < Duration::from_millis(1000),
|
||||
"3x4 SIGSTOP metadata read must finish sub-second, took {elapsed:?}"
|
||||
);
|
||||
let ok_count = parts_metadata.iter().filter(|fi| fi.name == object).count();
|
||||
assert_eq!(ok_count, 8, "all 8 surviving drives must be observed");
|
||||
for (hung_slot, err) in errs.iter().enumerate().take(4) {
|
||||
assert_eq!(*err, Some(DiskError::Timeout), "hung slot {hung_slot} should be reported as Timeout");
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
drop(dirs);
|
||||
}
|
||||
|
||||
/// Demo / regression guard for the backlog#1325 per-disk call counters.
|
||||
///
|
||||
/// The metadata fan-out issues each `read_version` inside its own
|
||||
@@ -12696,6 +12917,36 @@ mod tests {
|
||||
drop(dirs);
|
||||
}
|
||||
|
||||
async fn assert_metadata_fanout_bounds_a_paused_disk(
|
||||
disks: &[Option<DiskStore>],
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
paused_disk: usize,
|
||||
) {
|
||||
let barrier = rename_fanout_barrier::arm(object, paused_disk, rename_fanout_barrier::PHASE_READ_VERSION);
|
||||
let calls = disk_call_counters::observe(object);
|
||||
let read = SetDisks::read_all_fileinfo_observed(disks, bucket, bucket, object, "", true, false, false, true, 2);
|
||||
|
||||
// Hold the disk before its I/O begins. Only the post-quorum grace can
|
||||
// produce a timeout for this slot while preserving the healthy replies.
|
||||
let ((), result) = tokio::time::timeout(BARRIER_PAUSE_GUARD, async { tokio::join!(barrier.wait_until_paused(), read) })
|
||||
.await
|
||||
.expect("full fanout must dispatch the paused disk and finish within its grace");
|
||||
let (parts, errs, diagnostics) = result.expect("healthy metadata quorum should survive the straggler");
|
||||
|
||||
for disk_index in 0..disks.len() {
|
||||
assert_eq!(
|
||||
calls.for_disk(disk_call_counters::KIND_READ_VERSION, disk_index),
|
||||
1,
|
||||
"full fanout must dispatch slot {disk_index} exactly once"
|
||||
);
|
||||
}
|
||||
assert_eq!(diagnostics.total_responses(), disks.len());
|
||||
assert!(matches!(errs[paused_disk], Some(DiskError::Timeout)));
|
||||
assert_eq!(errs.iter().filter(|error| error.is_some()).count(), 1);
|
||||
assert_eq!(parts.iter().filter(|part| part.name == object).count(), disks.len() - 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bounded_metadata_early_stop_full_waits_when_inline_shard_identity_is_copied() {
|
||||
const DISKS: usize = 4;
|
||||
@@ -12718,51 +12969,7 @@ mod tests {
|
||||
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
|
||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
|
||||
],
|
||||
async {
|
||||
let spare_disk = bounded_spare_disk_index(bucket, &object, 2, 2);
|
||||
let barrier = rename_fanout_barrier::arm(&object, spare_disk, rename_fanout_barrier::PHASE_READ_VERSION);
|
||||
let calls = disk_call_counters::observe(&object);
|
||||
let disks_for_read = disks.clone();
|
||||
let object_for_read = object.clone();
|
||||
let mut read = tokio::spawn(async move {
|
||||
SetDisks::read_all_fileinfo_observed(
|
||||
&disks_for_read,
|
||||
bucket,
|
||||
bucket,
|
||||
&object_for_read,
|
||||
"",
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
2,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
|
||||
.await
|
||||
.expect("full-wait fallback should schedule the spare disk");
|
||||
assert!(
|
||||
tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await.is_err(),
|
||||
"copied inline shard identity must not satisfy the early-stop data gate"
|
||||
);
|
||||
barrier.release();
|
||||
|
||||
let (parts_metadata, errs, diagnostics) = read
|
||||
.await
|
||||
.expect("metadata read task should not panic")
|
||||
.expect("copied inline shard identity should fall back to full fanout");
|
||||
|
||||
assert_eq!(
|
||||
calls.total(disk_call_counters::KIND_READ_VERSION),
|
||||
DISKS as u64,
|
||||
"copied shard identity must keep metadata fanout open instead of aborting spares"
|
||||
);
|
||||
assert_eq!(diagnostics.total_responses(), DISKS);
|
||||
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
|
||||
assert!(errs.iter().all(Option::is_none));
|
||||
},
|
||||
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -12943,51 +13150,7 @@ mod tests {
|
||||
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
|
||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
|
||||
],
|
||||
async {
|
||||
let spare_disk = bounded_spare_disk_index(bucket, &object, 2, 2);
|
||||
let barrier = rename_fanout_barrier::arm(&object, spare_disk, rename_fanout_barrier::PHASE_READ_VERSION);
|
||||
let calls = disk_call_counters::observe(&object);
|
||||
let disks_for_read = disks.clone();
|
||||
let object_for_read = object.clone();
|
||||
let mut read = tokio::spawn(async move {
|
||||
SetDisks::read_all_fileinfo_observed(
|
||||
&disks_for_read,
|
||||
bucket,
|
||||
bucket,
|
||||
&object_for_read,
|
||||
"",
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
2,
|
||||
)
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
|
||||
.await
|
||||
.expect("purge-pending fallback should schedule the spare disk");
|
||||
assert!(
|
||||
tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await.is_err(),
|
||||
"purge-pending payload metadata must not satisfy the inline data-read gate"
|
||||
);
|
||||
barrier.release();
|
||||
|
||||
let (parts_metadata, errs, diagnostics) = read
|
||||
.await
|
||||
.expect("metadata read task should not panic")
|
||||
.expect("purge-pending inline payload should fall back to full fanout");
|
||||
|
||||
assert_eq!(
|
||||
calls.total(disk_call_counters::KIND_READ_VERSION),
|
||||
DISKS as u64,
|
||||
"purge-pending payload must keep metadata fanout open instead of aborting spares"
|
||||
);
|
||||
assert_eq!(diagnostics.total_responses(), DISKS);
|
||||
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
|
||||
assert!(errs.iter().all(Option::is_none));
|
||||
},
|
||||
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -13008,46 +13171,7 @@ mod tests {
|
||||
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
|
||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
|
||||
],
|
||||
async {
|
||||
let barrier = rename_fanout_barrier::arm(object, 2, rename_fanout_barrier::PHASE_READ_VERSION);
|
||||
let calls = disk_call_counters::observe(object);
|
||||
let disks_for_read = disks.clone();
|
||||
let mut read = tokio::spawn(async move {
|
||||
SetDisks::read_all_fileinfo_observed(&disks_for_read, bucket, bucket, object, "", true, false, false, true, 2)
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
|
||||
.await
|
||||
.expect("third scheduled read_version should pause at the deterministic barrier");
|
||||
tokio::time::timeout(BARRIER_PAUSE_GUARD, async {
|
||||
while calls.for_disk(disk_call_counters::KIND_READ_VERSION, 3) == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("bounded non-inline data-read fanout should immediately schedule the spare disk");
|
||||
|
||||
let pending = tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await;
|
||||
assert!(
|
||||
pending.is_err(),
|
||||
"non-inline data reads must not return before the paused metadata response"
|
||||
);
|
||||
barrier.release();
|
||||
let (parts_metadata, errs, diagnostics) = read
|
||||
.await
|
||||
.expect("metadata read task should not panic")
|
||||
.expect("healthy spare metadata should resolve");
|
||||
|
||||
assert_eq!(
|
||||
calls.total(disk_call_counters::KIND_READ_VERSION),
|
||||
DISKS as u64,
|
||||
"bounded non-inline data-read fanout should issue the paused disk plus the remaining spare"
|
||||
);
|
||||
assert_eq!(diagnostics.total_responses(), DISKS);
|
||||
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
|
||||
assert!(errs.iter().all(Option::is_none));
|
||||
},
|
||||
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2),
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -13068,48 +13192,7 @@ mod tests {
|
||||
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", None::<&str>),
|
||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", None::<&str>),
|
||||
],
|
||||
async {
|
||||
let barrier = rename_fanout_barrier::arm(object, 2, rename_fanout_barrier::PHASE_READ_VERSION);
|
||||
let calls = disk_call_counters::observe(object);
|
||||
let disks_for_read = disks.clone();
|
||||
let mut read = tokio::spawn(async move {
|
||||
SetDisks::read_all_fileinfo_observed(&disks_for_read, bucket, bucket, object, "", true, false, false, true, 2)
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::time::timeout(BARRIER_PAUSE_GUARD, barrier.wait_until_paused())
|
||||
.await
|
||||
.expect("default bounded non-inline read should schedule the paused metadata task");
|
||||
tokio::time::timeout(BARRIER_PAUSE_GUARD, async {
|
||||
while calls.for_disk(disk_call_counters::KIND_READ_VERSION, 3) == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect(
|
||||
"default bounded non-inline read should immediately force full fanout after the first non-inline response",
|
||||
);
|
||||
|
||||
let pending = tokio::time::timeout(BARRIER_PAUSE_GUARD, &mut read).await;
|
||||
assert!(
|
||||
pending.is_err(),
|
||||
"default non-inline data reads must not return before the paused metadata response"
|
||||
);
|
||||
barrier.release();
|
||||
let (parts_metadata, errs, diagnostics) = read
|
||||
.await
|
||||
.expect("metadata read task should not panic")
|
||||
.expect("default data-read metadata should resolve");
|
||||
|
||||
assert_eq!(
|
||||
calls.total(disk_call_counters::KIND_READ_VERSION),
|
||||
DISKS as u64,
|
||||
"default non-inline GET data-read metadata must keep full fanout without waiting for a quorum miss first"
|
||||
);
|
||||
assert_eq!(diagnostics.total_responses(), DISKS);
|
||||
assert_eq!(parts_metadata.iter().filter(|fi| fi.name == object).count(), DISKS);
|
||||
assert!(errs.iter().all(Option::is_none));
|
||||
},
|
||||
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2),
|
||||
)
|
||||
.await;
|
||||
|
||||
|
||||
@@ -724,6 +724,17 @@ pub(in crate::set_disk) fn non_inline_data_read_early_stop_allowed(read_data: bo
|
||||
}
|
||||
|
||||
const NON_INLINE_SINGLE_PENDING_HEDGE_DELAY: Duration = Duration::from_millis(100);
|
||||
/// Delay before fanning out remaining spare disks when multiple initial disks
|
||||
/// in bounded-fanout mode are simultaneously unresponsive (e.g., a SIGSTOP'd
|
||||
/// node owning 4 drives in a 3x4 set).
|
||||
const BOUNDED_FANOUT_MULTI_PENDING_HEDGE_DELAY: Duration = Duration::from_millis(100);
|
||||
/// Post-quorum straggler grace once all disks have been queried and a valid,
|
||||
/// conflict-free read quorum has already been observed. Prevents hung drives
|
||||
/// from pinning GET latency to the full 5s drive metadata timeout.
|
||||
const METADATA_POST_QUORUM_STRAGGLER_GRACE: Duration = Duration::from_millis(250);
|
||||
/// Post-quorum straggler grace for non-healing remote full-wait metadata reads
|
||||
/// once a verified, conflict-free write/read quorum has already replied.
|
||||
const FULL_WAIT_REMOTE_POST_QUORUM_STRAGGLER_GRACE: Duration = Duration::from_millis(350);
|
||||
|
||||
fn data_read_inline_missing_shards_are_pending(
|
||||
candidate: &FileInfo,
|
||||
@@ -1014,6 +1025,13 @@ impl SetDisks {
|
||||
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
|
||||
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
|
||||
);
|
||||
let fanout_host_progress: Vec<u64> = disks
|
||||
.iter()
|
||||
.map(|disk| match disk.as_deref() {
|
||||
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
|
||||
_ => 0,
|
||||
})
|
||||
.collect();
|
||||
let futures = disks.iter().enumerate().map(|(disk_index, disk)| {
|
||||
let disk = disk.clone();
|
||||
let task_opts = opts;
|
||||
@@ -1025,7 +1043,7 @@ impl SetDisks {
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
#[allow(clippy::redundant_locals)]
|
||||
let diagnostic_context = diagnostic_context;
|
||||
AbortOnDropJoinHandle(tokio::spawn(async move {
|
||||
AbortOnDropJoinHandle(tokio::spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
let read = async move {
|
||||
let response_start = observe.then(Instant::now);
|
||||
let result = if let Some(disk) = disk {
|
||||
@@ -1053,34 +1071,137 @@ impl SetDisks {
|
||||
.await;
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
read.await
|
||||
}))
|
||||
})))
|
||||
});
|
||||
|
||||
// Wait for all futures to complete
|
||||
let results = join_all(futures).await;
|
||||
// Non-healing distributed metadata reads (e.g. bucket metadata /
|
||||
// incarnation checks during PUT) should not stall for the full 5s
|
||||
// drive timeout on a SIGSTOP'd peer once a clean, conflict-free quorum
|
||||
// has already replied.
|
||||
let bound_remote_stragglers = !healing && !incl_free_versions && disks.iter().flatten().any(|disk| !disk.is_local());
|
||||
if bound_remote_stragglers {
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
for (index, join_result) in results.into_iter().enumerate() {
|
||||
match join_result {
|
||||
Ok((res, elapsed)) => match res {
|
||||
Ok(file_info) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_file_info(&file_info, elapsed));
|
||||
}
|
||||
slots[index].result = Some(Ok(file_info));
|
||||
let mut pending: FuturesUnordered<_> = futures
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, handle)| async move { (index, handle.await) })
|
||||
.collect();
|
||||
let mut valid_candidate: Option<FileInfo> = None;
|
||||
let mut matching_votes = 0usize;
|
||||
let mut conflicting = false;
|
||||
let mut required_quorum: Option<usize> = None;
|
||||
let mut grace_deadline: Option<tokio::time::Instant> = None;
|
||||
|
||||
loop {
|
||||
let next = if let Some(deadline) = grace_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = pending.next() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => None,
|
||||
}
|
||||
Err(e) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_error(&e, elapsed));
|
||||
} else {
|
||||
pending.next().await
|
||||
};
|
||||
let Some((index, join_result)) = next else {
|
||||
break;
|
||||
};
|
||||
match join_result {
|
||||
Ok((res, elapsed)) => match res {
|
||||
Ok(file_info) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_file_info(&file_info, elapsed));
|
||||
}
|
||||
if file_info_is_valid_for_metadata(&file_info) {
|
||||
if let Some(candidate) = valid_candidate.as_ref() {
|
||||
if metadata_early_stop_candidate_matches(candidate, &file_info) {
|
||||
matching_votes = matching_votes.saturating_add(1);
|
||||
} else {
|
||||
conflicting = true;
|
||||
}
|
||||
} else {
|
||||
let data_blocks = file_info.erasure.data_blocks;
|
||||
let parity_blocks = file_info.erasure.parity_blocks;
|
||||
if data_blocks > 0 && data_blocks + parity_blocks == disks.len() {
|
||||
required_quorum = Some(if data_blocks == parity_blocks {
|
||||
data_blocks.saturating_add(1)
|
||||
} else {
|
||||
data_blocks
|
||||
});
|
||||
}
|
||||
valid_candidate = Some(file_info.clone());
|
||||
matching_votes = 1;
|
||||
}
|
||||
}
|
||||
slots[index].result = Some(Ok(file_info));
|
||||
}
|
||||
slots[index].result = Some(Err(e));
|
||||
Err(e) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_error(&e, elapsed));
|
||||
}
|
||||
slots[index].result = Some(Err(e));
|
||||
}
|
||||
},
|
||||
Err(_join_err) => {
|
||||
if let Some(observations) = &mut observations {
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Unexpected, Duration::ZERO));
|
||||
}
|
||||
slots[index].result = Some(Err(DiskError::Unexpected));
|
||||
}
|
||||
}
|
||||
if grace_deadline.is_none()
|
||||
&& !conflicting
|
||||
&& !pending.is_empty()
|
||||
&& required_quorum.is_some_and(|quorum| matching_votes >= quorum)
|
||||
{
|
||||
grace_deadline = Some(tokio::time::Instant::now() + FULL_WAIT_REMOTE_POST_QUORUM_STRAGGLER_GRACE);
|
||||
}
|
||||
}
|
||||
// Dropping remaining `AbortOnDropJoinHandle`s aborts hung remote tasks.
|
||||
drop(pending);
|
||||
for slot in &mut slots {
|
||||
if slot.result.is_none() {
|
||||
if let Some(Some(disk)) = disks.get(slot.disk_index)
|
||||
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
|
||||
{
|
||||
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
|
||||
}
|
||||
},
|
||||
Err(_join_err) => {
|
||||
// A spawned task panicked — treat as unexpected disk error
|
||||
if let Some(observations) = &mut observations {
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Unexpected, Duration::ZERO));
|
||||
observations.push(MetadataFanoutObservation::from_error(
|
||||
&DiskError::Timeout,
|
||||
fanout_start.map_or(Duration::ZERO, |s| s.elapsed()),
|
||||
));
|
||||
}
|
||||
slot.result = Some(Err(DiskError::Timeout));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Wait for all futures to complete
|
||||
let results = join_all(futures).await;
|
||||
|
||||
for (index, join_result) in results.into_iter().enumerate() {
|
||||
match join_result {
|
||||
Ok((res, elapsed)) => match res {
|
||||
Ok(file_info) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_file_info(&file_info, elapsed));
|
||||
}
|
||||
slots[index].result = Some(Ok(file_info));
|
||||
}
|
||||
Err(e) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_error(&e, elapsed));
|
||||
}
|
||||
slots[index].result = Some(Err(e));
|
||||
}
|
||||
},
|
||||
Err(_join_err) => {
|
||||
// A spawned task panicked — treat as unexpected disk error
|
||||
if let Some(observations) = &mut observations {
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Unexpected, Duration::ZERO));
|
||||
}
|
||||
slots[index].result = Some(Err(DiskError::Unexpected));
|
||||
}
|
||||
slots[index].result = Some(Err(DiskError::Unexpected));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1149,11 +1270,20 @@ impl SetDisks {
|
||||
let mut final_miss_reason_override = None;
|
||||
let mut non_inline_candidate_eligible = None;
|
||||
let mut single_pending_hedge_deadline = None;
|
||||
let mut multi_pending_hedge_deadline: Option<tokio::time::Instant> = None;
|
||||
let mut post_quorum_straggler_deadline: Option<tokio::time::Instant> = None;
|
||||
let slowtail_fault = get_metadata_slowtail_fault_request(bucket.as_ref(), object.as_ref(), read_data);
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
|
||||
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::MetadataRead,
|
||||
);
|
||||
let fanout_host_progress: Vec<u64> = disks
|
||||
.iter()
|
||||
.map(|disk| match disk.as_deref() {
|
||||
Some(crate::disk::Disk::Remote(remote)) => remote.host_completed_ops(),
|
||||
_ => 0,
|
||||
})
|
||||
.collect();
|
||||
let spawn_read_version = |join_set: &mut JoinSet<(usize, disk::error::Result<FileInfo>, Duration)>,
|
||||
task_ids: &mut [Option<tokio::task::Id>],
|
||||
index: usize,
|
||||
@@ -1167,7 +1297,7 @@ impl SetDisks {
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
#[allow(clippy::redundant_locals)]
|
||||
let diagnostic_context = diagnostic_context;
|
||||
let task = join_set.spawn(async move {
|
||||
let task = join_set.spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
let read = async move {
|
||||
let response_start = stage_metrics_enabled.then(Instant::now);
|
||||
let result = if let Some(disk) = disk {
|
||||
@@ -1203,7 +1333,7 @@ impl SetDisks {
|
||||
.await;
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
read.await
|
||||
});
|
||||
}));
|
||||
task_ids[index] = Some(task.id());
|
||||
};
|
||||
|
||||
@@ -1224,37 +1354,130 @@ impl SetDisks {
|
||||
}
|
||||
}
|
||||
|
||||
if bounded_fanout && next_fanout_index < disks.len() && join_set.len() > 1 {
|
||||
multi_pending_hedge_deadline = Some(tokio::time::Instant::now() + BOUNDED_FANOUT_MULTI_PENDING_HEDGE_DELAY);
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum MetadataWaitTimer {
|
||||
SinglePendingHedge,
|
||||
MultiPendingHedge,
|
||||
PostQuorumStragglerGrace,
|
||||
}
|
||||
|
||||
loop {
|
||||
let mut defer_pending_inline_data_shard = false;
|
||||
let result = if let Some(deadline) = single_pending_hedge_deadline.take() {
|
||||
let active_timer = [
|
||||
single_pending_hedge_deadline.map(|d| (d, MetadataWaitTimer::SinglePendingHedge)),
|
||||
multi_pending_hedge_deadline.map(|d| (d, MetadataWaitTimer::MultiPendingHedge)),
|
||||
post_quorum_straggler_deadline.map(|d| (d, MetadataWaitTimer::PostQuorumStragglerGrace)),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.min_by_key(|(deadline, _)| *deadline);
|
||||
|
||||
let result = if let Some((deadline, timer_kind)) = active_timer {
|
||||
tokio::select! {
|
||||
result = join_set.join_next_with_id() => result,
|
||||
_ = async {
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
#[cfg(test)]
|
||||
rename_fanout_barrier::checkpoint(
|
||||
object.as_ref(),
|
||||
0,
|
||||
rename_fanout_barrier::PHASE_NON_INLINE_HEDGE_TIMER,
|
||||
)
|
||||
.await;
|
||||
if matches!(
|
||||
timer_kind,
|
||||
MetadataWaitTimer::SinglePendingHedge | MetadataWaitTimer::MultiPendingHedge
|
||||
) {
|
||||
rename_fanout_barrier::checkpoint(
|
||||
object.as_ref(),
|
||||
0,
|
||||
rename_fanout_barrier::PHASE_NON_INLINE_HEDGE_TIMER,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
} => {
|
||||
if bounded_fanout
|
||||
&& !force_full_wait
|
||||
&& join_set.len() == 1
|
||||
&& non_inline_candidate_eligible == Some(true)
|
||||
&& !accumulator.candidate_has_read_reserve()
|
||||
&& next_fanout_index < disks.len()
|
||||
{
|
||||
while next_fanout_index < disks.len() {
|
||||
let disk_index = fanout_order[next_fanout_index];
|
||||
next_fanout_index = next_fanout_index.saturating_add(1);
|
||||
if let Some(disk) = disks.get(disk_index).cloned() {
|
||||
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
|
||||
scheduled_count = scheduled_count.saturating_add(1);
|
||||
break;
|
||||
match timer_kind {
|
||||
MetadataWaitTimer::SinglePendingHedge => {
|
||||
single_pending_hedge_deadline = None;
|
||||
if bounded_fanout
|
||||
&& !force_full_wait
|
||||
&& join_set.len() == 1
|
||||
&& non_inline_candidate_eligible == Some(true)
|
||||
&& !accumulator.candidate_has_read_reserve()
|
||||
&& next_fanout_index < disks.len()
|
||||
{
|
||||
while next_fanout_index < disks.len() {
|
||||
let disk_index = fanout_order[next_fanout_index];
|
||||
next_fanout_index = next_fanout_index.saturating_add(1);
|
||||
if let Some(disk) = disks.get(disk_index).cloned() {
|
||||
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
|
||||
scheduled_count = scheduled_count.saturating_add(1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
MetadataWaitTimer::MultiPendingHedge => {
|
||||
multi_pending_hedge_deadline = None;
|
||||
// Multiple initial disks are still unanswered after 100ms
|
||||
// (e.g., a SIGSTOP'd node holding 4 drives in a 3x4 set).
|
||||
// Fan out all remaining spare drives immediately so healthy
|
||||
// parity/data nodes can establish read quorum without paying
|
||||
// the full 5s drive metadata timeout.
|
||||
if bounded_fanout && next_fanout_index < disks.len() && join_set.len() > 1 {
|
||||
while next_fanout_index < disks.len() {
|
||||
let disk_index = fanout_order[next_fanout_index];
|
||||
next_fanout_index = next_fanout_index.saturating_add(1);
|
||||
if let Some(disk) = disks.get(disk_index).cloned() {
|
||||
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
|
||||
scheduled_count = scheduled_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
MetadataWaitTimer::PostQuorumStragglerGrace => {
|
||||
// All disks have been dispatched and a verified, conflict-free
|
||||
// read quorum is already in hand. Abort the hung tail tasks and
|
||||
// return immediately so EC reconstruction can proceed in <500ms.
|
||||
join_set.abort_all();
|
||||
let mut cancelled_count = 0usize;
|
||||
while let Some(join_result) = join_set.join_next_with_id().await {
|
||||
if matches!(join_result, Err(join_error) if join_error.is_cancelled()) {
|
||||
cancelled_count = cancelled_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
let elapsed = fanout_start.map_or(Duration::ZERO, |s| s.elapsed());
|
||||
for slot in &mut slots {
|
||||
if slot.result.is_none() {
|
||||
if let Some(Some(disk)) = disks.get(slot.disk_index)
|
||||
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
|
||||
{
|
||||
remote.record_straggler_timeout_if_stalled(fanout_host_progress[slot.disk_index]);
|
||||
}
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
|
||||
slot.result = Some(Err(DiskError::Timeout));
|
||||
}
|
||||
}
|
||||
rustfs_io_metrics::record_get_object_metadata_early_stop_hit(
|
||||
metrics_path,
|
||||
crate::diagnostics::get::GET_METADATA_EARLY_STOP_REASON_VALID_QUORUM,
|
||||
);
|
||||
rustfs_io_metrics::record_get_object_metadata_early_stop_saved_responses(
|
||||
metrics_path,
|
||||
cancelled_count,
|
||||
);
|
||||
rustfs_io_metrics::record_get_object_metadata_fanout_lifecycle(
|
||||
metrics_path,
|
||||
scheduled_count,
|
||||
scheduled_count.saturating_sub(cancelled_count),
|
||||
cancelled_count,
|
||||
);
|
||||
let diagnostics = MetadataFanoutDiagnostics::new(elapsed, observations);
|
||||
return Ok(MetadataReadResult {
|
||||
slots,
|
||||
diagnostics,
|
||||
condition_stopped: false,
|
||||
verified_inline_body: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -1470,7 +1693,49 @@ impl SetDisks {
|
||||
&& accumulator.can_still_reach_early_stop_with_pending(join_set.len())
|
||||
&& next_fanout_index < disks.len()
|
||||
{
|
||||
single_pending_hedge_deadline = Some(tokio::time::Instant::now() + NON_INLINE_SINGLE_PENDING_HEDGE_DELAY);
|
||||
single_pending_hedge_deadline
|
||||
.get_or_insert_with(|| tokio::time::Instant::now() + NON_INLINE_SINGLE_PENDING_HEDGE_DELAY);
|
||||
} else {
|
||||
single_pending_hedge_deadline = None;
|
||||
}
|
||||
if bounded_fanout && next_fanout_index < disks.len() && join_set.len() > 1 {
|
||||
multi_pending_hedge_deadline
|
||||
.get_or_insert_with(|| tokio::time::Instant::now() + BOUNDED_FANOUT_MULTI_PENDING_HEDGE_DELAY);
|
||||
} else {
|
||||
multi_pending_hedge_deadline = None;
|
||||
}
|
||||
let all_disks_dispatched = !bounded_fanout || next_fanout_index >= disks.len();
|
||||
let valid_quorum_reached = accumulator
|
||||
.early_stop_decision()
|
||||
.or_else(|| accumulator.version_early_stop_decision())
|
||||
.is_some()
|
||||
|| accumulator.candidate.as_ref().is_some_and(|candidate| {
|
||||
candidate.size == 0
|
||||
&& accumulator.not_found_responses == 0
|
||||
&& accumulator.version_not_found_responses == 0
|
||||
&& accumulator.candidate_votes >= accumulator.default_write_quorum()
|
||||
});
|
||||
let not_found_quorum_reached = accumulator.valid_responses == 0
|
||||
&& !accumulator.delete_marker_seen
|
||||
&& accumulator.not_found_responses >= accumulator.missing_response_quorum();
|
||||
let quorum_ready_for_straggler_grace = all_disks_dispatched
|
||||
&& !join_set.is_empty()
|
||||
&& !accumulator.conflicting_metadata
|
||||
&& !accumulator.delete_marker_seen
|
||||
&& accumulator.hard_errors == 0
|
||||
&& ((valid_quorum_reached
|
||||
&& (!read_data
|
||||
|| non_inline_candidate_eligible == Some(true)
|
||||
|| accumulator
|
||||
.candidate
|
||||
.as_ref()
|
||||
.is_some_and(|candidate| accumulator.candidate_votes >= candidate.erasure.data_blocks)))
|
||||
|| not_found_quorum_reached);
|
||||
if quorum_ready_for_straggler_grace {
|
||||
post_quorum_straggler_deadline
|
||||
.get_or_insert_with(|| tokio::time::Instant::now() + METADATA_POST_QUORUM_STRAGGLER_GRACE);
|
||||
} else {
|
||||
post_quorum_straggler_deadline = None;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ struct FileInfoQuorumKey {
|
||||
|
||||
impl SetDisks {
|
||||
/// Read one key's complete version stack without enumerating its parent.
|
||||
pub(crate) async fn read_object_versions_for_lifecycle(
|
||||
pub(crate) async fn read_object_version_history(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
|
||||
@@ -138,6 +138,7 @@ use rustfs_io_metrics::{
|
||||
use rustfs_lock::LockClient;
|
||||
#[cfg(test)]
|
||||
use rustfs_lock::LockManager;
|
||||
use rustfs_lock::distributed_lock::same_write_voters;
|
||||
use rustfs_lock::fast_lock::types::LockResult;
|
||||
use rustfs_lock::{FastLockGuard, NamespaceLock, NamespaceLockGuard, NamespaceLockWrapper, ObjectKey};
|
||||
use rustfs_madmin::heal_commands::{HealDriveInfo, HealResultItem, Infos};
|
||||
@@ -507,9 +508,12 @@ fn release_materialized_read_lock(bucket: &str, object: &str, read_lock_guard: O
|
||||
drop(read_lock_guard);
|
||||
}
|
||||
|
||||
const MULTIPART_GENERATED_VERSION_SUFFIX: &str = "multipart-generated-version-id";
|
||||
|
||||
pub(crate) fn strip_internal_multipart_metadata(metadata: &mut HashMap<String, String>) {
|
||||
metadata.remove(RUSTFS_MULTIPART_BUCKET_KEY);
|
||||
metadata.remove(RUSTFS_MULTIPART_OBJECT_KEY);
|
||||
rustfs_utils::http::metadata_compat::remove_str(metadata, MULTIPART_GENERATED_VERSION_SUFFIX);
|
||||
rustfs_utils::http::metadata_compat::remove_str(metadata, SUFFIX_BUCKET_INCARNATION_ID);
|
||||
}
|
||||
|
||||
@@ -4434,7 +4438,8 @@ fn record_lock_acquire(bucket: &str, object: &str, lock_type: &str) -> String {
|
||||
return lock_id;
|
||||
}
|
||||
|
||||
let request_id = format!("get-{}-{}", bucket, object);
|
||||
let request_id =
|
||||
crate::cluster::rpc::context_propagation::current_request_id_or_fallback(|| format!("get-{}-{}", bucket, object));
|
||||
let resource = format!("{}/{}", bucket, object);
|
||||
|
||||
// Log with structured fields for analysis
|
||||
@@ -4456,7 +4461,8 @@ fn record_lock_release(bucket: &str, object: &str, lock_id: &str, lock_type: &st
|
||||
return;
|
||||
}
|
||||
|
||||
let request_id = format!("get-{}-{}", bucket, object);
|
||||
let request_id =
|
||||
crate::cluster::rpc::context_propagation::current_request_id_or_fallback(|| format!("get-{}-{}", bucket, object));
|
||||
|
||||
debug!(
|
||||
request_id = %request_id,
|
||||
@@ -4953,17 +4959,6 @@ pub(crate) fn same_distributed_lock_domain(left: &[Arc<dyn LockClient>], right:
|
||||
.all(|right_client| left.iter().any(|left_client| Arc::ptr_eq(left_client, right_client)))
|
||||
}
|
||||
|
||||
// Reusing a held writer additionally requires the same quorum, so repeated
|
||||
// clients must not give different weight to an otherwise identical domain.
|
||||
fn same_distributed_lock_quorum(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
|
||||
!left.is_empty()
|
||||
&& left.len() == right.len()
|
||||
&& left.iter().all(|client| {
|
||||
left.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
|
||||
&& right.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
|
||||
})
|
||||
}
|
||||
|
||||
const ERASURE_CACHE_MAX_ENTRIES: usize = 32;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
@@ -5950,7 +5945,7 @@ impl SetDisks {
|
||||
(false, false) => Arc::ptr_eq(&self.local_lock_manager, &other.local_lock_manager),
|
||||
// Distributed lock clients receive the raw ObjectKey; the pool
|
||||
// namespace is not part of the key stored by their backends.
|
||||
(true, true) => same_distributed_lock_quorum(&self.lockers, &other.lockers),
|
||||
(true, true) => same_write_voters(&self.lockers, &other.lockers),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -10482,13 +10477,10 @@ mod tests {
|
||||
let a: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
let b: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
let c: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
assert!(same_distributed_lock_quorum(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
|
||||
assert!(!same_distributed_lock_quorum(&[a.clone(), b.clone()], &[a.clone(), c]));
|
||||
assert!(!same_distributed_lock_quorum(
|
||||
&[a.clone(), a.clone(), b.clone()],
|
||||
&[a.clone(), b.clone(), b]
|
||||
));
|
||||
assert!(!same_distributed_lock_quorum(&[], &[]));
|
||||
assert!(same_write_voters(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
|
||||
assert!(!same_write_voters(&[a.clone(), b.clone()], &[a.clone(), c]));
|
||||
assert!(!same_write_voters(&[a.clone(), a.clone(), b.clone()], &[a.clone(), b.clone(), b]));
|
||||
assert!(!same_write_voters(&[], &[]));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -114,31 +114,62 @@ impl SetDisks {
|
||||
pub(crate) async fn stat_bucket_with_quorum(&self, bucket: &str, quorum: BucketInfoQuorum) -> Result<BucketInfo> {
|
||||
let disks = self.disk_inventory().await;
|
||||
let disk_count = disks.len();
|
||||
let probes = disks.into_iter().map(|disk| stat_bucket_volume(disk, bucket));
|
||||
let results = join_all(probes).await;
|
||||
let required = match quorum {
|
||||
// Bucket mutations use a majority regardless of object storage
|
||||
// class. A namespace read must intersect that majority; object
|
||||
// readers still enforce the persisted layout's data-shard quorum.
|
||||
BucketInfoQuorum::Read => disk_count.div_ceil(2).max(1),
|
||||
BucketInfoQuorum::Write | BucketInfoQuorum::HealCandidates => disk_count / 2 + 1,
|
||||
};
|
||||
let strict_majority = disk_count / 2 + 1;
|
||||
let mut probes = disks
|
||||
.into_iter()
|
||||
.map(|disk| stat_bucket_volume(disk, bucket))
|
||||
.collect::<FuturesUnordered<_>>();
|
||||
let mut first_info = None;
|
||||
let mut errs = Vec::with_capacity(results.len());
|
||||
for result in results {
|
||||
let mut errs = Vec::with_capacity(disk_count);
|
||||
let mut successes = 0usize;
|
||||
let mut not_found = 0usize;
|
||||
let mut remaining = disk_count;
|
||||
while let Some(result) = probes.next().await {
|
||||
remaining = remaining.saturating_sub(1);
|
||||
match result {
|
||||
Ok(info) => {
|
||||
successes += 1;
|
||||
if first_info.is_none() {
|
||||
first_info = Some(info);
|
||||
}
|
||||
errs.push(None);
|
||||
// Once enough disks confirm the bucket exists, remaining hung
|
||||
// peers (e.g. SIGSTOP grey failure) cannot overturn quorum.
|
||||
if successes >= required {
|
||||
return first_info
|
||||
.map(|info| BucketInfo {
|
||||
name: info.name,
|
||||
created: info.created,
|
||||
..Default::default()
|
||||
})
|
||||
.ok_or(Error::VolumeNotFound);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
if matches!(err, DiskError::VolumeNotFound) {
|
||||
not_found += 1;
|
||||
}
|
||||
errs.push(Some(err));
|
||||
// If a strict majority reports VolumeNotFound and remaining
|
||||
// disks can no longer reach success quorum, absence is decisive.
|
||||
if not_found >= strict_majority && successes + remaining < required {
|
||||
return Err(Error::VolumeNotFound);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let error = match quorum {
|
||||
// Bucket mutations use a majority regardless of object storage
|
||||
// class. A namespace read must intersect that majority; object
|
||||
// readers still enforce the persisted layout's data-shard quorum.
|
||||
BucketInfoQuorum::Read => reduce_read_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, disk_count.div_ceil(2).max(1)),
|
||||
BucketInfoQuorum::Read => reduce_read_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, required),
|
||||
BucketInfoQuorum::Write | BucketInfoQuorum::HealCandidates => {
|
||||
reduce_write_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, disk_count / 2 + 1)
|
||||
reduce_write_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, required)
|
||||
}
|
||||
};
|
||||
if let Some(err) = error {
|
||||
|
||||
@@ -22,7 +22,8 @@ use crate::disk::{
|
||||
};
|
||||
use crate::error::StorageError;
|
||||
use crate::set_disk::SetDisks;
|
||||
use futures::future::join_all;
|
||||
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
|
||||
use futures::future::{join_all, try_join_all};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
@@ -599,6 +600,98 @@ fn causal_transaction_order(states: &BTreeMap<Uuid, Vec<DeleteRecoveryInspection
|
||||
}
|
||||
|
||||
impl SetDisks {
|
||||
/// With the lifecycle fence held by the caller, check the exact set without
|
||||
/// repairing payloads or settling delete transactions.
|
||||
pub(crate) async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> crate::error::Result<bool> {
|
||||
let first = {
|
||||
let disks = self.disks.read().await;
|
||||
disks
|
||||
.iter()
|
||||
.flatten()
|
||||
.find(|disk| disk.is_local())
|
||||
.or_else(|| disks.iter().flatten().next())
|
||||
.cloned()
|
||||
};
|
||||
let Some(first) = first else {
|
||||
return Ok(false);
|
||||
};
|
||||
let missing = async |disk: &DiskStore| match disk
|
||||
.read_version("", bucket, object, "", &crate::disk::ReadOptions::default())
|
||||
.await
|
||||
{
|
||||
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound) => Ok(true),
|
||||
Ok(_) => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
if !missing(&first).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
// Lock order matches delete recovery and multi-pool decommission:
|
||||
// lifecycle, fixed/target raw object, decommission capacity, transaction, then inventory validation.
|
||||
let (fixed_guard, object_guard, capacity_guard) = if let Some(store) = capacity_store {
|
||||
Box::pin(async {
|
||||
let (fixed_guard, target_guard) = store.acquire_external_read_namespace(bucket, object, self).await?;
|
||||
let capacity_guard = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
crate::error::Result::Ok((Some(fixed_guard), target_guard, Some(capacity_guard)))
|
||||
})
|
||||
.await?
|
||||
} else {
|
||||
let namespace = self.new_ns_lock(bucket, object).await?;
|
||||
let object_guard = namespace.get_read_lock(crate::set_disk::get_lock_acquire_timeout()).await?;
|
||||
(None, Some(object_guard), None)
|
||||
};
|
||||
let transaction_guard = self.acquire_delete_transaction_lock(bucket, object).await?;
|
||||
let disks = self.get_disks_internal().await;
|
||||
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
|
||||
return Ok(false);
|
||||
}
|
||||
// The fast rejection is a hint. Read every member under both locks
|
||||
// before accepting a candidate absence.
|
||||
if try_join_all(disks.iter().flatten().map(missing)).await?.contains(&false) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// A recoverable transaction or legacy backup can restore the object.
|
||||
// Require complete, empty discovery on every disk. No inspection or
|
||||
// settlement is needed for this read-only path.
|
||||
let budget = crate::object_api::DeleteRecoveryWorkBudget::for_disks(disks.len());
|
||||
let transactions = try_join_all(
|
||||
disks
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|disk| discover_bounded(disk, bucket, object, &budget)),
|
||||
)
|
||||
.await?;
|
||||
if transactions.iter().any(|transactions| !transactions.is_empty()) {
|
||||
return Ok(false);
|
||||
}
|
||||
// Do not hold the registry read guard across RPC or disk I/O. A
|
||||
// topology writer may have replaced a member while the probe ran.
|
||||
let current = self.disks.read().await;
|
||||
let namespace_alive = fixed_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
|
||||
&& object_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
|
||||
&& capacity_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost());
|
||||
Ok(current.len() == disks.len()
|
||||
&& current.iter().zip(&disks).all(|(current, probed)| {
|
||||
current
|
||||
.as_ref()
|
||||
.zip(probed.as_ref())
|
||||
.is_some_and(|(current, probed)| Arc::ptr_eq(current, probed))
|
||||
})
|
||||
&& namespace_alive
|
||||
&& !transaction_guard.is_lock_lost())
|
||||
}
|
||||
|
||||
/// Publication follows the ordinary metadata quorum. Once a publication is
|
||||
/// attempted, response loss must never trigger blind rollback.
|
||||
pub(in crate::set_disk) async fn publish_delete_commit(
|
||||
@@ -2632,6 +2725,9 @@ mod tests {
|
||||
for shape in ["live-backup", "foreign", "partial-history", "damaged-data", "causal-cycle"] {
|
||||
let bucket = "recover-marker-source-guards";
|
||||
let (dirs, store) = isolated_store_over_temp_disks().await;
|
||||
store.pools[0].stop_endpoint_monitor_for_test().await;
|
||||
store.background_cancel_token().expect("fixture background token").cancel();
|
||||
tokio::task::yield_now().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
store
|
||||
.make_bucket(
|
||||
@@ -2652,7 +2748,7 @@ mod tests {
|
||||
set.disks.write().await[3] = None;
|
||||
let payload = vec![72; 1024 * 1024];
|
||||
let source = put(&store, bucket, &payload, true).await.unwrap();
|
||||
store
|
||||
let marker = store
|
||||
.delete_object(
|
||||
bucket,
|
||||
"object",
|
||||
@@ -2663,6 +2759,17 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.expect("publish marker while one member lacks the source version");
|
||||
let marker_id = marker.version_id.expect("the delete marker has a version ID");
|
||||
for absent in [source, marker_id] {
|
||||
assert_eq!(
|
||||
disks[3]
|
||||
.read_version("", bucket, "object", &absent.to_string(), &ReadOptions::default())
|
||||
.await
|
||||
.expect_err("the disconnected member must lack the source and marker"),
|
||||
DiskError::FileVersionNotFound,
|
||||
"{shape}: unexpected result reading version {absent}"
|
||||
);
|
||||
}
|
||||
set.disks.write().await[3] = Some(disks[3].clone());
|
||||
let mut first_info = disks[3]
|
||||
.read_version("", bucket, "object", &first.to_string(), &ReadOptions::default())
|
||||
@@ -2695,7 +2802,14 @@ mod tests {
|
||||
DeleteOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
.expect("remove the oldest member of the returning disk's history");
|
||||
assert_eq!(
|
||||
disks[3]
|
||||
.read_version("", bucket, "object", &oldest.to_string(), &ReadOptions::default())
|
||||
.await
|
||||
.expect_err("the returning disk's history must be incomplete before heal"),
|
||||
DiskError::FileVersionNotFound
|
||||
);
|
||||
}
|
||||
"damaged-data" => {
|
||||
// Three metadata sources meet write quorum, but corrupting
|
||||
|
||||
@@ -31,11 +31,37 @@ use std::sync::Arc;
|
||||
#[path = "heal_lock_wait_tests.rs"]
|
||||
mod heal_lock_wait_tests;
|
||||
|
||||
struct ExternalHealCommit {
|
||||
namespace: Option<crate::store::ObjectLockDiagGuard>,
|
||||
capacity: rustfs_lock::NamespaceLockGuard,
|
||||
}
|
||||
|
||||
impl ExternalHealCommit {
|
||||
fn is_lock_lost(&self) -> bool {
|
||||
self.capacity.is_lock_lost() || self.namespace.as_ref().is_some_and(|owner| owner.is_lock_lost())
|
||||
}
|
||||
}
|
||||
|
||||
enum ReadRepairWriteGuard {
|
||||
Set(Box<ObjectLockDiagGuard>),
|
||||
External(Arc<ExternalHealCommit>),
|
||||
}
|
||||
|
||||
impl ReadRepairWriteGuard {
|
||||
fn is_lock_lost(&self) -> bool {
|
||||
match self {
|
||||
Self::Set(guard) => guard.is_lock_lost(),
|
||||
Self::External(guard) => guard.is_lock_lost(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct ExplicitVersionHeal<'a> {
|
||||
opts: &'a HealOpts,
|
||||
allow_regeneration: bool,
|
||||
preserve_unrepairable: bool,
|
||||
capacity_store: Option<&'a crate::store::ECStore>,
|
||||
commit_fence: Option<&'a (dyn Fn() -> bool + Sync)>,
|
||||
namespace_owner: Option<&'a Arc<dyn Send + Sync>>,
|
||||
retirement: Option<&'a MarkerRetirementContext<'a>>,
|
||||
@@ -938,6 +964,7 @@ impl SetDisks {
|
||||
opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: None,
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -1023,6 +1050,29 @@ impl SetDisks {
|
||||
.with_attempt(attempt))
|
||||
}
|
||||
|
||||
async fn admit_external_heal_commit(
|
||||
&self,
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
no_lock: bool,
|
||||
) -> Result<Arc<ExternalHealCommit>> {
|
||||
let namespace = if no_lock {
|
||||
None
|
||||
} else {
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_target_lock_attempted();
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
};
|
||||
let capacity = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
Ok(Arc::new(ExternalHealCommit { namespace, capacity }))
|
||||
}
|
||||
|
||||
async fn acquire_revalidated_read_repair_commit_lock(
|
||||
&self,
|
||||
disks: &[Option<DiskStore>],
|
||||
@@ -1030,14 +1080,24 @@ impl SetDisks {
|
||||
object: &str,
|
||||
version_id: &str,
|
||||
expected_fingerprint: ReadRepairCommitFingerprint,
|
||||
) -> disk::error::Result<Option<ObjectLockDiagGuard>> {
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> disk::error::Result<Option<ReadRepairWriteGuard>> {
|
||||
#[cfg(test)]
|
||||
pause_read_repair(bucket, object, ReadRepairPausePhase::Commit).await;
|
||||
|
||||
let write_lock_wait_start = std::time::Instant::now();
|
||||
let guard = self
|
||||
.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
|
||||
.await?;
|
||||
let guard = if let Some(store) = capacity_store {
|
||||
ReadRepairWriteGuard::External(
|
||||
self.admit_external_heal_commit(store, bucket, object, false)
|
||||
.await
|
||||
.map_err(|error| error.narrow_to_disk().unwrap_or_else(DiskError::other))?,
|
||||
)
|
||||
} else {
|
||||
ReadRepairWriteGuard::Set(Box::new(
|
||||
self.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
|
||||
.await?,
|
||||
))
|
||||
};
|
||||
let write_lock_wait_ms = u64::try_from(write_lock_wait_start.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||
|
||||
let revalidation_start = std::time::Instant::now();
|
||||
@@ -1088,6 +1148,7 @@ impl SetDisks {
|
||||
opts,
|
||||
allow_regeneration: allow_explicit_version_regen,
|
||||
preserve_unrepairable,
|
||||
capacity_store,
|
||||
commit_fence,
|
||||
namespace_owner,
|
||||
retirement,
|
||||
@@ -1813,7 +1874,14 @@ impl SetDisks {
|
||||
.integrity
|
||||
.as_ref()
|
||||
.map(|part| {
|
||||
PartProofReader::new(part.clone(), &parts_metadata, &latest_disks, bucket, object)
|
||||
PartProofReader::new(
|
||||
part.clone(),
|
||||
&parts_metadata,
|
||||
&latest_disks,
|
||||
bucket,
|
||||
object,
|
||||
None,
|
||||
)
|
||||
})
|
||||
.transpose()?;
|
||||
// Cover the complete encoded shard, including a logical
|
||||
@@ -2060,6 +2128,7 @@ impl SetDisks {
|
||||
object,
|
||||
version_id,
|
||||
expected_fingerprint,
|
||||
capacity_store,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -3730,6 +3799,7 @@ impl SetDisks {
|
||||
opts: &opts,
|
||||
allow_regeneration: false,
|
||||
preserve_unrepairable: true,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(can_commit),
|
||||
namespace_owner,
|
||||
retirement: None,
|
||||
@@ -3767,17 +3837,38 @@ impl SetDisks {
|
||||
opts: &HealOpts,
|
||||
absence: &mut Option<HealedObjectAbsence>,
|
||||
proof: AbsenceProofRequest<'_>,
|
||||
) -> Result<(HealResultItem, Option<Error>)> {
|
||||
self.heal_object_for_store(bucket, object, version_id, opts, absence, proof, None)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn heal_object_for_store(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
version_id: &str,
|
||||
opts: &HealOpts,
|
||||
absence: &mut Option<HealedObjectAbsence>,
|
||||
proof: AbsenceProofRequest<'_>,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<(HealResultItem, Option<Error>)> {
|
||||
*absence = None;
|
||||
if opts.read_repair
|
||||
&& !opts.no_lock
|
||||
&& !opts.dry_run
|
||||
&& !opts.remove
|
||||
&& !has_suffix(object, SLASH_SEPARATOR)
|
||||
&& !crate::bucket::utils::is_meta_bucketname(bucket)
|
||||
{
|
||||
// Read repair may stage under a shared lock, but must not perform
|
||||
// destructive cleanup or produce an authoritative absence proof.
|
||||
if opts.read_repair && !opts.no_lock && !opts.dry_run && !opts.remove && !has_suffix(object, SLASH_SEPARATOR) {
|
||||
// Read repair may stage under a shared lock (including `.rustfs.sys`
|
||||
// metadata like `.bucket-incarnation` and `config.json` so a hung
|
||||
// peer cannot hold an exclusive write lock across read-repair timeouts
|
||||
// and stall foreground bucket reads), without performing destructive
|
||||
// cleanup or producing an authoritative absence proof.
|
||||
if let Some(store) = capacity_store {
|
||||
let probe = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
drop(probe);
|
||||
}
|
||||
let can_commit = || proof.retirement.is_none_or(|context| !context.lifecycle_guard.is_lock_lost());
|
||||
let mut read_opts = *opts;
|
||||
loop {
|
||||
@@ -3790,6 +3881,7 @@ impl SetDisks {
|
||||
opts: &read_opts,
|
||||
allow_regeneration: false,
|
||||
preserve_unrepairable: true,
|
||||
capacity_store,
|
||||
commit_fence: Some(&can_commit),
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -3809,7 +3901,22 @@ impl SetDisks {
|
||||
return Ok((result, error.map(Into::into)));
|
||||
}
|
||||
}
|
||||
let _write_lock_guard = if !opts.no_lock {
|
||||
let external = match capacity_store {
|
||||
Some(store) => {
|
||||
let guard = self.admit_external_heal_commit(store, bucket, object, opts.no_lock).await?;
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_operation_started(store.id);
|
||||
Some(guard)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let _write_lock_guard = if let Some(external) = &external {
|
||||
external
|
||||
.namespace
|
||||
.as_ref()
|
||||
.and_then(|guard| guard.target_write_guard())
|
||||
.cloned()
|
||||
} else if !opts.no_lock {
|
||||
let ns_lock = self
|
||||
.new_ns_lock(bucket, object)
|
||||
.await
|
||||
@@ -3845,7 +3952,8 @@ impl SetDisks {
|
||||
None
|
||||
};
|
||||
let locks_lost = || {
|
||||
_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|
||||
external.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
};
|
||||
let mut recovery_removed_version = false;
|
||||
@@ -4007,7 +4115,7 @@ impl SetDisks {
|
||||
let commit_fence = || !locks_lost();
|
||||
let namespace_owner = _write_lock_guard
|
||||
.as_ref()
|
||||
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone())) as Arc<dyn Send + Sync>);
|
||||
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone(), external.clone())) as Arc<dyn Send + Sync>);
|
||||
let (result, err) = pin_object_heal_future(|| {
|
||||
self.heal_object_with_explicit_version_regen(
|
||||
bucket,
|
||||
@@ -4017,6 +4125,7 @@ impl SetDisks {
|
||||
opts: &inner_opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&commit_fence),
|
||||
namespace_owner: namespace_owner.as_ref(),
|
||||
retirement: proof.retirement,
|
||||
@@ -4041,6 +4150,7 @@ impl SetDisks {
|
||||
opts: &inner_opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&commit_fence),
|
||||
namespace_owner: namespace_owner.as_ref(),
|
||||
retirement: proof.retirement,
|
||||
@@ -5981,6 +6091,127 @@ mod heal_result_report_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deep_heal_restores_part_flip_tail_truncation_and_xl_meta_byte_for_byte() {
|
||||
let (temp_dirs, disks, set) = hermetic_set_disks_isolated(4).await;
|
||||
let bucket = "deep-heal-triple-bitrot";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
|
||||
// Write 3 non-inline objects so we can independently inject:
|
||||
// (1) byte-0 flip on part.1, (2) 1-byte tail truncation on part.1,
|
||||
// and (3) 4-byte mid-file corruption (\xde\xad\xbe\xef) on xl.meta,
|
||||
// matching Jepsen `inject-bitrot-on-node!` on disk 0.
|
||||
let mut payloads = Vec::new();
|
||||
let mut target_paths = Vec::new();
|
||||
let mut original_bytes = Vec::new();
|
||||
for (idx, object) in ["obj-flip.bin", "obj-trunc.bin", "obj-meta.bin"].iter().enumerate() {
|
||||
let mut payload = vec![0u8; 512 * 1024];
|
||||
for (pos, byte) in payload.iter_mut().enumerate() {
|
||||
*byte = ((pos.wrapping_mul(31) + idx * 17) & 0xff) as u8;
|
||||
}
|
||||
let mut user_defined = std::collections::HashMap::new();
|
||||
user_defined.insert("x-amz-meta-z".to_string(), "zeta".to_string());
|
||||
user_defined.insert("x-amz-meta-a".to_string(), "alpha".to_string());
|
||||
user_defined.insert("x-amz-meta-m".to_string(), "mid".to_string());
|
||||
set.put_object(
|
||||
bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(payload.clone()),
|
||||
&ObjectOptions {
|
||||
no_lock: true,
|
||||
user_defined,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("source object should be written");
|
||||
let source = disks[2]
|
||||
.read_version("", bucket, object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("source metadata should be readable");
|
||||
let data_dir = source.data_dir.expect("non-inline object should have data_dir");
|
||||
let path = if idx == 2 {
|
||||
temp_dirs[0].path().join(bucket).join(object).join("xl.meta")
|
||||
} else {
|
||||
temp_dirs[0]
|
||||
.path()
|
||||
.join(bucket)
|
||||
.join(object)
|
||||
.join(data_dir.to_string())
|
||||
.join("part.1")
|
||||
};
|
||||
let bytes = tokio::fs::read(&path).await.expect("original on-disk file should exist");
|
||||
payloads.push((*object, payload));
|
||||
target_paths.push(path);
|
||||
original_bytes.push(bytes);
|
||||
}
|
||||
|
||||
// Fault 1: flip byte 0 of obj-flip/part.1 to 0xff (or xor if already 0xff)
|
||||
{
|
||||
let mut corrupted = original_bytes[0].clone();
|
||||
corrupted[0] = if corrupted[0] == 0xff { 0x00 } else { 0xff };
|
||||
tokio::fs::write(&target_paths[0], &corrupted)
|
||||
.await
|
||||
.expect("write byte-0 flip");
|
||||
}
|
||||
// Fault 2: 1-byte tail truncation on obj-trunc/part.1
|
||||
{
|
||||
let file = tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&target_paths[1])
|
||||
.await
|
||||
.expect("open part for truncation");
|
||||
file.set_len((original_bytes[1].len() - 1) as u64)
|
||||
.await
|
||||
.expect("truncate 1 byte from tail");
|
||||
}
|
||||
// Fault 3: 4-byte mid-file corruption (\xde\xad\xbe\xef) on obj-meta/xl.meta
|
||||
{
|
||||
let mut corrupted = original_bytes[2].clone();
|
||||
let mid = corrupted.len() / 2;
|
||||
corrupted[mid..mid + 4].copy_from_slice(&[0xde, 0xad, 0xbe, 0xef]);
|
||||
tokio::fs::write(&target_paths[2], &corrupted)
|
||||
.await
|
||||
.expect("corrupt xl.meta mid-file");
|
||||
}
|
||||
|
||||
for (idx, (object, expected_payload)) in payloads.iter().enumerate() {
|
||||
let (result, error) = set
|
||||
.heal_object(
|
||||
bucket,
|
||||
object,
|
||||
"",
|
||||
&HealOpts {
|
||||
no_lock: true,
|
||||
scan_mode: HealScanMode::Deep,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("deep heal should complete");
|
||||
assert!(error.is_none(), "deep heal failed for {object}: {error:?}");
|
||||
assert_eq!(result.drives_healed(), Some(1), "expected 1 drive healed for {object}");
|
||||
|
||||
let restored = tokio::fs::read(&target_paths[idx])
|
||||
.await
|
||||
.expect("healed file should exist on disk");
|
||||
assert_eq!(
|
||||
restored, original_bytes[idx],
|
||||
"on-disk file for {object} (including xl.meta) must be restored byte-for-byte"
|
||||
);
|
||||
|
||||
let mut reader = set
|
||||
.get_object_reader(bucket, object, None, Default::default(), &ObjectOptions::default())
|
||||
.await
|
||||
.expect("GET after deep heal must succeed");
|
||||
let mut got = Vec::new();
|
||||
tokio::io::copy(&mut reader, &mut got).await.expect("read healed payload");
|
||||
assert_eq!(&got, expected_payload, "GET payload mismatch after deep heal for {object}");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FailedIntegrityReadTransport {
|
||||
error: DiskError,
|
||||
@@ -6775,6 +7006,7 @@ mod heal_result_report_tests {
|
||||
opts: &opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&can_commit),
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -11222,6 +11454,50 @@ mod heal_result_report_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn multipool_read_repair_stages_with_shared_ownership() {
|
||||
let (_dirs, store, _peer) = crate::services::rebalance::test_two_pool_stores(None).await;
|
||||
let bucket = "multipool-shared-read-repair";
|
||||
let key = "entry";
|
||||
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
let target = store.pools[1].get_disks_by_key(key);
|
||||
let seeded = target
|
||||
.put_object(bucket, key, &mut PutObjReader::from_vec(b"body".to_vec()), &ObjectOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let (_pause, started, release) = ReadRepairPauseScope::install_at(bucket, key, super::ReadRepairPausePhase::Data);
|
||||
let repair = tokio::spawn(async move {
|
||||
store
|
||||
.heal_object_with_proof(
|
||||
bucket,
|
||||
key,
|
||||
"",
|
||||
&HealOpts {
|
||||
pool: Some(1),
|
||||
read_repair: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), started.notified())
|
||||
.await
|
||||
.expect("enter read repair under the shared object lock");
|
||||
let visible = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(2),
|
||||
target.get_object_info(bucket, key, &ObjectOptions::default()),
|
||||
)
|
||||
.await
|
||||
.expect("read while repair is staging")
|
||||
.unwrap();
|
||||
assert_eq!(visible.etag, seeded.etag);
|
||||
release.notify_one();
|
||||
let outcome = repair.await.unwrap().unwrap();
|
||||
assert!(outcome.error.is_none());
|
||||
assert!(outcome.absence.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn read_repair_storage_entry_keeps_readers_available_during_reconstruction() {
|
||||
@@ -11709,32 +11985,51 @@ mod shard_identity_tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_heal_rejects_complete_donor_shards_ec12_4() {
|
||||
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(16, 0, 4).await;
|
||||
assert_complete_donor_shards_rejected(
|
||||
12,
|
||||
4,
|
||||
5 * 1024 * 1024 + 123,
|
||||
&[
|
||||
(&[1], false),
|
||||
(&[6], false),
|
||||
(&[12], false),
|
||||
(&[13], false),
|
||||
(&[16], false),
|
||||
(&[1, 2, 3, 4], false),
|
||||
(&[1, 2, 3, 4, 5], false),
|
||||
(&[1], true),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_heal_rejects_complete_donor_shards_ec3_3() {
|
||||
assert_complete_donor_shards_rejected(3, 3, 128 * 1024, &[(&[1], false), (&[1, 2, 3, 4], false)]).await;
|
||||
}
|
||||
|
||||
async fn assert_complete_donor_shards_rejected(
|
||||
data_shards: usize,
|
||||
parity_shards: usize,
|
||||
size: usize,
|
||||
cases: &[(&[usize], bool)],
|
||||
) {
|
||||
let (dirs, disks, set) =
|
||||
hermetic_set_disks_for_pool_with_default_parity_isolated(data_shards + parity_shards, 0, parity_shards).await;
|
||||
let bucket = "donor-shard-identity";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("create fixture bucket");
|
||||
}
|
||||
let expected = vec![0x5a; 5 * 1024 * 1024 + 123];
|
||||
let expected = vec![0x5a; size];
|
||||
let donor_body = vec![0xa6; expected.len()];
|
||||
let options = ObjectOptions {
|
||||
shard_integrity_write_mode: Some(crate::object_api::ShardIntegrityWriteMode::Protected),
|
||||
no_lock: true,
|
||||
versioned: true,
|
||||
suppress_read_repair: true,
|
||||
..Default::default()
|
||||
};
|
||||
for (case, (coding_indexes, replace_descriptor)) in [
|
||||
(vec![1], false),
|
||||
(vec![6], false),
|
||||
(vec![12], false),
|
||||
(vec![13], false),
|
||||
(vec![16], false),
|
||||
(vec![1, 2, 3, 4], false),
|
||||
(vec![1, 2, 3, 4, 5], false),
|
||||
(vec![1], true),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
for (case, &(coding_indexes, replace_descriptor)) in cases.iter().enumerate() {
|
||||
let target = format!("target-{case}");
|
||||
let donor = format!("donor-{case}");
|
||||
set.put_object(bucket, &target, &mut PutObjReader::from_vec(expected.clone()), &options)
|
||||
@@ -11757,7 +12052,10 @@ mod shard_identity_tests {
|
||||
.expect("donor metadata"),
|
||||
);
|
||||
}
|
||||
assert_eq!((target_meta[0].erasure.data_blocks, target_meta[0].erasure.parity_blocks), (12, 4));
|
||||
assert_eq!(
|
||||
(target_meta[0].erasure.data_blocks, target_meta[0].erasure.parity_blocks),
|
||||
(data_shards, parity_shards)
|
||||
);
|
||||
let mut before = Vec::new();
|
||||
let mut paths = Vec::new();
|
||||
let mut meta_before = Vec::new();
|
||||
@@ -11770,7 +12068,7 @@ mod shard_identity_tests {
|
||||
meta_before.push(tokio::fs::read(object_path.join("xl.meta")).await.expect("original xl.meta"));
|
||||
paths.push(path);
|
||||
}
|
||||
for index in &coding_indexes {
|
||||
for index in coding_indexes {
|
||||
let target_slot = target_meta
|
||||
.iter()
|
||||
.position(|m| m.erasure.index == *index)
|
||||
@@ -11808,18 +12106,42 @@ mod shard_identity_tests {
|
||||
}
|
||||
}
|
||||
let version = target_meta[0].version_id.expect("versioned fixture").to_string();
|
||||
if coding_indexes.len() <= 4 {
|
||||
let mut reader = set
|
||||
.get_object_reader(bucket, &target, None, Default::default(), &options)
|
||||
.await
|
||||
.expect("recoverable GET before explicit heal");
|
||||
let mut body = Vec::new();
|
||||
reader
|
||||
.stream
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.expect("verify and reconstruct every GET block");
|
||||
assert_eq!(body, expected, "GET must not expose donor data before explicit heal");
|
||||
if coding_indexes.len() <= parity_shards {
|
||||
let explicit_version = ObjectOptions {
|
||||
version_id: Some(version.clone()),
|
||||
..options.clone()
|
||||
};
|
||||
let range_start = size / 5 + 17;
|
||||
let block_size = target_meta[0].erasure.block_size;
|
||||
let range_end = if size > 2 * block_size {
|
||||
2 * block_size - 1
|
||||
} else {
|
||||
size / 2 + 99
|
||||
};
|
||||
for (range, expected_body, options) in [
|
||||
(None, expected.as_slice(), &options),
|
||||
(
|
||||
Some(HTTPRangeSpec {
|
||||
start: i64::try_from(range_start).expect("fixture range start"),
|
||||
end: i64::try_from(range_end).expect("fixture range end"),
|
||||
is_suffix_length: false,
|
||||
}),
|
||||
&expected[range_start..=range_end],
|
||||
&explicit_version,
|
||||
),
|
||||
] {
|
||||
let mut reader = set
|
||||
.get_object_reader(bucket, &target, range, Default::default(), options)
|
||||
.await
|
||||
.expect("recoverable GET before explicit heal");
|
||||
let mut body = Vec::new();
|
||||
reader
|
||||
.stream
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.expect("complete verified GET body");
|
||||
assert_eq!(body, expected_body, "GET must not expose donor data before explicit heal");
|
||||
}
|
||||
}
|
||||
let heal = set
|
||||
.heal_object(
|
||||
@@ -11833,7 +12155,7 @@ mod shard_identity_tests {
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if coding_indexes.len() <= 4 {
|
||||
if coding_indexes.len() <= parity_shards {
|
||||
let (result, error) = heal.expect("recoverable donor mismatch");
|
||||
assert!(error.is_none(), "{error:?}");
|
||||
assert_eq!(
|
||||
@@ -11848,42 +12170,10 @@ mod shard_identity_tests {
|
||||
"reconstruct exact original bytes at slot {slot}"
|
||||
);
|
||||
}
|
||||
for (range, expected_range) in [
|
||||
(None, expected.as_slice()),
|
||||
(
|
||||
Some(HTTPRangeSpec {
|
||||
start: 1024 * 1024 + 17,
|
||||
end: 2 * 1024 * 1024 + 99,
|
||||
is_suffix_length: false,
|
||||
}),
|
||||
&expected[1024 * 1024 + 17..2 * 1024 * 1024 + 100],
|
||||
),
|
||||
] {
|
||||
let mut reader = set
|
||||
.get_object_reader(
|
||||
bucket,
|
||||
&target,
|
||||
range,
|
||||
Default::default(),
|
||||
&ObjectOptions {
|
||||
version_id: Some(version.clone()),
|
||||
..options.clone()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("read repaired version");
|
||||
let mut body = Vec::new();
|
||||
reader
|
||||
.stream
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.expect("complete verified GET body");
|
||||
assert_eq!(body, expected_range, "full and range GET must match original bytes");
|
||||
}
|
||||
} else {
|
||||
assert!(
|
||||
heal.as_ref().map_or(true, |(_, error)| error.is_some()),
|
||||
"eleven authoritative sources must not produce a successful heal"
|
||||
"read quorum minus one authoritative sources must not produce a successful heal"
|
||||
);
|
||||
let read = set
|
||||
.get_object_reader(bucket, &target, None, Default::default(), &options)
|
||||
@@ -11908,6 +12198,97 @@ mod shard_identity_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_aligned_range_reads_before_truncated_suffix() {
|
||||
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
|
||||
let bucket = "protected-range-boundary";
|
||||
let object = "truncated-suffix";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("create fixture bucket");
|
||||
}
|
||||
let mut expected = vec![0; 3 * 1024 * 1024 + 17];
|
||||
for (index, block) in expected.chunks_mut(4096).enumerate() {
|
||||
block.fill(u8::try_from(index % 251).expect("fixture byte"));
|
||||
}
|
||||
let options = ObjectOptions {
|
||||
shard_integrity_write_mode: Some(crate::object_api::ShardIntegrityWriteMode::Protected),
|
||||
no_lock: true,
|
||||
versioned: true,
|
||||
suppress_read_repair: true,
|
||||
..Default::default()
|
||||
};
|
||||
set.put_object(bucket, object, &mut PutObjReader::from_vec(expected.clone()), &options)
|
||||
.await
|
||||
.expect("write protected fixture");
|
||||
|
||||
let mut read_range = None;
|
||||
for (disk, dir) in disks.iter().zip(&dirs) {
|
||||
let info = disk
|
||||
.read_version("", bucket, object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("read committed version");
|
||||
let part = info.parts[0].integrity.as_ref().expect("independent commitment");
|
||||
assert!(part.stripes > 2);
|
||||
let codec = crate::erasure::coding::Erasure::try_new_with_options(
|
||||
info.erasure.data_blocks,
|
||||
info.erasure.parity_blocks,
|
||||
info.erasure.block_size,
|
||||
info.uses_legacy_checksum,
|
||||
)
|
||||
.expect("committed layout");
|
||||
let range = codec.block_size + 7..2 * codec.block_size;
|
||||
let hash_size = info.erasure.get_checksum_info(1).algorithm.size();
|
||||
let valid_len = u64::try_from(2 * (codec.shard_size() + hash_size)).expect("test shard length");
|
||||
let path = dir
|
||||
.path()
|
||||
.join(bucket)
|
||||
.join(object)
|
||||
.join(info.data_dir.expect("external part").to_string())
|
||||
.join("part.1");
|
||||
tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.await
|
||||
.expect("open committed shard")
|
||||
.set_len(valid_len)
|
||||
.await
|
||||
.expect("remove only the unrequested suffix");
|
||||
read_range = Some(range);
|
||||
}
|
||||
let range = read_range.expect("fixture has disks");
|
||||
let mut reader = set
|
||||
.get_object_reader(
|
||||
bucket,
|
||||
object,
|
||||
Some(HTTPRangeSpec {
|
||||
start: i64::try_from(range.start).expect("fixture range start"),
|
||||
end: i64::try_from(range.end - 1).expect("fixture range end"),
|
||||
is_suffix_length: false,
|
||||
}),
|
||||
Default::default(),
|
||||
&options,
|
||||
)
|
||||
.await
|
||||
.expect("aligned protected Range must ignore the truncated suffix");
|
||||
let mut body = Vec::new();
|
||||
reader
|
||||
.stream
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.expect("read the verified aligned range");
|
||||
assert_eq!(body, expected[range]);
|
||||
|
||||
if let Ok(mut full) = set
|
||||
.get_object_reader(bucket, object, None, Default::default(), &options)
|
||||
.await
|
||||
{
|
||||
assert!(
|
||||
full.stream.read_to_end(&mut Vec::new()).await.is_err(),
|
||||
"a full GET must reject the truncated object"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_inline_donor_repair_and_late_external_get() {
|
||||
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(4, 0, 2).await;
|
||||
|
||||
@@ -33,22 +33,22 @@ use super::super::{
|
||||
Arc, Bytes, CompletePart, Cursor, DATA_MOVEMENT_MULTIPART_PREFIX, DiskError, DiskStore, EVENT_SET_DISK_MULTIPART, Error,
|
||||
FileInfo, FileMeta, GLOBAL_MIN_PART_SIZE, HashAlgorithm, HashMap, HashReader, HashSet, HealChannelPriority, Instant,
|
||||
LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_SET_DISK, ListMultipartsInfo, ListPartsInfo, MAX_PARTS_COUNT,
|
||||
MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA, MULTIPART_WRITE_QUORUM_WRITER_SETUP,
|
||||
MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence, OBJECT_OP_IGNORED_ERRS, ObjectInfo,
|
||||
ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo, PutObjReader, RUSTFS_META_MULTIPART_BUCKET,
|
||||
RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY, Result, SLASH_SEPARATOR,
|
||||
SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID, SUFFIX_COMPRESSION_SIZE,
|
||||
SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID, SUFFIX_RESTORE_WORKER_LOCK, SetDisks,
|
||||
SmallWritePath, StorageError, Uuid, WriteLayout, check_object_lock_for_deletion_with_state,
|
||||
classify_multipart_part_write_path, coding, complete_multipart_part_error, complete_multipart_part_error_result,
|
||||
complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug, disk, error,
|
||||
file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str, is_err_object_not_found,
|
||||
is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure, multipart_part_logical_size,
|
||||
parts_after_marker, path_join_buf, prepare_complete_multipart_parts, record_compression_total_memory,
|
||||
record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs, remove_header_map,
|
||||
replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout, restore_commit_operation_id_from_metadata,
|
||||
restore_operation_id_from_metadata, should_persist_encryption_original_size, strip_internal_multipart_metadata,
|
||||
to_object_err, warn,
|
||||
MULTIPART_GENERATED_VERSION_SUFFIX, MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA,
|
||||
MULTIPART_WRITE_QUORUM_WRITER_SETUP, MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence,
|
||||
OBJECT_OP_IGNORED_ERRS, ObjectInfo, ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo,
|
||||
PutObjReader, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY,
|
||||
Result, SLASH_SEPARATOR, SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID,
|
||||
SUFFIX_COMPRESSION_SIZE, SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID,
|
||||
SUFFIX_RESTORE_WORKER_LOCK, SetDisks, SmallWritePath, StorageError, Uuid, WriteLayout,
|
||||
check_object_lock_for_deletion_with_state, classify_multipart_part_write_path, coding, complete_multipart_part_error,
|
||||
complete_multipart_part_error_result, complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug,
|
||||
disk, error, file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str,
|
||||
is_err_object_not_found, is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure,
|
||||
multipart_part_logical_size, parts_after_marker, path_join_buf, prepare_complete_multipart_parts,
|
||||
record_compression_total_memory, record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs,
|
||||
remove_header_map, replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout,
|
||||
restore_commit_operation_id_from_metadata, restore_operation_id_from_metadata, should_persist_encryption_original_size,
|
||||
strip_internal_multipart_metadata, to_object_err, warn,
|
||||
};
|
||||
use super::bitrot_self_verify::{
|
||||
BitrotSelfVerifyTarget, WrittenBitrotShards, drop_failed_writer_disks, verify_written_bitrot_shards,
|
||||
@@ -62,6 +62,7 @@ use super::object::{
|
||||
use crate::api::config::storageclass;
|
||||
use crate::bucket::metadata_sys::ObjectLockConfigState;
|
||||
use crate::bucket::quota::reservation;
|
||||
#[cfg(test)]
|
||||
use crate::bucket::replication::ReplicationStatusType;
|
||||
use crate::crash_inject::{self, CrashPoint};
|
||||
#[cfg(test)]
|
||||
@@ -905,6 +906,8 @@ pub enum MultipartCommitPause {
|
||||
PutPartAfterRename,
|
||||
AbortBeforeDelete,
|
||||
AbortAfterDelete,
|
||||
#[cfg(test)]
|
||||
BeforeConditionalNamespace,
|
||||
BeforeLockLost,
|
||||
BeforeQuotaRename,
|
||||
BeforeTransactionEpochVerify,
|
||||
@@ -1054,6 +1057,23 @@ impl Drop for NewMultipartUploadCommitObservation {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "dst")]
|
||||
fn should_dst_crash_multipart(
|
||||
disks: &[Option<DiskStore>],
|
||||
point: rustfs_dst_faults::crash::CrashPoint,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
) -> bool {
|
||||
let full_key = format!("{bucket}/{object}");
|
||||
disks.iter().flatten().any(|disk| match disk.as_ref() {
|
||||
crate::disk::Disk::Sim(sim) => {
|
||||
let registry = sim.crash_registry();
|
||||
registry.take_if_armed(point, object) || registry.take_if_armed(point, &full_key)
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn observe_new_multipart_upload_commit(bucket: &str, object: &str) {
|
||||
let state = NEW_MULTIPART_UPLOAD_COMMIT_OBSERVATION
|
||||
@@ -3730,15 +3750,39 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let opts = &commit_opts;
|
||||
let result: Result<PartInfo> = async {
|
||||
let commit_check_started = rustfs_io_metrics::put_stage_timer();
|
||||
let fast_commit_head_verified = _upload_commit_guard.is_some() && multipart_size_limit.is_none() && {
|
||||
let commit_disks = commit_set.get_disks_internal().await;
|
||||
commit_disks.len() == commit_set.set_drive_count
|
||||
&& commit_disks.iter().all(|disk| {
|
||||
disk.as_ref().is_some_and(|disk| {
|
||||
disk.has_active_multipart_source_matching(&upload_id_path, fi.data_dir, fi.mod_time)
|
||||
})
|
||||
})
|
||||
};
|
||||
let (fast_commit_head_verified, fast_part_clean_verified) =
|
||||
if _upload_commit_guard.is_some() && multipart_size_limit.is_none() {
|
||||
let commit_disks = commit_set.get_disks_internal().await;
|
||||
if commit_disks.len() == commit_set.set_drive_count {
|
||||
let mut all_head_matched = true;
|
||||
let mut all_part_clean = true;
|
||||
for disk in &commit_disks {
|
||||
let Some(disk) = disk.as_ref() else {
|
||||
all_head_matched = false;
|
||||
all_part_clean = false;
|
||||
break;
|
||||
};
|
||||
let (head_matched, part_clean) = disk
|
||||
.check_active_multipart_source_matching_and_clean_part(
|
||||
&upload_id_path,
|
||||
fi.data_dir,
|
||||
fi.mod_time,
|
||||
part_id,
|
||||
);
|
||||
if !head_matched {
|
||||
all_head_matched = false;
|
||||
all_part_clean = false;
|
||||
break;
|
||||
}
|
||||
all_part_clean &= part_clean;
|
||||
}
|
||||
(all_head_matched, all_part_clean)
|
||||
} else {
|
||||
(false, false)
|
||||
}
|
||||
} else {
|
||||
(false, false)
|
||||
};
|
||||
let commit_fi = if fast_commit_head_verified {
|
||||
fi.clone()
|
||||
} else {
|
||||
@@ -3845,7 +3889,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
commit_staging_cleanup.disarm();
|
||||
let rename_started = rustfs_io_metrics::put_stage_timer();
|
||||
let rename_result = commit_set
|
||||
.rename_part(
|
||||
.rename_part_with_clean_hint(
|
||||
&shuffle_disks,
|
||||
RUSTFS_META_TMP_BUCKET,
|
||||
&tmp_part_path,
|
||||
@@ -3860,6 +3904,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
upload_id,
|
||||
part_number: Some(part_id),
|
||||
}),
|
||||
fast_part_clean_verified,
|
||||
)
|
||||
.await;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from("multipart_set_disk_rename_part", rename_started);
|
||||
@@ -3880,6 +3925,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
last_mod: Some(OffsetDateTime::now_utc()),
|
||||
size: w_size,
|
||||
actual_size,
|
||||
checksums: part_info.checksums,
|
||||
};
|
||||
|
||||
// error!("put_object_part ret {:?}", &ret);
|
||||
@@ -3978,6 +4024,19 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
bucket: owner.bucket,
|
||||
object: owner.object,
|
||||
});
|
||||
// The upload records its checksum algorithm and type at CreateMultipartUpload.
|
||||
// ListParts echoes them like CreateMultipartUpload and CompleteMultipartUpload do,
|
||||
// so a client that resumes an upload can state the same checksum contract.
|
||||
let checksum_algorithm = fi
|
||||
.metadata
|
||||
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let checksum_type = fi
|
||||
.metadata
|
||||
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut ret = ListPartsInfo {
|
||||
recorded_owner,
|
||||
bucket: bucket.to_owned(),
|
||||
@@ -3986,6 +4045,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
storage_class,
|
||||
max_parts,
|
||||
part_number_marker,
|
||||
checksum_algorithm,
|
||||
checksum_type,
|
||||
user_defined: {
|
||||
let mut metadata = fi.metadata.clone();
|
||||
strip_internal_multipart_metadata(&mut metadata);
|
||||
@@ -4078,6 +4139,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
last_mod: part.mod_time,
|
||||
size: part.size,
|
||||
actual_size: part.actual_size,
|
||||
checksums: part.checksums.clone(),
|
||||
});
|
||||
|
||||
count -= 1;
|
||||
@@ -4185,6 +4247,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_PART_CHECKSUMS);
|
||||
if !opts.data_movement {
|
||||
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_DATA_MOVEMENT_UPLOAD);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
}
|
||||
rustfs_utils::http::metadata_compat::remove_str(
|
||||
&mut user_defined,
|
||||
@@ -4234,18 +4297,19 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
}
|
||||
|
||||
fi.version_id = if let Some(vid) = &opts.version_id {
|
||||
Some(Uuid::parse_str(vid)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if opts.versioned && opts.version_id.is_none() {
|
||||
fi.version_id = Some(Uuid::new_v4());
|
||||
}
|
||||
|
||||
let data_dir = Uuid::new_v4();
|
||||
fi.data_dir = Some(data_dir);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX);
|
||||
fi.version_id = match &opts.version_id {
|
||||
Some(id) => Some(Uuid::parse_str(id)?),
|
||||
None if opts.versioned => {
|
||||
let id = Uuid::new_v4();
|
||||
insert_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX, format!("{data_dir}/{id}"));
|
||||
Some(id)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
if crate::object_api::legacy_encrypted_range_seek_enabled()
|
||||
&& !opts.no_lock
|
||||
&& should_persist_encryption_original_size(&user_defined)
|
||||
@@ -4427,7 +4491,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
result
|
||||
}
|
||||
|
||||
// complete_multipart_upload finished
|
||||
#[tracing::instrument(level = "trace", skip(self))]
|
||||
async fn complete_multipart_upload(
|
||||
self: Arc<Self>,
|
||||
@@ -4436,6 +4499,21 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
upload_id: &str,
|
||||
uploaded_parts: Vec<CompletePart>,
|
||||
opts: &ObjectOptions,
|
||||
) -> Result<ObjectInfo> {
|
||||
self.complete_multipart_upload_with_store(bucket, object, upload_id, uploaded_parts, opts, None)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl SetDisks {
|
||||
pub(crate) async fn complete_multipart_upload_with_store(
|
||||
self: Arc<Self>,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
upload_id: &str,
|
||||
uploaded_parts: Vec<CompletePart>,
|
||||
opts: &ObjectOptions,
|
||||
multipool_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<ObjectInfo> {
|
||||
crate::hp_guard!("SetDisks::complete_multipart_upload");
|
||||
let write_context = WriteCommitContext::from_options(opts, bucket, object, false)?;
|
||||
@@ -4445,8 +4523,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let range_seek_rollout_enabled =
|
||||
crate::object_api::legacy_encrypted_range_seek_enabled() && write_context.acquires_namespace();
|
||||
let mut object_lock_guard = None;
|
||||
let mut decommission_object_lock_guard = None;
|
||||
let mut decommission_target_lock_covered = false;
|
||||
let mut store_object_guards: Option<Arc<[crate::store::ObjectLockDiagGuard]>> = None;
|
||||
let has_lost_store_lock =
|
||||
|guards: &[crate::store::ObjectLockDiagGuard]| guards.iter().any(crate::store::ObjectLockDiagGuard::is_lock_lost);
|
||||
let mut decommission_capacity_guard = None;
|
||||
|
||||
// Lock order: lifecycle -> metadata transaction -> object namespace -> upload.
|
||||
@@ -4467,44 +4546,62 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
opts
|
||||
};
|
||||
|
||||
if opts.http_preconditions.is_some() {
|
||||
if write_context.acquires_namespace() {
|
||||
object_lock_guard = Some(
|
||||
self.acquire_write_lock_diag("complete_multipart_upload_precondition", bucket, object)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(err) = self.check_write_precondition(bucket, object, opts).await {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
// Conditional publication requires namespace locking. Ordinary writes retain
|
||||
// the selected set's namespace when deployment-wide locking is disabled.
|
||||
let multipool_locks =
|
||||
multipool_store.filter(|_| opts.http_preconditions.is_some() || !self.ctx.lock_manager().is_disabled());
|
||||
let target_covered = if let Some(store) = multipool_locks.or(opts.decommission_capacity_admission.as_deref()) {
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
|
||||
}
|
||||
let (object_guard, target_lock_covered, capacity_guard) = store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
!write_context.acquires_namespace() || object_lock_guard.is_some(),
|
||||
DecommissionCapacityAdmission::ExistingMultipart,
|
||||
)
|
||||
.await?;
|
||||
decommission_object_lock_guard = object_guard;
|
||||
decommission_target_lock_covered = target_lock_covered;
|
||||
decommission_capacity_guard = capacity_guard;
|
||||
}
|
||||
if write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered {
|
||||
if multipool_locks.is_some() {
|
||||
#[cfg(test)]
|
||||
if opts.http_preconditions.is_some() {
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeConditionalNamespace).await;
|
||||
}
|
||||
store_object_guards = Some(
|
||||
Box::pin(store.acquire_physical_object_write_locks(
|
||||
"complete_multipart_upload_commit",
|
||||
bucket,
|
||||
object,
|
||||
write_context.borrowed_write_guards(bucket, object),
|
||||
))
|
||||
.await?
|
||||
.into(),
|
||||
);
|
||||
true
|
||||
} else if write_context.acquires_namespace() {
|
||||
let guard = store.acquire_external_commit_namespace(bucket, object, &self).await?;
|
||||
store_object_guards = Some(Arc::new([guard]));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if write_context.acquires_namespace() && !target_covered {
|
||||
object_lock_guard = Some(
|
||||
self.acquire_write_lock_diag("complete_multipart_upload_commit", bucket, object)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
let conditional_current = match multipool_store {
|
||||
Some(store) if opts.http_preconditions.is_some() => {
|
||||
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
|
||||
}
|
||||
Some(_) => None,
|
||||
None => {
|
||||
if opts.http_preconditions.is_some()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
let mut upload_guard = self
|
||||
.acquire_multipart_upload_write_lock("complete_multipart_upload_commit", bucket, object, upload_id, opts)
|
||||
.await?;
|
||||
@@ -4646,6 +4743,13 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
ensure_multipart_bucket_lifecycle_lock_held(bucket, object, opts)?;
|
||||
}
|
||||
let source_condition = capture_source_condition(bucket, object, &upload_id_path, &fi, Uuid::new_v4())?;
|
||||
// A marker copied from a prior object cannot establish how this upload's version was assigned.
|
||||
let generated_version = get_consistent_str(&fi.metadata, MULTIPART_GENERATED_VERSION_SUFFIX).and_then(|marker| {
|
||||
source_condition
|
||||
.lineage
|
||||
.original_version_id
|
||||
.filter(|id| marker == format!("{}/{id}", source_condition.lineage.original_data_dir))
|
||||
});
|
||||
let preserved_encrypted_etag = preserves_staged_encrypted_etag_proof(&fi, opts, expected_restore_operation_id);
|
||||
let upload_data_dir = source_condition.lineage.original_data_dir.to_string();
|
||||
// The source generation remains in the captured precondition. Its
|
||||
@@ -4671,9 +4775,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
// and heterogeneous replication clients can send an authorized
|
||||
// REPLICA status on Complete without repeating the source-request
|
||||
// marker, so either authenticated parser result is sufficient.
|
||||
let authorized_inbound_replica =
|
||||
opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica;
|
||||
if !authorized_inbound_replica {
|
||||
if !opts.is_inbound_multipart_replica() {
|
||||
fi.metadata
|
||||
.retain(|key, _| !key.eq_ignore_ascii_case(metadata_keys::REPLICATION_STATUS));
|
||||
for suffix in [
|
||||
@@ -4736,8 +4838,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
// source's null version, so its completion keeps the null version,
|
||||
// exactly like the single-PUT path (rustfs/rustfs#8747). Any other
|
||||
// completion in a versioned bucket gets a concrete version.
|
||||
let replicated_null_version = fi.version_id.is_none_or(|version_id| version_id.is_nil())
|
||||
&& (opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica);
|
||||
let replicated_null_version =
|
||||
fi.version_id.is_none_or(|version_id| version_id.is_nil()) && opts.is_inbound_multipart_replica();
|
||||
if opts.restore_copyback {
|
||||
require_multipart_restore_target(opts, fi.version_id)?;
|
||||
} else if opts.versioned && replicated_null_version {
|
||||
@@ -4757,6 +4859,23 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
} else {
|
||||
fi.version_id = None;
|
||||
}
|
||||
let predecessors = match multipool_store {
|
||||
Some(store) => {
|
||||
let current = if opts.http_preconditions.is_some() {
|
||||
conditional_current
|
||||
} else {
|
||||
// An unconditional replay returns before it needs the current head.
|
||||
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
|
||||
};
|
||||
// A version already visible under this UUID is an overwrite, even
|
||||
// if Create generated it. Legacy uploads can also name a historical version.
|
||||
let target = fi.version_id.unwrap_or_default();
|
||||
let matches_head = current.as_ref().is_some_and(|info| info.version_id == Some(target));
|
||||
let replaced = (matches_head || Some(target) != generated_version).then_some(target);
|
||||
Some(Box::pin(store.resolve_put_predecessors(bucket, object, opts, current, replaced)).await?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let write_quorum = fi.write_quorum(self.default_write_quorum());
|
||||
let read_quorum = fi.read_quorum(self.default_read_quorum());
|
||||
|
||||
@@ -5173,6 +5292,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
|
||||
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
|
||||
strip_internal_multipart_metadata(&mut fi.metadata);
|
||||
if !opts.data_movement {
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
}
|
||||
if opts.restore_copyback {
|
||||
insert_str(
|
||||
&mut fi.metadata,
|
||||
@@ -5189,7 +5311,11 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
fi.size = object_size as i64;
|
||||
fi.mod_time = opts.mod_time;
|
||||
if fi.mod_time.is_none() {
|
||||
fi.mod_time = Some(OffsetDateTime::now_utc());
|
||||
let now = OffsetDateTime::now_utc();
|
||||
fi.mod_time = Some(match &predecessors {
|
||||
Some(predecessors) => predecessors.commit_time(now)?,
|
||||
None => now,
|
||||
});
|
||||
}
|
||||
|
||||
// etag
|
||||
@@ -5268,11 +5394,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
// other read failures must leave the upload retryable rather than
|
||||
// committing inbound metadata without the LWW check.
|
||||
//
|
||||
// The same read enforces the commit-time WORM gate on the staged
|
||||
// `fi.version_id`, which the completion request does not name. An
|
||||
// ordinary upload stages a fresh UUID and finds no version here;
|
||||
// `opts.restore_copyback` and `opts.data_movement` run their stricter
|
||||
// checks below.
|
||||
// Create can name the version to replace without repeating it at Complete.
|
||||
// Reuse the locked cross-pool predecessor when available. Replication
|
||||
// judges the destination set's version and metadata together.
|
||||
let snapshot_state = opts.object_lock_config_snapshot.as_deref().map(|snapshot| snapshot.state());
|
||||
let need_worm_lookup = !opts.data_movement
|
||||
&& !opts.restore_copyback
|
||||
@@ -5283,28 +5407,35 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if (need_worm_lookup || replication_lww_applicable)
|
||||
&& let Some(version_id) = target_version_id
|
||||
{
|
||||
match self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(existing) => {
|
||||
let local;
|
||||
let existing = match &predecessors {
|
||||
Some(predecessors) => Ok(predecessors.replaced().filter(|info| !info.delete_marker)),
|
||||
None => {
|
||||
local = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
local.as_ref().map(Some).map_err(Clone::clone)
|
||||
}
|
||||
};
|
||||
match existing {
|
||||
Ok(Some(existing)) => {
|
||||
if !opts.data_movement && !opts.restore_copyback && !crate::bucket::utils::is_meta_bucketname(bucket) {
|
||||
let effective_state = snapshot_state.unwrap_or(&ObjectLockConfigState::ConfirmedAbsent);
|
||||
if check_object_lock_for_deletion_with_state(effective_state, &existing, false)?.is_some() {
|
||||
if check_object_lock_for_deletion_with_state(effective_state, existing, false)?.is_some() {
|
||||
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
|
||||
effective_state,
|
||||
&existing,
|
||||
existing,
|
||||
opts,
|
||||
&fi.metadata,
|
||||
)? {
|
||||
@@ -5338,9 +5469,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
#[cfg(test)]
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5399,7 +5528,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
|
||||
drop(object_lock_guard.take());
|
||||
drop(decommission_object_lock_guard.take());
|
||||
drop(store_object_guards.take());
|
||||
drop(decommission_capacity_guard.take());
|
||||
if let Err(err) = self
|
||||
.delete_all_with_quorum(RUSTFS_META_MULTIPART_BUCKET, &upload_id_path, write_quorum)
|
||||
@@ -5425,10 +5554,11 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
}
|
||||
if replication_lww_applicable {
|
||||
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(&existing);
|
||||
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(existing);
|
||||
crate::set_disk::ops::object::merge_replication_metadata_lww(&mut fi.metadata, &stored, opts);
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
// A null delete marker has no protected payload to replace.
|
||||
Err(StorageError::MethodNotAllowed) if version_id.is_nil() => {}
|
||||
// Version absent: a fresh version id or the first replication
|
||||
@@ -5486,9 +5616,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
#[cfg(test)]
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5600,9 +5728,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
}
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5640,7 +5766,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
// Recheck decommission capacity only after those locks, and retain the
|
||||
// guard through the durable rename below.
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
&& let Some(store) = multipool_store.or(opts.decommission_capacity_admission.as_deref())
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
store
|
||||
@@ -5677,9 +5803,12 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
copy_publication_controls(&fi.metadata, &mut metadata.metadata)?;
|
||||
}
|
||||
|
||||
let put_usage = predecessors.as_deref().map(|previous| previous.usage_receipt()).transpose()?;
|
||||
let quota_old_size = if quota_context.is_enforced() {
|
||||
if opts.data_movement {
|
||||
quota_new_size
|
||||
} else if let Some(usage) = &put_usage {
|
||||
usage.replaced_size()
|
||||
} else {
|
||||
reservation::replaced_logical_size(&self, bucket, object, opts).await?
|
||||
}
|
||||
@@ -5748,7 +5877,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let commit_capacity_scope_token = opts.capacity_scope_token;
|
||||
let commit_object_lock_guard = object_lock_guard.take().map(Arc::new);
|
||||
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
|
||||
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take().map(Arc::new);
|
||||
let commit_store_object_guards = store_object_guards;
|
||||
let multipool_publication = multipool_locks.is_some();
|
||||
let commit_decommission_capacity_guard = decommission_capacity_guard.take().map(Arc::new);
|
||||
// CompleteMultipartUpload is an S3 publication boundary: after a
|
||||
// successful response, the object must be immediately readable and
|
||||
@@ -5761,7 +5891,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let write_context = Arc::new(write_context);
|
||||
let mut _object_lock_guard = commit_object_lock_guard;
|
||||
let _object_lock_config_snapshot = commit_object_lock_config_snapshot;
|
||||
let mut _decommission_object_lock_guard = commit_decommission_object_lock_guard;
|
||||
let mut _store_object_guards = commit_store_object_guards;
|
||||
let mut _upload_guard = upload_guard.map(Arc::new);
|
||||
let mut _decommission_capacity_guard = commit_decommission_capacity_guard;
|
||||
let mut quota_reservation = quota_reservation;
|
||||
@@ -5776,15 +5906,22 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if crash_inject::should_crash_at(CrashPoint::MultipartBeforeCommitRename, &commit_object) {
|
||||
return Err(StorageError::Unexpected);
|
||||
}
|
||||
#[cfg(feature = "dst")]
|
||||
if should_dst_crash_multipart(
|
||||
&commit_disks,
|
||||
rustfs_dst_faults::crash::CrashPoint::MultipartBeforeCommitRename,
|
||||
&commit_bucket,
|
||||
&commit_object,
|
||||
) {
|
||||
return Err(StorageError::Unexpected);
|
||||
}
|
||||
quota_reservation.mark_commit_started().await?;
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pause_multipart_commit(&commit_bucket, &commit_object, MultipartCommitPause::BeforeQuotaRename).await;
|
||||
if quota_reservation.is_lock_lost()
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| commit_namespace_lock_fence
|
||||
.as_ref()
|
||||
@@ -5836,9 +5973,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if quota_reservation.is_lock_lost()
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| commit_namespace_lock_fence
|
||||
.as_ref()
|
||||
@@ -5886,7 +6021,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let multipart_commit_owner = crate::set_disk::core::io_primitives::MultipartLogicalGuards::new((
|
||||
write_context.clone(),
|
||||
_object_lock_guard.clone(),
|
||||
_decommission_object_lock_guard.clone(),
|
||||
_store_object_guards.clone(),
|
||||
_upload_guard.clone(),
|
||||
_decommission_capacity_guard.clone(),
|
||||
commit_namespace_lock_fence.clone(),
|
||||
@@ -5978,6 +6113,15 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if crash_inject::should_crash_at(CrashPoint::MultipartAfterCommitBeforePartsCleanup, &commit_object) {
|
||||
return Err(StorageError::Unexpected);
|
||||
}
|
||||
#[cfg(feature = "dst")]
|
||||
if should_dst_crash_multipart(
|
||||
&commit_disks,
|
||||
rustfs_dst_faults::crash::CrashPoint::MultipartAfterCommitBeforeCleanup,
|
||||
&commit_bucket,
|
||||
&commit_object,
|
||||
) {
|
||||
return Err(StorageError::Unexpected);
|
||||
}
|
||||
|
||||
fi = committed_file_info;
|
||||
let committed_dir = fi.data_dir.unwrap_or_default().to_string();
|
||||
@@ -5992,6 +6136,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
.await;
|
||||
|
||||
drop(_object_lock_guard.take()); // release the object lock before multipart cleanup IO.
|
||||
if multipool_publication {
|
||||
drop(_store_object_guards.take());
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pause_multipart_commit(&commit_bucket, &commit_object, MultipartCommitPause::AfterObjectPublication).await;
|
||||
@@ -6055,6 +6202,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
|
||||
let mut obj_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
|
||||
obj_info.backfilled_old_current_size = old_current_size;
|
||||
obj_info.put_usage = put_usage;
|
||||
Ok(obj_info)
|
||||
};
|
||||
|
||||
@@ -7547,6 +7695,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_object_parts_echoes_upload_and_part_checksums() {
|
||||
let (_temp_dirs, disks, set_disks) = hermetic_set_disks(4).await;
|
||||
let bucket = "multipart-checksum-listing";
|
||||
let object = "object";
|
||||
make_bucket_on_all(&disks, bucket).await;
|
||||
let payloads: [&[u8]; 2] = [b"first checksummed part", b"second checksummed part"];
|
||||
let (upload_id, _, checksums) =
|
||||
stage_checksummed_multipart_upload(&set_disks, bucket, object, Some(rustfs_rio::ChecksumType::SHA256), &payloads)
|
||||
.await;
|
||||
|
||||
let page = set_disks
|
||||
.list_object_parts(bucket, object, &upload_id, None, 10, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("checksummed parts should be listable");
|
||||
|
||||
assert_eq!(page.checksum_algorithm, "SHA256");
|
||||
assert_eq!(page.checksum_type, "COMPOSITE");
|
||||
assert_eq!(page.parts.len(), payloads.len());
|
||||
for (part, checksum) in page.parts.iter().zip(&checksums) {
|
||||
assert_eq!(
|
||||
part.checksums.as_ref().and_then(|checksums| checksums.get("SHA256")),
|
||||
Some(&checksum.encoded),
|
||||
"part {} must echo its recorded checksum",
|
||||
part.part_num
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_parts_baseline_legacy_owner_metadata() {
|
||||
let (_roots, disks, set) = hermetic_set_disks(4).await;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1550,7 +1550,7 @@ impl SetDisks {
|
||||
.await?;
|
||||
if let Some(expected) = part.integrity.as_ref() {
|
||||
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(1))?;
|
||||
for (index, reader) in readers.iter_mut().enumerate() {
|
||||
if let Some(reader) = reader {
|
||||
reader.set_integrity(ShardVerifier::new(Arc::clone(&proof), index, 0, None)?)?;
|
||||
@@ -1618,7 +1618,7 @@ impl SetDisks {
|
||||
erasure.data_shards,
|
||||
)
|
||||
.await;
|
||||
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0)?;
|
||||
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0..1)?;
|
||||
let reader_setup_elapsed = reader_setup_stage_start.elapsed();
|
||||
rustfs_io_metrics::record_get_object_shard_reader_setup_duration(reader_setup_elapsed.as_secs_f64());
|
||||
rustfs_io_metrics::record_get_object_stage_duration_by_size(
|
||||
@@ -1926,7 +1926,7 @@ impl SetDisks {
|
||||
);
|
||||
}
|
||||
}
|
||||
let (reader_setup, reader_setup_elapsed) = match setup_result {
|
||||
let (mut reader_setup, mut reader_setup_elapsed) = match setup_result {
|
||||
Some(result) => result,
|
||||
None => {
|
||||
setup_multipart_part_readers(
|
||||
@@ -1934,7 +1934,7 @@ impl SetDisks {
|
||||
&disks,
|
||||
bucket,
|
||||
object,
|
||||
sync_spec,
|
||||
sync_spec.clone(),
|
||||
erasure.shard_size(),
|
||||
erasure.data_shards,
|
||||
erasure.parity_shards,
|
||||
@@ -1949,6 +1949,55 @@ impl SetDisks {
|
||||
}
|
||||
};
|
||||
|
||||
// If read quorum is about to fail because some remote disks are still in `Returning`
|
||||
// or `Offline` (e.g. immediately after a peer restarted in a rolling upgrade/rollback),
|
||||
// probe those faulty drives on demand once before failing with 503.
|
||||
if reader_setup.available_shards() < erasure.data_shards {
|
||||
let faulty_disks: Vec<DiskStore> = reader_setup
|
||||
.errors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, err)| {
|
||||
if matches!(err, Some(DiskError::FaultyDisk | DiskError::FaultyRemoteDisk)) {
|
||||
disks.get(idx).and_then(|d| d.as_ref()).filter(|d| d.is_faulty()).cloned()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !faulty_disks.is_empty() {
|
||||
let mut probes: FuturesUnordered<_> = faulty_disks
|
||||
.into_iter()
|
||||
.map(|disk| async move { disk.probe_quorum_recovery_if_faulty().await })
|
||||
.collect();
|
||||
let mut recovered_any = false;
|
||||
while let Some(recovered) = probes.next().await {
|
||||
recovered_any |= recovered;
|
||||
}
|
||||
if recovered_any {
|
||||
let (retried_setup, retried_elapsed) = setup_multipart_part_readers(
|
||||
&files,
|
||||
&disks,
|
||||
bucket,
|
||||
object,
|
||||
sync_spec,
|
||||
erasure.shard_size(),
|
||||
erasure.data_shards,
|
||||
erasure.parity_shards,
|
||||
skip_verify_bitrot,
|
||||
use_mmap_read,
|
||||
prefer_data_blocks_first_reader_setup,
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
)
|
||||
.await;
|
||||
reader_setup = retried_setup;
|
||||
reader_setup_elapsed = reader_setup_elapsed.saturating_add(retried_elapsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Kick off the next part's reader setup before decoding this one
|
||||
// so the disk opens overlap with decode + client writeback
|
||||
// (backlog#870).
|
||||
@@ -1973,7 +2022,7 @@ impl SetDisks {
|
||||
let shard_size = erasure.shard_size();
|
||||
let data_shards = erasure.data_shards;
|
||||
let parity_shards = erasure.parity_shards;
|
||||
let handle = tokio::task::spawn(async move {
|
||||
let handle = tokio::task::spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
setup_multipart_part_readers(
|
||||
&files,
|
||||
&disks,
|
||||
@@ -1991,7 +2040,7 @@ impl SetDisks {
|
||||
metrics_size_bucket,
|
||||
)
|
||||
.await
|
||||
});
|
||||
}));
|
||||
prefetched = Some((next_part, PrefetchedReaderSetup::new(handle)));
|
||||
}
|
||||
rustfs_io_metrics::record_get_object_shard_reader_setup_duration(reader_setup_elapsed.as_secs_f64());
|
||||
@@ -2003,13 +2052,17 @@ impl SetDisks {
|
||||
reader_setup_elapsed.as_secs_f64(),
|
||||
);
|
||||
let setup_available_readers = reader_setup.available_shards();
|
||||
let request_id = crate::cluster::rpc::context_propagation::propagated_request_id();
|
||||
let version_id = fi.version_id.map(|v| v.to_string()).unwrap_or_default();
|
||||
if reader_setup_elapsed >= SLOW_OBJECT_READ_LOG_THRESHOLD {
|
||||
warn!(
|
||||
event = EVENT_SET_DISK_READ,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_SET_DISK,
|
||||
request_id = %request_id,
|
||||
bucket,
|
||||
object,
|
||||
version_id = %version_id,
|
||||
part_index = current_part,
|
||||
part_number,
|
||||
read_offset,
|
||||
@@ -2037,8 +2090,10 @@ impl SetDisks {
|
||||
event = EVENT_SET_DISK_READ,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_SET_DISK,
|
||||
request_id = %request_id,
|
||||
bucket,
|
||||
object,
|
||||
version_id = %version_id,
|
||||
part_index = current_part,
|
||||
part_number,
|
||||
part_offset,
|
||||
@@ -2065,8 +2120,10 @@ impl SetDisks {
|
||||
event = EVENT_SET_DISK_READ,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_SET_DISK,
|
||||
request_id = %request_id,
|
||||
bucket,
|
||||
object,
|
||||
version_id = %version_id,
|
||||
part_index = current_part,
|
||||
part_number,
|
||||
part_offset,
|
||||
@@ -2864,7 +2921,7 @@ impl SetDisks {
|
||||
let builder: LazyPartBuilder = Box::new(move |remaining_index| {
|
||||
let ctx = Arc::clone(&ctx);
|
||||
let (part_number, part_size) = remaining_parts[remaining_index];
|
||||
tokio::task::spawn(async move {
|
||||
tokio::task::spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
SetDisks::build_codec_streaming_part_reader(
|
||||
&ctx.bucket,
|
||||
&ctx.object,
|
||||
@@ -2892,7 +2949,7 @@ impl SetDisks {
|
||||
ctx.metrics_path,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}))
|
||||
});
|
||||
|
||||
Ok(GetCodecStreamingReaderBuildOutcome::Reader(Box::new(
|
||||
@@ -2930,8 +2987,9 @@ impl SetDisks {
|
||||
let frame_size = read_frame_size_for_file_info(fi, erasure)?;
|
||||
let checksum_algo = part_checksum_algorithm(fi, part_number);
|
||||
let use_mmap_read = object_mmap_read_enabled();
|
||||
let shard_size = erasure.shard_size();
|
||||
let till_offset = erasure.shard_file_offset(part_offset, part_length, part_size);
|
||||
let read_offset = (part_offset / erasure.block_size) * erasure.shard_size();
|
||||
let read_offset = (part_offset / erasure.block_size) * shard_size;
|
||||
let read_length = till_offset.saturating_sub(read_offset);
|
||||
|
||||
let stage_metrics_enabled = rustfs_io_metrics::get_stage_metrics_enabled();
|
||||
@@ -2951,7 +3009,7 @@ impl SetDisks {
|
||||
part_number,
|
||||
read_offset,
|
||||
read_length,
|
||||
erasure.shard_size(),
|
||||
shard_size,
|
||||
frame_size,
|
||||
checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
@@ -2973,7 +3031,14 @@ impl SetDisks {
|
||||
.iter()
|
||||
.find(|part| part.number == part_number)
|
||||
.and_then(|part| part.integrity.as_ref());
|
||||
reader_setup.bind_integrity(expected, files, disks, bucket, object, part_offset / erasure.block_size)?;
|
||||
reader_setup.bind_integrity(
|
||||
expected,
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
object,
|
||||
read_offset / shard_size..till_offset.div_ceil(shard_size),
|
||||
)?;
|
||||
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READER_SETUP, reader_setup_stage_start);
|
||||
|
||||
let available_shards = reader_setup.available_shards();
|
||||
@@ -3210,6 +3275,7 @@ impl AsyncRead for RepairReportingReader {
|
||||
}
|
||||
|
||||
/// Per-part parameters for a multipart bitrot reader setup.
|
||||
#[derive(Clone)]
|
||||
struct PartReaderSetupSpec {
|
||||
integrity: Option<rustfs_filemeta::shard_integrity::PartIntegrity>,
|
||||
part_number: usize,
|
||||
@@ -3424,7 +3490,14 @@ async fn setup_multipart_part_readers(
|
||||
)
|
||||
.await;
|
||||
if setup
|
||||
.bind_integrity(spec.integrity.as_ref(), files, disks, bucket, object, spec.read_offset / shard_size)
|
||||
.bind_integrity(
|
||||
spec.integrity.as_ref(),
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
object,
|
||||
spec.read_offset / shard_size..spec.read_offset.saturating_add(spec.read_length).div_ceil(shard_size),
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
setup = BitrotReaderSetup::new(disks.len());
|
||||
|
||||
@@ -169,21 +169,13 @@ impl SetDisks {
|
||||
.clone()
|
||||
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
|
||||
let version_id = expected.version_id.map(|v| v.to_string());
|
||||
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
opts.no_lock,
|
||||
DecommissionCapacityAdmission::Mutation,
|
||||
)
|
||||
.await?
|
||||
let decommission_object_lock_guard =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
} else {
|
||||
(None, false, None)
|
||||
None
|
||||
};
|
||||
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
|
||||
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
|
||||
Some(
|
||||
self.acquire_write_lock_diag("restore_finalize_metadata", bucket, object)
|
||||
.await?,
|
||||
@@ -191,15 +183,15 @@ impl SetDisks {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
Some(
|
||||
store
|
||||
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let read_opts = ObjectOptions {
|
||||
version_id,
|
||||
versioned: opts.versioned,
|
||||
@@ -286,21 +278,13 @@ impl SetDisks {
|
||||
.clone()
|
||||
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
|
||||
let version_id = expected.version_id.map(|v| v.to_string());
|
||||
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
opts.no_lock,
|
||||
DecommissionCapacityAdmission::Mutation,
|
||||
)
|
||||
.await?
|
||||
let decommission_object_lock_guard =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
} else {
|
||||
(None, false, None)
|
||||
None
|
||||
};
|
||||
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
|
||||
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
|
||||
Some(
|
||||
self.acquire_write_lock_diag("restore_cleanup_metadata", bucket, object)
|
||||
.await?,
|
||||
@@ -308,15 +292,15 @@ impl SetDisks {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
Some(
|
||||
store
|
||||
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let read_opts = ObjectOptions {
|
||||
version_id,
|
||||
versioned: opts.versioned,
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
use super::ECStore;
|
||||
use crate::bucket::utils::is_meta_bucketname;
|
||||
use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore};
|
||||
use crate::disk::{DeleteTransactionId, Disk, DiskAPI, DiskStore, error::DiskError, local::DiscoverySession};
|
||||
use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
|
||||
use rand::RngExt as _;
|
||||
use rustfs_heal_contracts::heal_channel::HealOpts;
|
||||
@@ -29,13 +29,15 @@ use std::sync::{
|
||||
};
|
||||
use std::time::Duration;
|
||||
use tokio::time::{Instant, MissedTickBehavior};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
|
||||
use uuid::Uuid;
|
||||
|
||||
const HINT_CAPACITY: usize = 1_024;
|
||||
const DISCOVERY_PAGE_SIZE: u32 = 128;
|
||||
const PAGES_PER_PASS: usize = 8;
|
||||
const MAX_ACTIVE_DISCOVERY_CURSORS: usize = 32;
|
||||
const DISCOVERY_PAGE_WAIT: Duration = Duration::from_millis(100);
|
||||
const DISCOVERY_PAGE_STALL: Duration = Duration::from_secs(30);
|
||||
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
|
||||
const LOG_SUBSYSTEM_DELETE_RECOVERY: &str = "delete_recovery";
|
||||
const EVENT_DELETE_RECOVERY_STATUS: &str = "delete_recovery_status";
|
||||
@@ -468,18 +470,50 @@ struct LocalSource {
|
||||
available: bool,
|
||||
}
|
||||
|
||||
impl LocalSource {
|
||||
fn same_disk(&self, other: &Self) -> bool {
|
||||
self.pool == other.pool && self.set == other.set && Arc::ptr_eq(&self.disk, &other.disk)
|
||||
}
|
||||
}
|
||||
|
||||
struct DiscoveryPage {
|
||||
incarnation: Uuid,
|
||||
transactions: Vec<DeleteTransactionId>,
|
||||
next: Option<DiscoverySession>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum BucketDiscovery {
|
||||
#[default]
|
||||
Unstarted,
|
||||
Paused(DiscoverySession),
|
||||
InFlight(BoxFuture<'static, crate::disk::error::Result<DiscoveryPage>>),
|
||||
}
|
||||
|
||||
struct BucketScan {
|
||||
bucket: String,
|
||||
incarnation: Option<Uuid>,
|
||||
cursor: Option<DeleteRecoveryCursor>,
|
||||
discovery: BucketDiscovery,
|
||||
pending: VecDeque<String>,
|
||||
}
|
||||
|
||||
impl BucketScan {
|
||||
fn has_progress(&self) -> bool {
|
||||
!matches!(self.discovery, BucketDiscovery::Unstarted) || !self.pending.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskScan {
|
||||
source: LocalSource,
|
||||
buckets: Option<VecDeque<BucketScan>>,
|
||||
}
|
||||
|
||||
impl DiskScan {
|
||||
fn front_bucket(&self) -> Option<&BucketScan> {
|
||||
self.buckets.as_ref()?.front()
|
||||
}
|
||||
}
|
||||
|
||||
fn admit_discovered_keys(hints: &DeleteRecoveryHints, source: &LocalSource, bucket: &mut BucketScan) {
|
||||
while let Some(object) = bucket.pending.front() {
|
||||
if !hints.register_discovered(DeleteRecoveryKey {
|
||||
@@ -531,11 +565,8 @@ impl RecoveryPass {
|
||||
}
|
||||
}
|
||||
}
|
||||
let contains_source = |inventory: &[LocalSource], source: &LocalSource| {
|
||||
inventory.iter().any(|current| {
|
||||
current.pool == source.pool && current.set == source.set && Arc::ptr_eq(¤t.disk, &source.disk)
|
||||
})
|
||||
};
|
||||
let contains_source =
|
||||
|inventory: &[LocalSource], source: &LocalSource| inventory.iter().any(|current| current.same_disk(source));
|
||||
if sources.len() != self.sources.len() || self.sources.iter().any(|source| !contains_source(&sources, source)) {
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
@@ -547,12 +578,10 @@ impl RecoveryPass {
|
||||
.iter()
|
||||
.filter(|source| {
|
||||
source.available
|
||||
&& !self.sources.iter().any(|previous| {
|
||||
previous.available
|
||||
&& Arc::ptr_eq(&previous.disk, &source.disk)
|
||||
&& previous.pool == source.pool
|
||||
&& previous.set == source.set
|
||||
})
|
||||
&& !self
|
||||
.sources
|
||||
.iter()
|
||||
.any(|previous| previous.available && previous.same_disk(source))
|
||||
})
|
||||
.map(|source| (source.pool, source.set))
|
||||
.collect();
|
||||
@@ -567,42 +596,39 @@ impl RecoveryPass {
|
||||
fn defer(&mut self, mut scan: DiskScan) {
|
||||
if let Some(buckets) = scan.buckets.as_mut() {
|
||||
for bucket in buckets {
|
||||
bucket.cursor = None;
|
||||
bucket.discovery = BucketDiscovery::Unstarted;
|
||||
bucket.incarnation = None;
|
||||
}
|
||||
}
|
||||
let same_scope = |other: &DiskScan| {
|
||||
scan.source.pool == other.source.pool
|
||||
&& scan.source.set == other.source.set
|
||||
&& scan.source.disk.to_string() == other.source.disk.to_string()
|
||||
&& scan
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.bucket)
|
||||
== other
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.bucket)
|
||||
scan.source.same_disk(&other.source)
|
||||
&& scan.front_bucket().map(|bucket| &bucket.bucket) == other.front_bucket().map(|bucket| &bucket.bucket)
|
||||
};
|
||||
if let Some(failed) = scan.front_bucket() {
|
||||
// A full sweep may have listed this bucket before the retry failed.
|
||||
// Keep the failed scope's backoff for all still-unopened copies.
|
||||
self.scans.retain_mut(|queued| {
|
||||
if queued.source.same_disk(&scan.source)
|
||||
&& let Some(buckets) = queued.buckets.as_mut()
|
||||
{
|
||||
buckets.retain(|bucket| bucket.bucket != failed.bucket || bucket.has_progress());
|
||||
!buckets.is_empty()
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
if !self.deferred.iter().any(|(_, pending)| same_scope(pending)) {
|
||||
self.deferred.push_back((Instant::now() + INVENTORY_INTERVAL, scan));
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant) {
|
||||
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant, cancel: &CancellationToken) {
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
let active_cursor = |scan: &DiskScan| {
|
||||
scan.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.is_some_and(|bucket| bucket.cursor.is_some() || !bucket.pending.is_empty())
|
||||
};
|
||||
let active_cursor = |scan: &DiskScan| scan.front_bucket().is_some_and(BucketScan::has_progress);
|
||||
if self.scans.iter().filter(|scan| active_cursor(scan)).count() >= MAX_ACTIVE_DISCOVERY_CURSORS {
|
||||
// Keep room for exact-key recovery and other discovery callers in
|
||||
// the disk API's bounded session table. Finish existing cursors
|
||||
// before starting another bucket; queued sources retain their place.
|
||||
// Bound the number of directory stacks we keep open while rotating
|
||||
// across disks. Finish existing walks before opening another bucket.
|
||||
if let Some(index) = self.scans.iter().position(active_cursor) {
|
||||
self.scans.rotate_left(index);
|
||||
}
|
||||
@@ -611,14 +637,28 @@ impl RecoveryPass {
|
||||
if scan.buckets.is_none() {
|
||||
match tokio::time::timeout_at(deadline, scan.source.disk.list_volumes()).await {
|
||||
Ok(Ok(volumes)) => {
|
||||
// A retry that has yet to open its bucket can cover the full
|
||||
// scope for this generation, without bypassing its backoff.
|
||||
let unopened_retries: HashSet<_> = self
|
||||
.scans
|
||||
.iter()
|
||||
.chain(self.deferred.iter().map(|(_, retry)| retry))
|
||||
.filter(|retry| retry.source.same_disk(&scan.source))
|
||||
.filter_map(|retry| retry.buckets.as_ref())
|
||||
.flatten()
|
||||
.filter(|bucket| !bucket.has_progress())
|
||||
.map(|bucket| bucket.bucket.as_str())
|
||||
.collect();
|
||||
scan.buckets = Some(
|
||||
volumes
|
||||
.into_iter()
|
||||
.filter(|volume| !is_meta_bucketname(&volume.name))
|
||||
.filter(|volume| {
|
||||
!is_meta_bucketname(&volume.name) && !unopened_retries.contains(volume.name.as_str())
|
||||
})
|
||||
.map(|volume| BucketScan {
|
||||
bucket: volume.name,
|
||||
incarnation: None,
|
||||
cursor: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
})
|
||||
.collect(),
|
||||
@@ -634,7 +674,7 @@ impl RecoveryPass {
|
||||
{
|
||||
let had_pending = !bucket.pending.is_empty();
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if !bucket.pending.is_empty() || (had_pending && bucket.cursor.is_none()) {
|
||||
if !bucket.pending.is_empty() || (had_pending && matches!(bucket.discovery, BucketDiscovery::Unstarted)) {
|
||||
if !bucket.pending.is_empty() {
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
@@ -643,47 +683,104 @@ impl RecoveryPass {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if bucket.incarnation.is_none() {
|
||||
match tokio::time::timeout_at(deadline, store.bucket_incarnation_id_from_disk(&bucket.bucket)).await {
|
||||
Ok(Ok(incarnation)) => bucket.incarnation = Some(incarnation),
|
||||
_ => {
|
||||
// Finish an older cursor before the new sweep revisits that
|
||||
// bucket. A different bucket may proceed once the disk is idle.
|
||||
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_))
|
||||
&& self
|
||||
.scans
|
||||
.iter()
|
||||
.filter(|other| other.source.same_disk(&scan.source))
|
||||
.filter_map(DiskScan::front_bucket)
|
||||
.any(|other| {
|
||||
matches!(other.discovery, BucketDiscovery::InFlight(_))
|
||||
|| (!bucket.has_progress() && other.bucket == bucket.bucket && other.has_progress())
|
||||
})
|
||||
{
|
||||
buckets.push_front(bucket);
|
||||
self.scans.push_back(scan);
|
||||
return;
|
||||
}
|
||||
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_)) {
|
||||
let store = Arc::clone(store);
|
||||
let incarnation = bucket.incarnation;
|
||||
let disk = Arc::clone(&scan.source.disk);
|
||||
let volume = bucket.bucket.clone();
|
||||
let cancel = cancel.child_token();
|
||||
let session = match std::mem::take(&mut bucket.discovery) {
|
||||
BucketDiscovery::Paused(session) => Some(session),
|
||||
_ => None,
|
||||
};
|
||||
bucket.discovery = BucketDiscovery::InFlight(Box::pin(async move {
|
||||
let _cancel_on_drop = cancel.clone().drop_guard();
|
||||
let (volume, incarnation) = match incarnation {
|
||||
Some(incarnation) => (volume, incarnation),
|
||||
None => {
|
||||
// Finish the quorum read and release its metadata guard even
|
||||
// while the discovery scheduler is polling other disks.
|
||||
let lookup = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let incarnation =
|
||||
tokio::time::timeout(DISCOVERY_BUDGET, store.bucket_incarnation_id_from_disk(&volume))
|
||||
.await
|
||||
.map_err(|_| DiskError::Timeout)?
|
||||
.map_err(DiskError::other)?;
|
||||
Ok::<_, DiskError>((volume, incarnation))
|
||||
}));
|
||||
lookup.await.map_err(DiskError::other)??
|
||||
}
|
||||
};
|
||||
// A stalled disk must not prevent later sweeps on healthy disks.
|
||||
let (transactions, next) = tokio::time::timeout(DISCOVERY_PAGE_STALL, async move {
|
||||
match disk.as_ref() {
|
||||
Disk::Local(local) => {
|
||||
local
|
||||
.advance_background_delete_discovery(volume, session, DISCOVERY_PAGE_SIZE, cancel)
|
||||
.await
|
||||
}
|
||||
#[cfg(feature = "dst")]
|
||||
Disk::Sim(sim) => sim
|
||||
.discover_delete_transactions(&volume, None, None, DISCOVERY_PAGE_SIZE)
|
||||
.await
|
||||
.map(|page| (page.transactions, None)),
|
||||
Disk::Remote(_) => Err(DiskError::DiskNotFound),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DiskError::Timeout)??;
|
||||
Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions,
|
||||
next,
|
||||
})
|
||||
}));
|
||||
}
|
||||
if let BucketDiscovery::InFlight(page) = &mut bucket.discovery {
|
||||
let wait_until = deadline.min(Instant::now() + DISCOVERY_PAGE_WAIT);
|
||||
match tokio::time::timeout_at(wait_until, page.as_mut()).await {
|
||||
Ok(Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions,
|
||||
next,
|
||||
})) => {
|
||||
bucket.incarnation = Some(incarnation);
|
||||
bucket.pending = transactions.into_iter().map(|transaction| transaction.object).collect();
|
||||
bucket.discovery = next.map_or(BucketDiscovery::Unstarted, BucketDiscovery::Paused);
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if !matches!(bucket.discovery, BucketDiscovery::Unstarted) || !bucket.pending.is_empty() {
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
self.defer(DiskScan {
|
||||
source: scan.source.clone(),
|
||||
buckets: Some(VecDeque::from([bucket])),
|
||||
});
|
||||
if !buckets.is_empty() {
|
||||
self.scans.push_back(scan);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
match tokio::time::timeout_at(
|
||||
deadline,
|
||||
scan.source
|
||||
.disk
|
||||
.discover_delete_transactions(&bucket.bucket, None, bucket.cursor.take(), DISCOVERY_PAGE_SIZE),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(page)) => {
|
||||
bucket.pending = page.transactions.into_iter().map(|transaction| transaction.object).collect();
|
||||
bucket.cursor = page.next;
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if bucket.cursor.is_some() || !bucket.pending.is_empty() {
|
||||
// Keep one bounded page until its keys are admitted;
|
||||
// unopened buckets cannot displace its continuation.
|
||||
Err(_) => {
|
||||
// Native calls can run past a scheduling window. Poll the
|
||||
// same page next time, including any evidence it has found.
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Retry only this source, never a full healthy tree
|
||||
// because another disk is offline or a cursor expired.
|
||||
self.defer(DiskScan {
|
||||
source: scan.source.clone(),
|
||||
buckets: Some(VecDeque::from([bucket])),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if scan.buckets.as_ref().is_some_and(|buckets| !buckets.is_empty()) {
|
||||
@@ -699,24 +796,6 @@ impl RecoveryPass {
|
||||
}
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
// Renew only this worker's bounded local cursors before any await.
|
||||
// Backpressure and a slow canonical rollback must not erase progress.
|
||||
for scan in &mut self.scans {
|
||||
if let Some(bucket) = scan.buckets.as_mut().and_then(|buckets| buckets.front_mut())
|
||||
&& let Some(cursor) = bucket.cursor.as_ref()
|
||||
{
|
||||
let renewed = match scan.source.disk.as_ref() {
|
||||
crate::disk::Disk::Local(local) => local.get_disk().renew_delete_recovery_cursor(&bucket.bucket, cursor),
|
||||
crate::disk::Disk::Remote(_) => false,
|
||||
#[cfg(feature = "dst")]
|
||||
crate::disk::Disk::Sim(_) => false,
|
||||
};
|
||||
if !renewed {
|
||||
bucket.cursor = None;
|
||||
hints.request_rescan();
|
||||
}
|
||||
}
|
||||
}
|
||||
let discovery_deadline = Instant::now() + DISCOVERY_BUDGET;
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
@@ -731,12 +810,21 @@ impl RecoveryPass {
|
||||
}
|
||||
if let Some(generation) = hints.rescan() {
|
||||
self.scan_generation = Some(generation);
|
||||
self.scans = self
|
||||
.sources
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|source| DiskScan { source, buckets: None })
|
||||
.collect();
|
||||
// A due retry may already have a live page even though the
|
||||
// previous full sweep completed. Keep it ahead of fresh work.
|
||||
for source in &self.sources {
|
||||
let inventory_queued = self
|
||||
.scans
|
||||
.iter()
|
||||
.chain(self.deferred.iter().map(|(_, retry)| retry))
|
||||
.any(|scan| scan.buckets.is_none() && scan.source.same_disk(source));
|
||||
if !inventory_queued {
|
||||
self.scans.push_back(DiskScan {
|
||||
source: source.clone(),
|
||||
buckets: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _ in 0..self.deferred.len() {
|
||||
@@ -753,7 +841,7 @@ impl RecoveryPass {
|
||||
}
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
_ = self.discover_page(store, discovery_deadline) => {}
|
||||
_ = self.discover_page(store, discovery_deadline, cancel) => {}
|
||||
}
|
||||
}
|
||||
if self.scans.is_empty()
|
||||
@@ -1538,6 +1626,180 @@ mod tests {
|
||||
assert!(pass.scans.is_empty());
|
||||
assert!(store.ctx.delete_recovery_hints().rescan().is_none());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_slow_bucket_identity_does_not_block_other_disks() {
|
||||
let healthy = "runtime-healthy-identity";
|
||||
let blocked = "runtime-blocked-identity";
|
||||
let (_dirs, store, disks) = fixture(healthy).await;
|
||||
store
|
||||
.make_bucket(blocked, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create second bucket");
|
||||
prepare(&store, &disks, healthy).await;
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(healthy)
|
||||
.await
|
||||
.expect("healthy bucket incarnation");
|
||||
let writer = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked)
|
||||
.await
|
||||
.expect("hold the blocked bucket's metadata write lock");
|
||||
let key = DeleteRecoveryKey {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
bucket: healthy.to_owned(),
|
||||
object: "object".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.scans
|
||||
.extend([blocked, healthy].into_iter().enumerate().map(|(index, bucket)| DiskScan {
|
||||
source: LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[index].clone(),
|
||||
available: true,
|
||||
},
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
}));
|
||||
let cancel = CancellationToken::new();
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
assert!(!hints.is_pending(&key), "the key must be discovered by the healthy scan");
|
||||
tokio::time::timeout(Duration::from_secs(2), pass.discover(&store, &cancel))
|
||||
.await
|
||||
.expect("identity lookup yields to independent disk work");
|
||||
|
||||
assert!(hints.is_pending(&key), "the healthy disk discovers its journal while metadata is locked");
|
||||
assert!(pass.deferred.is_empty(), "the scheduler keeps the waiting page");
|
||||
assert!(matches!(
|
||||
pass.scans.front().and_then(DiskScan::front_bucket),
|
||||
Some(BucketScan { bucket, discovery: BucketDiscovery::InFlight(_), .. }) if bucket == blocked
|
||||
));
|
||||
|
||||
drop(writer);
|
||||
let writer = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked),
|
||||
)
|
||||
.await
|
||||
.expect("the parked discovery page must not keep the metadata guard held")
|
||||
.expect("reacquire the bucket's metadata write lock");
|
||||
drop(writer);
|
||||
pass.discover(&store, &cancel).await;
|
||||
assert!(pass.scans.is_empty(), "the original identity lookup resumes through the native page");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_rescan_keeps_an_inflight_retry_page() {
|
||||
let bucket = "runtime-rescan-retry";
|
||||
let (_dirs, store, disks) = fixture(bucket).await;
|
||||
let source = LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[0].clone(),
|
||||
available: true,
|
||||
};
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(bucket)
|
||||
.await
|
||||
.expect("bucket incarnation");
|
||||
let discovered = DeleteRecoveryKey {
|
||||
pool: source.pool,
|
||||
set: source.set,
|
||||
bucket: bucket.to_owned(),
|
||||
object: "found-in-retry".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.sources.push(source.clone());
|
||||
pass.scans.push_back(DiskScan {
|
||||
source,
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
discovery: BucketDiscovery::InFlight(Box::pin(std::future::ready(Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions: vec![DeleteTransactionId {
|
||||
object: discovered.object.clone(),
|
||||
transaction: Uuid::new_v4(),
|
||||
}],
|
||||
next: None,
|
||||
})))),
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
pass.discover(&store, &CancellationToken::new()).await;
|
||||
|
||||
assert!(hints.is_pending(&discovered), "a fresh sweep must admit the in-flight retry result");
|
||||
assert!(pass.scans.is_empty(), "the fresh sweep also completes");
|
||||
assert!(hints.rescan().is_none(), "the new generation is acknowledged");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_rescan_respects_the_retry_backoff() {
|
||||
let bucket = "runtime-rescan-backoff";
|
||||
let (_dirs, store, disks) = fixture(bucket).await;
|
||||
prepare(&store, &disks, bucket).await;
|
||||
let source = LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[0].clone(),
|
||||
available: true,
|
||||
};
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(bucket)
|
||||
.await
|
||||
.expect("bucket incarnation");
|
||||
let discovered = DeleteRecoveryKey {
|
||||
pool: source.pool,
|
||||
set: source.set,
|
||||
bucket: bucket.to_owned(),
|
||||
object: "object".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.sources.push(source.clone());
|
||||
pass.scans.push_back(DiskScan {
|
||||
source: source.clone(),
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
pass.defer(DiskScan {
|
||||
source,
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
let cancel = CancellationToken::new();
|
||||
pass.discover(&store, &cancel).await;
|
||||
|
||||
assert!(!hints.is_pending(&discovered), "the full sweep must not bypass the bucket retry");
|
||||
assert!(hints.rescan().is_none(), "the deferred bucket does not block the full sweep");
|
||||
let (ready, _) = pass.deferred.front_mut().expect("pending bucket retry");
|
||||
*ready = Instant::now();
|
||||
pass.discover(&store, &cancel).await;
|
||||
|
||||
assert!(hints.is_pending(&discovered), "the due retry still reads the hidden preparation");
|
||||
assert!(pass.deferred.is_empty(), "the retry settled its discovery obligation");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_blocked_capacity_yields_until_periodic_sweep() {
|
||||
let (_dirs, store, _disks) = fixture("runtime-blocked-sweep").await;
|
||||
@@ -1962,6 +2224,24 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_continues_current_bucket_before_opening_later_buckets() {
|
||||
async fn finish_page(pass: &mut RecoveryPass, store: &Arc<ECStore>, cancel: &CancellationToken) {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
assert!(Instant::now() < deadline, "discovery page did not return");
|
||||
pass.discover_page(store, deadline, cancel).await;
|
||||
if !matches!(
|
||||
pass.scans
|
||||
.front()
|
||||
.and_then(|scan| scan.buckets.as_ref())
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.discovery),
|
||||
Some(BucketDiscovery::InFlight(_))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let bucket = "runtime-cursor-progress";
|
||||
let (dirs, store, disks) = fixture(bucket).await;
|
||||
let other = "runtime-after-large";
|
||||
@@ -1983,11 +2263,12 @@ mod tests {
|
||||
buckets: Some(VecDeque::from([bucket, other].map(|bucket| BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
cursor: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}))),
|
||||
});
|
||||
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
|
||||
let cancel = CancellationToken::new();
|
||||
finish_page(&mut pass, &store, &cancel).await;
|
||||
let first = pass.scans[0]
|
||||
.buckets
|
||||
.as_ref()
|
||||
@@ -1995,8 +2276,44 @@ mod tests {
|
||||
.front()
|
||||
.expect("current bucket");
|
||||
assert_eq!(first.bucket, bucket);
|
||||
assert!(first.cursor.is_some(), "raw entry budget must leave a continuation");
|
||||
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
|
||||
assert!(
|
||||
matches!(first.discovery, BucketDiscovery::Paused(_)),
|
||||
"raw entry budget must leave a continuation"
|
||||
);
|
||||
let Disk::Local(local) = disks[0].as_ref() else {
|
||||
panic!("expected a local drive");
|
||||
};
|
||||
let lease = local
|
||||
.get_disk()
|
||||
.lock_delete_discovery_bucket(bucket)
|
||||
.await
|
||||
.expect("hold bucket lease");
|
||||
pass.discover_page(&store, Instant::now(), &cancel).await;
|
||||
assert!(
|
||||
pass.deferred.is_empty(),
|
||||
"the scheduling deadline must not discard a page waiting on the disk"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
pass.scans[0]
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.discovery),
|
||||
Some(BucketDiscovery::InFlight(_))
|
||||
),
|
||||
"the original page and its continuation stay owned across the deadline"
|
||||
);
|
||||
let volumes = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
crate::disk::with_background_disk_io(cancel.clone(), local.list_volumes()),
|
||||
)
|
||||
.await
|
||||
.expect("another background operation can use the disk while discovery waits for its bucket lease")
|
||||
.expect("list volumes under background admission");
|
||||
assert!(volumes.iter().any(|volume| volume.name == other));
|
||||
drop(lease);
|
||||
finish_page(&mut pass, &store, &cancel).await;
|
||||
assert_eq!(
|
||||
pass.scans[0]
|
||||
.buckets
|
||||
@@ -2008,5 +2325,25 @@ mod tests {
|
||||
other,
|
||||
"the second page completes instead of cycling through unopened buckets"
|
||||
);
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
pass.scan_generation = Some(hints.rescan().expect("scan obligation before the stall"));
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(other)
|
||||
.await
|
||||
.expect("source incarnation");
|
||||
pass.scans[0].buckets.as_mut().expect("open inventory")[0].incarnation = Some(incarnation);
|
||||
let _lease = local
|
||||
.get_disk()
|
||||
.lock_delete_discovery_bucket(other)
|
||||
.await
|
||||
.expect("hold bucket lease");
|
||||
tokio::time::pause();
|
||||
pass.discover_page(&store, Instant::now(), &cancel).await;
|
||||
tokio::time::advance(DISCOVERY_PAGE_STALL).await;
|
||||
pass.next_inventory = Some(Instant::now() + INVENTORY_INTERVAL);
|
||||
pass.discover(&store, &cancel).await;
|
||||
assert_eq!(pass.deferred.len(), 1, "a genuinely stalled source is deferred");
|
||||
assert!(pass.scan_generation.is_none(), "the stall cannot pin subsequent sweeps");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,7 +326,18 @@ impl ECStore {
|
||||
));
|
||||
}
|
||||
// Lock order: bucket lifecycle, then bucket/object and capacity locks used by healing.
|
||||
let fence = self.acquire_bucket_incarnation_fence(bucket, expected).await?;
|
||||
// DeleteBucket publishes a durable retirement record before removing `.bucket-incarnation`,
|
||||
// so a retired expected generation classifies as BucketNotFound rather than corrupt metadata.
|
||||
let fence = match self.acquire_bucket_incarnation_fence(bucket, expected).await {
|
||||
Ok(fence) => fence,
|
||||
Err(err @ StorageError::BucketNotFound(_)) => return Err(err),
|
||||
Err(err) => {
|
||||
if matches!(self.is_bucket_incarnation_retired(bucket, expected).await, Ok(true)) {
|
||||
return Err(StorageError::BucketNotFound(bucket.to_owned()));
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let scope = Arc::new(BucketHealScope {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: expected,
|
||||
@@ -581,6 +592,53 @@ impl ECStore {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Check whether an unversioned MRF target is absent from its original set.
|
||||
/// A true result requires every configured drive and no pending delete recovery.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if storage cannot establish identity, locks, or complete reads.
|
||||
pub async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
|
||||
) -> Result<bool> {
|
||||
use rustfs_common::mrf_channel::MrfKind;
|
||||
|
||||
let (Some(scope), None, MrfKind::PartialWrite) = (anchor.scope, anchor.version_id, anchor.kind) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let bucket = anchor.bucket.as_ref();
|
||||
let object = anchor.object.as_ref();
|
||||
if anchor.bucket_incarnation_id.is_nil()
|
||||
|| self.ctx.lock_manager().is_disabled()
|
||||
|| super::utils::is_reserved_or_invalid_bucket(bucket, false)
|
||||
|| object.ends_with('/')
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let pool_index = scope.pool_index as usize;
|
||||
let set_index = scope.set_index as usize;
|
||||
let opts = HealOpts {
|
||||
pool: Some(pool_index),
|
||||
set: Some(set_index),
|
||||
..Default::default()
|
||||
};
|
||||
let bucket_guard = self
|
||||
.acquire_bucket_incarnation_fence(bucket, anchor.bucket_incarnation_id)
|
||||
.await?;
|
||||
let pool = self
|
||||
.pools
|
||||
.get(pool_index)
|
||||
.ok_or_else(|| invalid_heal_pool_index(pool_index, self.pools.len()))?;
|
||||
if self.pool_meta.read().await.is_suspended(pool_index) {
|
||||
return Ok(false);
|
||||
}
|
||||
let set = pool.get_disks_for_heal_object(object, &opts)?;
|
||||
let capacity_store = (!self.single_pool()).then_some(self);
|
||||
let absent = set.probe_mrf_unversioned_absence(bucket, object, capacity_store).await?;
|
||||
self.validate_bucket_incarnation_fence(&bucket_guard, bucket)?;
|
||||
Ok(absent)
|
||||
}
|
||||
|
||||
async fn acquire_heal_format_fence(
|
||||
&self,
|
||||
) -> Result<(
|
||||
@@ -1442,24 +1500,10 @@ impl ECStore {
|
||||
Err(err) => vec![Err(err)],
|
||||
}
|
||||
} else {
|
||||
let mut futures = Vec::with_capacity(heal_pools.len());
|
||||
for pool in heal_pools {
|
||||
let pool_idx = pool.pool_idx;
|
||||
let pool_object = object.clone();
|
||||
let opts = *opts;
|
||||
futures.push(self.run_external_decommission_capacity_heal(
|
||||
pool_idx,
|
||||
bucket,
|
||||
&object,
|
||||
opts,
|
||||
move |opts| async move {
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_operation_started(store_id);
|
||||
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, proof)
|
||||
.await
|
||||
},
|
||||
));
|
||||
}
|
||||
let capacity_store = (!self.single_pool()).then_some(self);
|
||||
let futures = heal_pools
|
||||
.iter()
|
||||
.map(|pool| pool.heal_object_with_absence(bucket, &object, version_id, opts, proof, capacity_store));
|
||||
join_all(futures).await
|
||||
};
|
||||
|
||||
@@ -1513,7 +1557,7 @@ impl ECStore {
|
||||
version_id
|
||||
};
|
||||
let (before, error, absence) = pool
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
|
||||
.await?;
|
||||
let target = pool.get_disks_for_heal_object(POOL_META_NAME, opts)?;
|
||||
let owns_replica = Arc::ptr_eq(&target, &pool.get_disks_by_key(POOL_META_NAME));
|
||||
@@ -1532,7 +1576,7 @@ impl ECStore {
|
||||
return Ok((before, Some(error), None));
|
||||
}
|
||||
let (mut after, error, _) = pool
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
|
||||
.await?;
|
||||
after.before = before.before;
|
||||
if guard.is_lock_lost() {
|
||||
@@ -4330,6 +4374,11 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn targeted_heal_is_blocked_by_exact_fit_decommission_reservation() {
|
||||
use rustfs_common::mrf_channel::{
|
||||
MrfDurableRepairAnchor, MrfIngressResult, MrfIntent, MrfKind, MrfScope, release_mrf_intent,
|
||||
try_rearm_mrf_replay_intent,
|
||||
};
|
||||
|
||||
let (_temp_dirs, store, _other_store) = test_two_pool_stores(None).await;
|
||||
let bucket = format!("heal-capacity-{}", Uuid::new_v4().simple());
|
||||
let object = "targeted-heal.bin";
|
||||
@@ -4338,6 +4387,34 @@ mod tests {
|
||||
.await
|
||||
.expect("heal capacity bucket should be created");
|
||||
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(&bucket)
|
||||
.await
|
||||
.expect("MRF probe bucket incarnation should be readable");
|
||||
let mut intent = MrfIntent {
|
||||
bucket: Arc::from(bucket.as_str()),
|
||||
object: Arc::from("absent-mrf-target.bin"),
|
||||
version_id: None,
|
||||
kind: MrfKind::PartialWrite,
|
||||
scope: Some(MrfScope {
|
||||
pool_index: 1,
|
||||
set_index: 0,
|
||||
}),
|
||||
lease: None,
|
||||
enqueued_at_ms: 0,
|
||||
attempts: 0,
|
||||
delete_marker_purge: None,
|
||||
};
|
||||
assert_eq!(try_rearm_mrf_replay_intent(&mut intent), MrfIngressResult::Enqueued);
|
||||
let anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("MRF probe anchor should be valid");
|
||||
assert!(
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), store.probe_mrf_unversioned_absence(&anchor))
|
||||
.await
|
||||
.expect("unreserved MRF probe should finish")
|
||||
.expect("unreserved MRF probe should be admitted"),
|
||||
"an absent target should be proven before the reservation"
|
||||
);
|
||||
|
||||
let target_set = store.pools[1].get_disks(0);
|
||||
let mut reader = PutObjReader::from_vec(b"targeted heal body".to_vec());
|
||||
target_set
|
||||
@@ -4388,6 +4465,15 @@ mod tests {
|
||||
assert_eq!(reservation.targets[0].reserved_physical_bytes, 60);
|
||||
}
|
||||
|
||||
let probe = tokio::time::timeout(std::time::Duration::from_secs(2), store.probe_mrf_unversioned_absence(&anchor))
|
||||
.await
|
||||
.expect("reserved-target MRF admission should finish");
|
||||
release_mrf_intent(&intent);
|
||||
assert!(
|
||||
matches!(probe, Err(Error::SlowDown)),
|
||||
"reserved-target MRF probe must remain capacity-blocked: {probe:?}"
|
||||
);
|
||||
|
||||
let (_, err) = store
|
||||
.handle_heal_object(
|
||||
&bucket,
|
||||
|
||||
@@ -6119,6 +6119,351 @@ mod tests {
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
async fn stage_multipart_on_first_pool(
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
bytes: &[u8],
|
||||
opts: &ObjectOptions,
|
||||
) -> (String, Vec<crate::storage_api_contracts::multipart::CompletePart>) {
|
||||
use crate::storage_api_contracts::multipart::CompletePart;
|
||||
|
||||
let pool = &store.pools[0];
|
||||
let upload = pool
|
||||
.new_multipart_upload(bucket, key, opts)
|
||||
.await
|
||||
.expect("stage upload in pool 0");
|
||||
let part = pool
|
||||
.put_object_part(bucket, key, &upload.upload_id, 1, &mut PutObjReader::from_vec(bytes.to_vec()), opts)
|
||||
.await
|
||||
.expect("stage the part");
|
||||
(
|
||||
upload.upload_id,
|
||||
vec![CompletePart {
|
||||
part_num: part.part_num,
|
||||
etag: part.etag,
|
||||
..Default::default()
|
||||
}],
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
async fn seed_multipart_predecessors(
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
named_predecessor: bool,
|
||||
) -> (ObjectInfo, ObjectInfo) {
|
||||
store
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create bucket");
|
||||
store
|
||||
.update_bucket_metadata_config(
|
||||
bucket,
|
||||
crate::bucket::metadata::OBJECT_LOCK_CONFIG,
|
||||
b"<ObjectLockConfiguration><ObjectLockEnabled>Enabled</ObjectLockEnabled></ObjectLockConfiguration>".to_vec(),
|
||||
)
|
||||
.await
|
||||
.expect("enable Object Lock");
|
||||
let peer = &store.pools[1];
|
||||
let old = peer
|
||||
.put_object(
|
||||
bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(vec![1; 20]),
|
||||
&ObjectOptions {
|
||||
versioned: named_predecessor,
|
||||
user_defined: HashMap::from([(
|
||||
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
|
||||
"ON".to_owned(),
|
||||
)]),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write protected predecessor in pool 1");
|
||||
let head = peer
|
||||
.put_object(
|
||||
bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(vec![2; 10]),
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write a newer unprotected version in pool 1");
|
||||
(old, head)
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn unconditional_multipart_checks_the_historical_null_for_object_lock_and_quota() {
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-null-predecessor", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("mpu-null-{}", Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, false).await;
|
||||
let mut opts = ObjectOptions {
|
||||
version_suspended: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(opts.set_quota_admission(30, 30));
|
||||
let (upload, parts) = stage_multipart_on_first_pool(&store, &bucket, key, &[3; 20], &opts).await;
|
||||
let denied = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &opts)
|
||||
.await
|
||||
.expect_err("the historical null is under legal hold in pool 1");
|
||||
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
|
||||
let null = ObjectOptions {
|
||||
version_id: Some(Uuid::nil().to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
store.pools[1]
|
||||
.get_object_info(&bucket, key, &null)
|
||||
.await
|
||||
.expect("preserved null")
|
||||
.etag,
|
||||
old.etag
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("unchanged head")
|
||||
.version_id,
|
||||
head.version_id
|
||||
);
|
||||
store.pools[1]
|
||||
.get_disks_by_key(key)
|
||||
.put_object_metadata(
|
||||
&bucket,
|
||||
key,
|
||||
&ObjectOptions {
|
||||
eval_metadata: Some(HashMap::from([(
|
||||
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
|
||||
"OFF".to_owned(),
|
||||
)])),
|
||||
..null
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("release the legal hold on the historical null");
|
||||
let completed = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &opts)
|
||||
.await
|
||||
.expect("retry the same upload and replace 20 bytes in a full bucket");
|
||||
assert!(completed.version_id.is_none_or(|id| id.is_nil()));
|
||||
assert_ne!(completed.etag, old.etag);
|
||||
assert!(completed.mod_time > head.mod_time);
|
||||
assert_eq!(completed.put_usage.expect("replacement usage").replaced_size(), 20);
|
||||
assert_eq!(
|
||||
store.pools[1]
|
||||
.get_object_info(
|
||||
&bucket,
|
||||
key,
|
||||
&ObjectOptions {
|
||||
version_id: Some(head.version_id.expect("named head").to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.expect("preserved named version")
|
||||
.etag,
|
||||
head.etag
|
||||
);
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn multipart_reads_remote_history_only_for_an_explicit_named_replacement() {
|
||||
use crate::disk::lifecycle_test_io::Observer;
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-named-predecessor", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("mpu-named-{}", Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, true).await;
|
||||
let old_id = old.version_id.expect("named predecessor");
|
||||
let opts = ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (explicit, explicit_parts) = stage_multipart_on_first_pool(
|
||||
&store,
|
||||
&bucket,
|
||||
key,
|
||||
b"replace the retained version",
|
||||
&ObjectOptions {
|
||||
version_id: Some(old_id.to_string()),
|
||||
..opts.clone()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let (fresh, fresh_parts) = stage_multipart_on_first_pool(&store, &bucket, key, b"new version", &opts).await;
|
||||
let reads = Observer::new(&bucket);
|
||||
let condition = ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: Some(head.etag.expect("current ETag")),
|
||||
..Default::default()
|
||||
}),
|
||||
..opts.clone()
|
||||
};
|
||||
let completed = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &fresh, fresh_parts, &condition)
|
||||
.await
|
||||
.expect("publish a fresh named version beside a retained historical version");
|
||||
let id = completed.version_id.expect("fresh UUID");
|
||||
assert_ne!(id, old_id);
|
||||
assert_ne!(Some(id), head.version_id);
|
||||
assert_eq!(completed.put_usage.expect("usage for fresh version").replaced_size(), 0);
|
||||
assert!(
|
||||
reads.snapshot().reads.iter().all(|name| name != key),
|
||||
"a live head proves a fresh version appends without reading the complete history"
|
||||
);
|
||||
let denied = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &explicit, explicit_parts, &opts)
|
||||
.await
|
||||
.expect_err("the version requested at initiation remains protected");
|
||||
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
|
||||
assert!(
|
||||
reads.snapshot().reads.iter().any(|name| name == key),
|
||||
"an explicit historical replacement must be located before publication"
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("preserved fresh head")
|
||||
.version_id,
|
||||
Some(id)
|
||||
);
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn conditional_multipart_matches_the_current_pool_and_rechecks_concurrent_writes() {
|
||||
use crate::set_disk::{MultipartCommitBarrier, MultipartCommitPause};
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
|
||||
let if_match = |info: &ObjectInfo| ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: Some(info.etag.clone().expect("object ETag")),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "conditional-mpu-writes", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("conditional-mpu-{}", uuid::Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create bucket");
|
||||
let write_peer = async |body: &[u8], mod_time| {
|
||||
store.pools[1]
|
||||
.put_object(
|
||||
&bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(body.to_vec()),
|
||||
&ObjectOptions {
|
||||
mod_time: Some(mod_time),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write on the other pool")
|
||||
};
|
||||
let future_time = OffsetDateTime::now_utc() + time::Duration::hours(1);
|
||||
let existing = write_peer(b"old", future_time).await;
|
||||
let (upload, parts) =
|
||||
stage_multipart_on_first_pool(&store, &bucket, key, b"first completion", &ObjectOptions::default()).await;
|
||||
let first = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&existing))
|
||||
.await
|
||||
.expect("match the object in pool 1 and publish the upload in pool 0");
|
||||
assert!(first.mod_time > existing.mod_time);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("current completion")
|
||||
.etag,
|
||||
first.etag
|
||||
);
|
||||
|
||||
let (upload, parts) =
|
||||
stage_multipart_on_first_pool(&store, &bucket, key, b"retryable completion", &ObjectOptions::default()).await;
|
||||
let paused = MultipartCommitBarrier::install(&bucket, key, MultipartCommitPause::BeforeConditionalNamespace);
|
||||
let complete = tokio::spawn({
|
||||
let (store, bucket, upload, parts, condition) =
|
||||
(store.clone(), bucket.clone(), upload.clone(), parts.clone(), if_match(&first));
|
||||
async move {
|
||||
store
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &condition)
|
||||
.await
|
||||
}
|
||||
});
|
||||
paused.wait_until_paused().await;
|
||||
let winner = write_peer(b"concurrent write", future_time + time::Duration::seconds(1)).await;
|
||||
drop(paused);
|
||||
assert_eq!(
|
||||
complete
|
||||
.await
|
||||
.expect("completion task")
|
||||
.expect_err("the concurrent write changed the current ETag"),
|
||||
StorageError::PreconditionFailed
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("concurrent winner")
|
||||
.etag,
|
||||
winner.etag
|
||||
);
|
||||
let retry = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &if_match(&winner))
|
||||
.await
|
||||
.expect("retry the same staged upload with the current ETag");
|
||||
assert!(retry.mod_time > winner.mod_time);
|
||||
let replay = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&retry))
|
||||
.await
|
||||
.expect("a matching condition may replay the published upload");
|
||||
assert!(replay.multipart_completion_replayed);
|
||||
assert_eq!(replay.data_dir, retry.data_dir);
|
||||
assert!(replay.put_usage.is_none());
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
|
||||
@@ -1438,19 +1438,7 @@ impl ECStore {
|
||||
.acquire_object_read_lock_if_needed("lifecycle_versions", bucket, &disk_object, &mut opts)
|
||||
.await?;
|
||||
|
||||
// As with version listings, include every physical set: migration can
|
||||
// leave a key's history in more than its current hash destination.
|
||||
let reads = self
|
||||
.pools
|
||||
.iter()
|
||||
.flat_map(|pool| &pool.disk_set)
|
||||
.map(|set| set.read_object_versions_for_lifecycle(bucket, object));
|
||||
let mut entries = Vec::new();
|
||||
for result in join_all(reads).await {
|
||||
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
let versions = self.read_object_version_history(bucket, object, &[]).await?;
|
||||
if self.pools.is_empty()
|
||||
|| bucket_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| opts
|
||||
@@ -1462,6 +1450,34 @@ impl ECStore {
|
||||
{
|
||||
return Err(Error::PreconditionFailed);
|
||||
}
|
||||
let versioned = versioning.versioned(object);
|
||||
Ok(versions
|
||||
.iter()
|
||||
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(super) async fn read_object_version_history(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
retired: &[usize],
|
||||
) -> Result<Vec<rustfs_filemeta::FileInfo>> {
|
||||
// As with version listings, include every physical set: migration can
|
||||
// leave a key's history in more than its current hash destination.
|
||||
let reads = self
|
||||
.pools
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| !retired.contains(index))
|
||||
.flat_map(|(_, pool)| &pool.disk_set)
|
||||
.map(|set| set.read_object_version_history(bucket, object));
|
||||
let mut entries = Vec::new();
|
||||
for result in join_all(reads).await {
|
||||
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
let mut entries = entries.into_iter();
|
||||
let Some(mut entry) = entries.next() else {
|
||||
return Ok(Vec::new());
|
||||
@@ -1469,15 +1485,7 @@ impl ECStore {
|
||||
if entries.len() > 0 {
|
||||
merge_object_entry_versions(&mut entry, entries, log_listing_merge_corruption)?;
|
||||
}
|
||||
// This projection excludes tier free-version bookkeeping but retains
|
||||
// pending version purges for the evaluator's replication safeguards.
|
||||
let versions = entry.file_info_versions(bucket)?;
|
||||
let versioned = versioning.versioned(object);
|
||||
Ok(versions
|
||||
.versions
|
||||
.iter()
|
||||
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
|
||||
.collect())
|
||||
Ok(entry.file_info_versions(bucket)?.versions)
|
||||
}
|
||||
|
||||
async fn inner_list_object_versions_with_projection(
|
||||
@@ -1572,6 +1580,18 @@ impl ECStore {
|
||||
})
|
||||
}
|
||||
|
||||
fn list_read_fanout(&self) -> usize {
|
||||
self.pools.iter().fold(0usize, |total, pool| {
|
||||
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the local budget can fit one full listing walk at the time of sampling.
|
||||
/// Returns `None` until a listing walk initializes the budget.
|
||||
pub fn list_read_budget_has_capacity(&self) -> Option<bool> {
|
||||
self.ctx.list_read_budget_has_capacity(self.list_read_fanout())
|
||||
}
|
||||
|
||||
pub async fn list_path(self: Arc<Self>, o: &ListPathOptions) -> Result<ListPage> {
|
||||
// tracing::warn!("list_path opt {:?}", &o);
|
||||
|
||||
@@ -1625,10 +1645,11 @@ impl ECStore {
|
||||
if o.transient {
|
||||
o.create = false;
|
||||
}
|
||||
let fanout = self.pools.iter().fold(0usize, |total, pool| {
|
||||
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
|
||||
});
|
||||
o.read_budget = self.ctx.acquire_list_read_budget(fanout).await.map_err(Error::other)?;
|
||||
o.read_budget = self
|
||||
.ctx
|
||||
.acquire_list_read_budget(self.list_read_fanout())
|
||||
.await
|
||||
.map_err(Error::other)?;
|
||||
|
||||
let log_context = ListPathLogContext::from_options(&o);
|
||||
|
||||
@@ -2716,7 +2737,7 @@ fn merge_object_entry_versions(
|
||||
let equivalent = if info.delete_marker && previous_info.delete_marker {
|
||||
super::object::is_equivalent_data_movement_delete_marker(&info, previous_info)
|
||||
} else {
|
||||
crate::data_movement::is_equivalent_data_movement_object_identity(&info, previous_info, true, true)
|
||||
crate::data_movement::equivalent_listed_object_versions(&info, previous_info)
|
||||
};
|
||||
if !equivalent {
|
||||
return Err(corrupt("version_identity_conflict"));
|
||||
@@ -9085,7 +9106,15 @@ mod test {
|
||||
let first = test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 4, 2)]);
|
||||
let second = rewrite_test_version(
|
||||
test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 6, 2)]),
|
||||
|version| version.object.as_mut().expect("object version").data_dir = Some(Uuid::from_u128(42)),
|
||||
|version| {
|
||||
let object = version.object.as_mut().expect("object version");
|
||||
let original = object.data_dir.replace(Uuid::from_u128(42)).expect("source data directory");
|
||||
rustfs_utils::http::insert_bytes(
|
||||
&mut object.meta_sys,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
original.to_string().into_bytes(),
|
||||
);
|
||||
},
|
||||
);
|
||||
let forward = merge_test_object_entries(vec![first.clone(), second.clone()])
|
||||
.await
|
||||
|
||||
@@ -217,6 +217,33 @@ async fn lifecycle_exact_matches_listing_for_complete_version_groups() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_usage_counts_live_versions_hidden_by_a_current_marker() {
|
||||
let (dirs, store, bucket, _) = fixture(2).await;
|
||||
let key = "masked";
|
||||
let marker = FileInfo {
|
||||
name: key.into(),
|
||||
deleted: true,
|
||||
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_001).expect("marker timestamp")),
|
||||
..Default::default()
|
||||
};
|
||||
seed(&dirs[..4], &bucket, key, std::slice::from_ref(&marker)).await;
|
||||
let current = ObjectInfo::from_file_info(&marker, &bucket, key, true);
|
||||
for had_live_version in [false, true] {
|
||||
if had_live_version {
|
||||
seed(&dirs[4..], &bucket, key, &[version(key, Some(Uuid::new_v4()), 1_700_000_000)]).await;
|
||||
}
|
||||
let previous = store
|
||||
.resolve_put_predecessors(&bucket, key, &ObjectOptions::default(), Some(current.clone()), Some(Uuid::nil()))
|
||||
.await
|
||||
.expect("resolve all live versions under the marker");
|
||||
assert_eq!(
|
||||
previous.usage_receipt().expect("version usage"),
|
||||
crate::data_usage::PutUsageReceipt::from_predecessors(had_live_version, Some(¤t)).expect("fixture usage")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lifecycle_exact_merges_pools_and_more_than_one_page_of_versions() {
|
||||
let (dirs, store, bucket, incarnation) = fixture(2).await;
|
||||
|
||||
@@ -712,7 +712,7 @@ impl ECStore {
|
||||
}
|
||||
if opts.http_preconditions.is_some()
|
||||
&& !opts.data_movement
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, &opts, false).await
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, &opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
@@ -1340,32 +1340,12 @@ impl ECStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn check_write_precondition(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
opts: &ObjectOptions,
|
||||
require_all_pools: bool,
|
||||
) -> Option<StorageError> {
|
||||
async fn check_write_precondition(&self, bucket: &str, object: &str, opts: &ObjectOptions) -> Option<StorageError> {
|
||||
let mut lookup_opts = opts.clone();
|
||||
let http_preconditions = lookup_opts.http_preconditions?;
|
||||
lookup_opts.http_preconditions = None;
|
||||
lookup_opts.no_lock = true;
|
||||
let oi = if require_all_pools {
|
||||
lookup_opts.metadata_cache_safe = false;
|
||||
lookup_opts.metadata_cache_fence_proof = None;
|
||||
lookup_opts.suppress_read_repair = true;
|
||||
// Only completion uses this branch, after validating bucket and object.
|
||||
let encoded_object = encode_dir_object_ref(object);
|
||||
self.get_latest_object_info_for_conditional_write(bucket, encoded_object.as_ref(), &lookup_opts)
|
||||
.await
|
||||
.and_then(|(info, _)| {
|
||||
lookup_opts.precondition_check(&info)?;
|
||||
Ok(info)
|
||||
})
|
||||
} else {
|
||||
self.get_object_info_for_delete(bucket, object, &lookup_opts).await
|
||||
};
|
||||
let oi = self.get_object_info_for_delete(bucket, object, &lookup_opts).await;
|
||||
crate::set_disk::SetDisks::evaluate_write_precondition(oi, &http_preconditions, bucket, object, opts)
|
||||
}
|
||||
|
||||
@@ -1421,33 +1401,36 @@ impl ECStore {
|
||||
.await;
|
||||
return enqueue_transition_after_write(self.as_ref(), result, LcEventSrc::S3CompleteMultipartUpload, opts).await;
|
||||
}
|
||||
if opts.http_preconditions.is_some() && !opts.data_movement {
|
||||
// Preserve explicitly scoped internal reads and borrowed-lock callers.
|
||||
let require_all_pools =
|
||||
!opts.replication_request && !opts.no_lock && !opts.skip_decommissioned && !opts.skip_rebalancing;
|
||||
if let Some(err) = self.check_write_precondition(bucket, object, opts, require_all_pools).await {
|
||||
return Err(err);
|
||||
}
|
||||
let multipool_store = (!opts.skip_decommissioned
|
||||
&& !opts.skip_rebalancing
|
||||
&& !opts.restore_copyback
|
||||
&& !opts.is_inbound_multipart_replica()
|
||||
&& self.uses_multipool_put_commit(bucket, object, opts).await?)
|
||||
.then_some(self.as_ref());
|
||||
if multipool_store.is_none()
|
||||
&& opts.http_preconditions.is_some()
|
||||
&& !opts.data_movement
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let result = match self.multipart_upload_pool_idx(bucket, object, upload_id, opts).await {
|
||||
Ok(pool_idx) => {
|
||||
let complete = |pool_idx: usize, parts| {
|
||||
Box::pin(
|
||||
self.pools[pool_idx]
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts, opts)
|
||||
.await
|
||||
}
|
||||
.get_disks_by_key(object)
|
||||
.complete_multipart_upload_with_store(bucket, object, upload_id, parts, opts, multipool_store),
|
||||
)
|
||||
};
|
||||
let result = match self.multipart_upload_pool_idx(bucket, object, upload_id, opts).await {
|
||||
Ok(pool_idx) => complete(pool_idx, uploaded_parts).await,
|
||||
// The staging upload is already gone. The completed object lives on
|
||||
// the pool that published it; other pools answer InvalidUploadID.
|
||||
Err(err) if is_err_invalid_upload_id(&err) => {
|
||||
let mut missing = err;
|
||||
let mut found = None;
|
||||
for pool_idx in self.existing_multipart_pool_order().await {
|
||||
match self.pools[pool_idx]
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts.clone(), opts)
|
||||
.await
|
||||
{
|
||||
match complete(pool_idx, uploaded_parts.clone()).await {
|
||||
Ok(info) => {
|
||||
found = Some(Ok(info));
|
||||
break;
|
||||
|
||||
+1255
-200
File diff suppressed because it is too large
Load Diff
@@ -876,6 +876,25 @@ impl ECStore {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Completed sources have passed the terminal empty-pool verification and can
|
||||
/// be removed from the deployment. Active, failed and canceled sources remain readable.
|
||||
pub(super) async fn completed_decommission_pools(&self) -> Vec<usize> {
|
||||
self.pool_meta
|
||||
.read()
|
||||
.await
|
||||
.pools
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, status)| {
|
||||
status
|
||||
.decommission
|
||||
.as_ref()
|
||||
.filter(|info| info.complete && !info.failed && !info.canceled && info.unresolved_entries.is_empty())
|
||||
.map(|_| idx)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Observe every pool for a conditional-write preflight. This does not
|
||||
/// hold the namespace locks needed to prove a condition at publication.
|
||||
pub(super) async fn get_latest_object_info_for_conditional_write(
|
||||
@@ -904,9 +923,14 @@ impl ECStore {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let completed = if require_all_pools && !is_meta_bucketname(bucket) {
|
||||
self.completed_decommission_pools().await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut futures = Vec::with_capacity(self.pools.len());
|
||||
for (idx, pool) in self.pools.iter().enumerate() {
|
||||
if suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
|
||||
if completed.contains(&idx) || suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,10 +29,10 @@ use http::HeaderMap;
|
||||
use rustfs_filemeta::FileMeta;
|
||||
use sha2::{Digest, Sha256};
|
||||
use storage_api::dst_production_ecstore::{
|
||||
BLOCK_SIZE_V2, BucketOperations, CHECK_PART_FILE_CORRUPT, CHECK_PART_SUCCESS, CrashPoint, CrashSemantics, DiskAPI,
|
||||
DstSimSetFixture, EcstoreResult, Error as EcstoreError, HealOperations, HealOpts, HealScanMode, MakeBucketOptions, ObjectIO,
|
||||
ObjectOperations, ObjectOptions, PutObjReader, ReadOptions, RngSource, STORAGE_FORMAT_FILE, SimDiskIoTrait, SimRng,
|
||||
dst_object_options, is_err_object_not_found, load_format_erasure, make_dst_sim_set_disks,
|
||||
BLOCK_SIZE_V2, BucketOperations, CHECK_PART_FILE_CORRUPT, CHECK_PART_SUCCESS, CompletePart, CrashPoint, CrashSemantics,
|
||||
DiskAPI, DstSimSetFixture, EcstoreResult, Error as EcstoreError, HealOperations, HealOpts, HealScanMode, MakeBucketOptions,
|
||||
MultipartOperations, ObjectIO, ObjectOperations, ObjectOptions, PutObjReader, ReadOptions, RngSource, STORAGE_FORMAT_FILE,
|
||||
SimDiskIoTrait, SimRng, dst_object_options, is_err_object_not_found, load_format_erasure, make_dst_sim_set_disks,
|
||||
};
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
@@ -742,3 +742,284 @@ async fn dst_prod_test4_deterministic_multiseed_concurrent_chaos_and_replay_equi
|
||||
assert_eq!(digest_run1, digest_run2, "deterministic replay invariant violated for seed {seed:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Test 5: Real ECStore multipart commit crash cutpoints (backlog#3390 P0-5):
|
||||
// - `fault.multipart_crashed_before_commit_rename`
|
||||
// (`CrashPoint::MultipartBeforeCommitRename`)
|
||||
// - `fault.multipart_crashed_before_cleanup`
|
||||
// (`CrashPoint::MultipartAfterCommitBeforeCleanup`)
|
||||
// ============================================================================
|
||||
#[tokio::test]
|
||||
async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_before_cleanup() {
|
||||
let opts = ObjectOptions::default();
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Cutpoint A: `fault.multipart_crashed_before_commit_rename` (4 seeds)
|
||||
// Pre-commit crash after parts are staged/locked, before rename_data commit:
|
||||
// 1. Real cutpoint fires and consumes its one-shot arm.
|
||||
// 2. After ALICE power-loss reboot, prior object v1 stays 100% intact
|
||||
// (and a brand-new key remains absent — zero partial visibility).
|
||||
// 3. Retrying `complete_multipart_upload` commits cleanly and reads back
|
||||
// 100% bit-exact concatenated multipart bytes.
|
||||
// ------------------------------------------------------------------------
|
||||
let mut before_rename_hits = 0usize;
|
||||
for &seed in &[0x4D50_0001_u64, 0x4D50_0002_u64, 0x4D50_0003_u64, 0x4D50_0004_u64] {
|
||||
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
|
||||
.await
|
||||
.expect("dst sim SetDisks for multipart pre-rename cutpoint");
|
||||
for sim in &fixture.sim_disks {
|
||||
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
|
||||
}
|
||||
let bucket = "dst-mp-before-rename";
|
||||
fixture
|
||||
.set_disks
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("make_bucket");
|
||||
|
||||
let overwrite_key = format!("mp/overwrite-before-rename-{seed:x}.bin");
|
||||
let fresh_key = format!("mp/fresh-before-rename-{seed:x}.bin");
|
||||
let v1_payload = deterministic_payload(seed, "mp-v1", BLOCK_SIZE_V2 + 12_288);
|
||||
put_bytes(&fixture, bucket, &overwrite_key, &v1_payload)
|
||||
.await
|
||||
.expect("commit baseline v1");
|
||||
|
||||
for (key, prior) in [(&overwrite_key, Some(&v1_payload)), (&fresh_key, None)] {
|
||||
let part1 = deterministic_payload(seed ^ 0x11, key, 5 * 1024 * 1024);
|
||||
let part2 = deterministic_payload(seed ^ 0x22, key, 65_536);
|
||||
let mut expected = Vec::with_capacity(part1.len() + part2.len());
|
||||
expected.extend_from_slice(&part1);
|
||||
expected.extend_from_slice(&part2);
|
||||
|
||||
let upload = fixture
|
||||
.set_disks
|
||||
.new_multipart_upload(bucket, key, &opts)
|
||||
.await
|
||||
.expect("new_multipart_upload");
|
||||
let mut r1 = PutObjReader::from_vec(part1);
|
||||
let p1 = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, key, &upload.upload_id, 1, &mut r1, &opts)
|
||||
.await
|
||||
.expect("put part 1");
|
||||
let mut r2 = PutObjReader::from_vec(part2);
|
||||
let p2 = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, key, &upload.upload_id, 2, &mut r2, &opts)
|
||||
.await
|
||||
.expect("put part 2");
|
||||
let parts = vec![
|
||||
CompletePart {
|
||||
part_num: 1,
|
||||
etag: p1.etag,
|
||||
..Default::default()
|
||||
},
|
||||
CompletePart {
|
||||
part_num: 2,
|
||||
etag: p2.etag,
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
|
||||
// Arm REAL ECStore cutpoint `MultipartBeforeCommitRename`.
|
||||
fixture.crash_registry.arm(CrashPoint::MultipartBeforeCommitRename, key);
|
||||
let crashed = fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, key, &upload.upload_id, parts.clone(), &opts)
|
||||
.await;
|
||||
assert!(
|
||||
crashed.is_err(),
|
||||
"seed={seed:#x} key={key}: MultipartBeforeCommitRename must abort complete_multipart_upload"
|
||||
);
|
||||
assert!(
|
||||
!fixture
|
||||
.crash_registry
|
||||
.take_if_armed(CrashPoint::MultipartBeforeCommitRename, key),
|
||||
"seed={seed:#x} key={key}: real ECStore MultipartBeforeCommitRename cutpoint must have fired"
|
||||
);
|
||||
before_rename_hits += 1;
|
||||
|
||||
// Simulate abrupt ALICE power loss right at the cutpoint.
|
||||
fixture.crash_and_reboot_all();
|
||||
|
||||
// Verify zero corrupt xl.meta and zero partial visibility.
|
||||
for (slot, sim_disk) in fixture.sim_disks.iter().enumerate() {
|
||||
let xl_rel = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}");
|
||||
if let Ok(raw) = SimDiskIoTrait::read_file(sim_disk.sim(), &xl_rel).await {
|
||||
assert!(
|
||||
FileMeta::load(&raw).is_ok(),
|
||||
"corrupt xl.meta on drive {slot} after MultipartBeforeCommitRename"
|
||||
);
|
||||
}
|
||||
}
|
||||
match prior {
|
||||
Some(v1) => {
|
||||
assert_eq!(
|
||||
get_bytes(&fixture, bucket, key).await.expect("prior v1 must remain intact"),
|
||||
*v1,
|
||||
"pre-rename crash must leave prior object v1 bit-exact"
|
||||
);
|
||||
}
|
||||
None => {
|
||||
let res = get_bytes(&fixture, bucket, key).await;
|
||||
assert!(
|
||||
res.is_err() && is_err_object_not_found(res.as_ref().unwrap_err()),
|
||||
"pre-rename crash on fresh key must not expose partial object: {res:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Retrying completion after reboot must succeed cleanly and commit full multipart payload!
|
||||
fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, key, &upload.upload_id, parts, &opts)
|
||||
.await
|
||||
.expect("retry complete_multipart_upload after pre-rename crash must succeed");
|
||||
assert_eq!(
|
||||
get_bytes(&fixture, bucket, key).await.expect("read retried multipart object"),
|
||||
expected,
|
||||
"retried multipart object bytes must match part1 || part2"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
before_rename_hits, 8,
|
||||
"fault.multipart_crashed_before_commit_rename must hit across all 4 seeds (overwrite + fresh)"
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Cutpoint B: `fault.multipart_crashed_before_cleanup` (4 seeds)
|
||||
// Post-commit crash after authoritative `rename_data` commit succeeds,
|
||||
// before stale part staging cleanup:
|
||||
// 1. Real cutpoint fires and consumes its one-shot arm.
|
||||
// 2. After ALICE power-loss reboot, newly committed multipart payload is
|
||||
// 100% durably readable (zero data loss!).
|
||||
// 3. All 4 drives have valid xl.meta and pass HighwayHash256S `verify_file`
|
||||
// after post-crash heal.
|
||||
// ------------------------------------------------------------------------
|
||||
let mut before_cleanup_hits = 0usize;
|
||||
for &seed in &[0x4D50_0101_u64, 0x4D50_0102_u64, 0x4D50_0103_u64, 0x4D50_0104_u64] {
|
||||
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
|
||||
.await
|
||||
.expect("dst sim SetDisks for multipart pre-cleanup cutpoint");
|
||||
for sim in &fixture.sim_disks {
|
||||
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
|
||||
}
|
||||
let bucket = "dst-mp-before-cleanup";
|
||||
fixture
|
||||
.set_disks
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("make_bucket");
|
||||
|
||||
let key = format!("mp/committed-before-cleanup-{seed:x}.bin");
|
||||
let part1 = deterministic_payload(seed ^ 0x33, &key, 5 * 1024 * 1024);
|
||||
let part2 = deterministic_payload(seed ^ 0x44, &key, 98_304);
|
||||
let mut expected = Vec::with_capacity(part1.len() + part2.len());
|
||||
expected.extend_from_slice(&part1);
|
||||
expected.extend_from_slice(&part2);
|
||||
|
||||
let upload = fixture
|
||||
.set_disks
|
||||
.new_multipart_upload(bucket, &key, &opts)
|
||||
.await
|
||||
.expect("new_multipart_upload");
|
||||
let mut r1 = PutObjReader::from_vec(part1);
|
||||
let p1 = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, &key, &upload.upload_id, 1, &mut r1, &opts)
|
||||
.await
|
||||
.expect("put part 1");
|
||||
let mut r2 = PutObjReader::from_vec(part2);
|
||||
let p2 = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, &key, &upload.upload_id, 2, &mut r2, &opts)
|
||||
.await
|
||||
.expect("put part 2");
|
||||
let parts = vec![
|
||||
CompletePart {
|
||||
part_num: 1,
|
||||
etag: p1.etag,
|
||||
..Default::default()
|
||||
},
|
||||
CompletePart {
|
||||
part_num: 2,
|
||||
etag: p2.etag,
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
|
||||
// Arm REAL ECStore cutpoint `MultipartAfterCommitBeforeCleanup`.
|
||||
fixture
|
||||
.crash_registry
|
||||
.arm(CrashPoint::MultipartAfterCommitBeforeCleanup, &key);
|
||||
let crashed = fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
|
||||
.await;
|
||||
assert!(
|
||||
crashed.is_err(),
|
||||
"seed={seed:#x}: MultipartAfterCommitBeforeCleanup must interrupt complete_multipart_upload"
|
||||
);
|
||||
assert!(
|
||||
!fixture
|
||||
.crash_registry
|
||||
.take_if_armed(CrashPoint::MultipartAfterCommitBeforeCleanup, &key),
|
||||
"seed={seed:#x}: real ECStore MultipartAfterCommitBeforeCleanup cutpoint must have fired"
|
||||
);
|
||||
before_cleanup_hits += 1;
|
||||
|
||||
// Simulate abrupt ALICE power loss right after commit before cleanup.
|
||||
fixture.crash_and_reboot_all();
|
||||
|
||||
// Newly committed multipart object MUST survive power loss 100% bit-exact!
|
||||
assert_eq!(
|
||||
get_bytes(&fixture, bucket, &key)
|
||||
.await
|
||||
.expect("committed multipart object must survive pre-cleanup power loss"),
|
||||
expected,
|
||||
"seed={seed:#x}: committed multipart payload must be bit-exact after pre-cleanup crash"
|
||||
);
|
||||
|
||||
// Post-crash heal converges cleanly and every drive verifies both parts!
|
||||
let (_heal_item, heal_err) = fixture
|
||||
.set_disks
|
||||
.heal_object(
|
||||
bucket,
|
||||
&key,
|
||||
"",
|
||||
&HealOpts {
|
||||
scan_mode: HealScanMode::Deep,
|
||||
remove: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("post-crash heal_object");
|
||||
assert!(heal_err.is_none(), "post-crash heal error: {heal_err:?}");
|
||||
|
||||
for (slot, disk) in fixture.disks.iter().enumerate() {
|
||||
let fi = disk
|
||||
.read_version("", bucket, &key, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("xl.meta readable on all drives after pre-cleanup crash");
|
||||
let check = disk
|
||||
.verify_file(bucket, &key, &fi)
|
||||
.await
|
||||
.expect("verify_file on committed multipart object");
|
||||
assert_eq!(
|
||||
check.results,
|
||||
vec![CHECK_PART_SUCCESS, CHECK_PART_SUCCESS],
|
||||
"drive {slot} must pass HighwayHash256S verification for both parts"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
before_cleanup_hits, 4,
|
||||
"fault.multipart_crashed_before_cleanup must hit across all 4 seeds"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -106,7 +106,9 @@ pub(crate) mod local_drive_retirement {
|
||||
|
||||
#[cfg(feature = "dst")]
|
||||
pub(crate) mod dst_production_ecstore {
|
||||
pub(crate) use super::storage_contracts::{BucketOperations, HealOperations, MakeBucketOptions, ObjectIO, ObjectOperations};
|
||||
pub(crate) use super::storage_contracts::{
|
||||
BucketOperations, CompletePart, HealOperations, MakeBucketOptions, MultipartOperations, ObjectIO, ObjectOperations,
|
||||
};
|
||||
pub(crate) use super::{DiskAPI, Error, ObjectOptions, PutObjReader, STORAGE_FORMAT_FILE};
|
||||
pub(crate) use rustfs_ecstore::api::{
|
||||
disk::ReadOptions,
|
||||
|
||||
@@ -2275,7 +2275,9 @@ impl MetaObjectV1 {
|
||||
|
||||
rmp::encode::write_str(wr, "Meta")?;
|
||||
rmp::encode::write_map_len(wr, self.meta.len() as u32)?;
|
||||
for (k, v) in &self.meta {
|
||||
let mut sorted_meta: Vec<(&String, &String)> = self.meta.iter().collect();
|
||||
sorted_meta.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_meta {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -2590,7 +2592,9 @@ impl MetaObjectV1Part {
|
||||
if let Some(ref checksums) = self.checksums {
|
||||
rmp::encode::write_str(wr, "crc")?;
|
||||
rmp::encode::write_map_len(wr, checksums.len() as u32)?;
|
||||
for (k, v) in checksums {
|
||||
let mut sorted_checksums: Vec<(&String, &String)> = checksums.iter().collect();
|
||||
sorted_checksums.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_checksums {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -2801,25 +2805,29 @@ impl MetaObject {
|
||||
let nanos = self.mod_time.unwrap_or(OffsetDateTime::UNIX_EPOCH).unix_timestamp_nanos();
|
||||
rmp::encode::write_sint(wr, nanos as i64)?;
|
||||
|
||||
// MetaSys (write nil when empty)
|
||||
// MetaSys (write nil when empty; sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
rmp::encode::write_str(wr, "MetaSys")?;
|
||||
if !include_maps || self.meta_sys.is_empty() {
|
||||
rmp::encode::write_nil(wr)?;
|
||||
} else {
|
||||
rmp::encode::write_map_len(wr, self.meta_sys.len() as u32)?;
|
||||
for (k, v) in &self.meta_sys {
|
||||
let mut sorted_meta_sys: Vec<(&String, &Vec<u8>)> = self.meta_sys.iter().collect();
|
||||
sorted_meta_sys.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_meta_sys {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_bin(wr, v)?;
|
||||
}
|
||||
}
|
||||
|
||||
// MetaUsr (write nil when empty)
|
||||
// MetaUsr (write nil when empty; sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
rmp::encode::write_str(wr, "MetaUsr")?;
|
||||
if !include_maps || self.meta_user.is_empty() {
|
||||
rmp::encode::write_nil(wr)?;
|
||||
} else {
|
||||
rmp::encode::write_map_len(wr, self.meta_user.len() as u32)?;
|
||||
for (k, v) in &self.meta_user {
|
||||
let mut sorted_meta_user: Vec<(&String, &String)> = self.meta_user.iter().collect();
|
||||
sorted_meta_user.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_meta_user {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -3891,13 +3899,15 @@ impl MetaDeleteMarker {
|
||||
let nanos = self.mod_time.unwrap_or(OffsetDateTime::UNIX_EPOCH).unix_timestamp_nanos();
|
||||
rmp::encode::write_sint(wr, nanos as i64)?;
|
||||
|
||||
// MetaSys
|
||||
// MetaSys (sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
rmp::encode::write_str(wr, "MetaSys")?;
|
||||
if !include_meta_sys || self.meta_sys.is_empty() {
|
||||
rmp::encode::write_map_len(wr, 0)?;
|
||||
} else {
|
||||
rmp::encode::write_map_len(wr, self.meta_sys.len() as u32)?;
|
||||
for (k, v) in &self.meta_sys {
|
||||
let mut sorted_meta_sys: Vec<(&String, &Vec<u8>)> = self.meta_sys.iter().collect();
|
||||
sorted_meta_sys.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_meta_sys {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_bin(wr, v)?;
|
||||
}
|
||||
@@ -7049,4 +7059,80 @@ mod read_xl_meta_sync_equivalence_tests {
|
||||
assert_eq!(e, Error::Unexpected, "short read surfaces as Unexpected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xl_meta_encoding_is_deterministic_across_hash_map_orders() {
|
||||
let version_id = Some(Uuid::from_u128(0x11223344_5566_7788_99aa_bbccddeeff00));
|
||||
let mod_time = Some(OffsetDateTime::from_unix_timestamp(1_735_000_000).unwrap());
|
||||
|
||||
let build_obj = |reverse: bool| {
|
||||
let mut meta_sys = HashMap::new();
|
||||
let mut meta_user = HashMap::new();
|
||||
let sys_entries = [
|
||||
("x-rustfs-internal-a", b"alpha".to_vec()),
|
||||
("x-rustfs-internal-z", b"omega".to_vec()),
|
||||
("x-rustfs-internal-m", b"middle".to_vec()),
|
||||
("x-rustfs-internal-c", b"charlie".to_vec()),
|
||||
];
|
||||
let usr_entries = [
|
||||
("content-type", "application/octet-stream"),
|
||||
("etag", "0123456789abcdef0123456789abcdef"),
|
||||
("x-amz-meta-z", "last"),
|
||||
("x-amz-meta-a", "first"),
|
||||
];
|
||||
if reverse {
|
||||
for (k, v) in sys_entries.iter().rev() {
|
||||
meta_sys.insert((*k).to_string(), v.clone());
|
||||
}
|
||||
for (k, v) in usr_entries.iter().rev() {
|
||||
meta_user.insert((*k).to_string(), (*v).to_string());
|
||||
}
|
||||
} else {
|
||||
for (k, v) in sys_entries {
|
||||
meta_sys.insert(k.to_string(), v);
|
||||
}
|
||||
for (k, v) in usr_entries {
|
||||
meta_user.insert(k.to_string(), v.to_string());
|
||||
}
|
||||
}
|
||||
MetaObject {
|
||||
version_id,
|
||||
mod_time,
|
||||
size: 262_144,
|
||||
meta_sys,
|
||||
meta_user,
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
|
||||
let first = build_obj(false).marshal_msg().expect("marshal first");
|
||||
for i in 0..32 {
|
||||
let candidate = build_obj(i % 2 == 1).marshal_msg().expect("marshal candidate");
|
||||
assert_eq!(first, candidate, "xl.meta object bytes must be deterministic on iteration {i}");
|
||||
}
|
||||
|
||||
let build_dm = |reverse: bool| {
|
||||
let mut meta_sys = HashMap::new();
|
||||
let entries = [("k3", b"3".to_vec()), ("k1", b"1".to_vec()), ("k2", b"2".to_vec())];
|
||||
if reverse {
|
||||
for (k, v) in entries.iter().rev() {
|
||||
meta_sys.insert((*k).to_string(), v.clone());
|
||||
}
|
||||
} else {
|
||||
for (k, v) in entries {
|
||||
meta_sys.insert(k.to_string(), v);
|
||||
}
|
||||
}
|
||||
MetaDeleteMarker {
|
||||
version_id,
|
||||
mod_time,
|
||||
meta_sys,
|
||||
}
|
||||
};
|
||||
let dm_first = build_dm(false).marshal_msg().expect("marshal dm first");
|
||||
for i in 0..32 {
|
||||
let dm_candidate = build_dm(i % 2 == 1).marshal_msg().expect("marshal dm candidate");
|
||||
assert_eq!(dm_first, dm_candidate, "xl.meta delete marker bytes must be deterministic");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ use thiserror::Error;
|
||||
use super::heal::{DiskError, EcstoreError, storage_api::owner::EcstorePoolMetadataFailure};
|
||||
|
||||
const HEAL_DANGLING_DELETE_GRACE_MESSAGE: &str = "dangling object deletion deferred by heal grace window";
|
||||
pub(crate) const MRF_MISSING_PROOF_PREFIX: &str = "Missing exact storage proof for durable MRF repair ";
|
||||
|
||||
/// Custom error type for heal operations
|
||||
/// This enum defines various error variants that can occur during
|
||||
@@ -57,6 +56,10 @@ pub enum Error {
|
||||
#[error("Heal task execution failed: {message}")]
|
||||
TaskExecutionFailed { message: String },
|
||||
|
||||
/// The storage result could not authorize discharge of a durable partial write.
|
||||
#[error("Missing exact storage proof for durable MRF repair {target}: {reason}")]
|
||||
MrfStorageProofUnavailable { target: String, reason: &'static str },
|
||||
|
||||
/// Only the qualified MRF Deep check may produce this terminal result.
|
||||
#[error("Independent verification unavailable for legacy object {target}; durable MRF responsibility retained")]
|
||||
LegacyMrfUnverified { target: String },
|
||||
@@ -239,11 +242,10 @@ pub(crate) fn classify_heal_error(error: &Error) -> HealErrorClass {
|
||||
| Error::ReplacementNamespaceChanged
|
||||
| Error::TransientSkip { .. }
|
||||
| Error::BucketDiscoveryIncomplete => HealErrorClass::Transient,
|
||||
Error::LegacyMrfUnverified { .. } => HealErrorClass::Permanent,
|
||||
Error::LegacyMrfUnverified { .. } | Error::MrfStorageProofUnavailable { .. } => HealErrorClass::Permanent,
|
||||
Error::Storage(error) => classify_storage_error(error),
|
||||
Error::Disk(error) => classify_disk_error(error),
|
||||
Error::Io(error) => classify_io_error(error),
|
||||
Error::TaskExecutionFailed { message } if message.starts_with(MRF_MISSING_PROOF_PREFIX) => HealErrorClass::Permanent,
|
||||
Error::TaskExecutionFailed { message } | Error::Other(message) => {
|
||||
classify_error_display(message).unwrap_or(HealErrorClass::Permanent)
|
||||
}
|
||||
|
||||
@@ -2317,6 +2317,13 @@ impl HealManager {
|
||||
self.storage.mrf_bucket_incarnation_retired(bucket, expected).await
|
||||
}
|
||||
|
||||
pub(super) async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
|
||||
) -> Result<bool> {
|
||||
self.storage.probe_mrf_unversioned_absence(anchor).await
|
||||
}
|
||||
|
||||
async fn submit_heal_request_with_receipt_alias_and_mrf_notice(
|
||||
&self,
|
||||
mut request: HealRequest,
|
||||
|
||||
@@ -539,7 +539,7 @@ impl PriorityHealQueue {
|
||||
|
||||
let chosen_index = first_runnable.filter(|index| {
|
||||
let item = &items[*index];
|
||||
item.priority == HealPriority::Normal
|
||||
matches!(item.priority, HealPriority::Normal | HealPriority::High)
|
||||
&& matches!(item.request.source, HealRequestSource::Mrf | HealRequestSource::Internal)
|
||||
});
|
||||
let best_effort_priority = best_effort_candidates
|
||||
@@ -573,7 +573,7 @@ impl PriorityHealQueue {
|
||||
self.mrf_normal_dispatches_since_best_effort = 0;
|
||||
self.last_best_effort_source = Some(request.source);
|
||||
} else if matches!(request.source, HealRequestSource::Mrf | HealRequestSource::Internal)
|
||||
&& request.priority == HealPriority::Normal
|
||||
&& matches!(request.priority, HealPriority::Normal | HealPriority::High)
|
||||
{
|
||||
self.mrf_normal_dispatches_since_best_effort = self.mrf_normal_dispatches_since_best_effort.saturating_add(1);
|
||||
}
|
||||
|
||||
@@ -274,6 +274,12 @@ impl HealManager {
|
||||
"Heal scheduler task started"
|
||||
);
|
||||
let result = task.execute_owned(parent.clone()).await;
|
||||
crate::heal::mrf_queue::management::record_heal_source_executed(task.source);
|
||||
if task.source == HealRequestSource::Mrf
|
||||
&& matches!(&result, Err(err) if err.to_string().contains("recreate_failed"))
|
||||
{
|
||||
crate::heal::mrf_queue::management::record_mrf_recreate_failed_loop();
|
||||
}
|
||||
let retry_request = retry_request_for_result_with_budget(task.as_ref(), &result).await;
|
||||
record_task_disposition(&disposition_cache_clone, task.as_ref(), &result, retry_request.is_some()).await;
|
||||
match &result {
|
||||
|
||||
@@ -2176,6 +2176,10 @@ fn only_typed_mrf_result_can_pause_unverified_legacy() {
|
||||
Err(Error::TaskExecutionFailed {
|
||||
message: "Missing exact storage proof for durable MRF repair display only".to_owned(),
|
||||
}),
|
||||
Err(Error::MrfStorageProofUnavailable {
|
||||
target: "file not found".to_owned(),
|
||||
reason: "storage receipt did not verify the requested identity and disposition",
|
||||
}),
|
||||
Err(Error::TaskCancelled),
|
||||
Err(Error::TaskTimeout),
|
||||
] {
|
||||
@@ -2580,6 +2584,48 @@ fn test_priority_queue_fairness_skips_blocked_best_effort_source() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_priority_queue_fairness_prevents_high_priority_mrf_from_starving_scanner() {
|
||||
let mut queue = PriorityHealQueue::new();
|
||||
for index in 0..8 {
|
||||
assert_eq!(
|
||||
queue.push(bucket_request(&format!("mrf-high-{index}"), HealPriority::High, HealRequestSource::Mrf)),
|
||||
QueuePushOutcome::Accepted
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
queue.push(bucket_request("scanner", HealPriority::Low, HealRequestSource::Scanner)),
|
||||
QueuePushOutcome::Accepted
|
||||
);
|
||||
assert_eq!(
|
||||
queue.push(bucket_request("read-repair", HealPriority::Low, HealRequestSource::ReadRepair)),
|
||||
QueuePushOutcome::Accepted
|
||||
);
|
||||
|
||||
for _ in 0..4 {
|
||||
let (request, _) = queue.pop_runnable_with_fairness(|_| true, |_| None);
|
||||
assert_eq!(request.expect("High MRF quantum should run").source, HealRequestSource::Mrf);
|
||||
}
|
||||
let (request, _) = queue.pop_runnable_with_fairness(|_| true, |_| None);
|
||||
assert_eq!(
|
||||
request
|
||||
.expect("Scanner must not be starved by High-priority MRF burst")
|
||||
.source,
|
||||
HealRequestSource::Scanner
|
||||
);
|
||||
for _ in 0..4 {
|
||||
let (request, _) = queue.pop_runnable_with_fairness(|_| true, |_| None);
|
||||
assert_eq!(request.expect("Next High MRF quantum should run").source, HealRequestSource::Mrf);
|
||||
}
|
||||
let (request, _) = queue.pop_runnable_with_fairness(|_| true, |_| None);
|
||||
assert_eq!(
|
||||
request
|
||||
.expect("ReadRepair must not be starved by High-priority MRF burst")
|
||||
.source,
|
||||
HealRequestSource::ReadRepair
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_priority_queue_fifo_same_priority() {
|
||||
let mut queue = PriorityHealQueue::new();
|
||||
|
||||
@@ -57,6 +57,9 @@ use partial_write::{PartialWrites, ResponsibilityCheckpoint};
|
||||
|
||||
const MRF_LIFECYCLE_CONTROL_CAPACITY: usize = 128;
|
||||
const MRF_JOURNAL_DISK_CONCURRENCY: usize = 4;
|
||||
const MRF_HELD_ABSENCE_PROBE_INTERVAL: Duration = Duration::from_secs(1);
|
||||
const MRF_HELD_ABSENCE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MRF_LIFECYCLE_LIST_MAX_LIMIT: usize = 256;
|
||||
|
||||
static GLOBAL_MRF_LIFECYCLE_SENDER: std::sync::OnceLock<mpsc::Sender<MrfLifecycleCommand>> = std::sync::OnceLock::new();
|
||||
@@ -1035,6 +1038,29 @@ async fn submit_mrf_heal_request(
|
||||
Ok(receipt.result)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
struct MrfCheckpointRecords {
|
||||
authoritative: Vec<u8>,
|
||||
legacy: Vec<u8>,
|
||||
lifecycle: Vec<ResponsibilityCheckpoint>,
|
||||
}
|
||||
|
||||
impl MrfCheckpointRecords {
|
||||
fn append(&mut self, intent: &MrfIntent) -> Option<&[u8]> {
|
||||
let start = self.authoritative.len();
|
||||
if !encode_intent(intent, &mut self.authoritative) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
return None;
|
||||
}
|
||||
let encoded = &self.authoritative[start..];
|
||||
if intent.kind == MrfKind::MetadataCorruption || intent.scope.is_none() {
|
||||
self.legacy.extend_from_slice(encoded);
|
||||
}
|
||||
Some(encoded)
|
||||
}
|
||||
}
|
||||
|
||||
struct MrfRuntime {
|
||||
queue: MrfQueue,
|
||||
partial_writes: PartialWrites,
|
||||
@@ -1410,20 +1436,17 @@ impl MrfRuntime {
|
||||
self.publish_metrics();
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> (Vec<u8>, Vec<u8>) {
|
||||
let mut authoritative = Vec::new();
|
||||
let mut legacy = Vec::new();
|
||||
for intent in self.queue.intents().chain(self.partial_writes.intents()) {
|
||||
let scoped_identity =
|
||||
!matches!(intent.kind, rustfs_common::mrf_channel::MrfKind::MetadataCorruption) && intent.scope.is_some();
|
||||
if !encode_intent(intent, &mut authoritative) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
}
|
||||
if !scoped_identity && !encode_intent(intent, &mut legacy) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
}
|
||||
fn snapshot(&self) -> MrfCheckpointRecords {
|
||||
let mut snapshot = MrfCheckpointRecords::default();
|
||||
for intent in self.queue.intents() {
|
||||
let _ = snapshot.append(intent);
|
||||
}
|
||||
(authoritative, legacy)
|
||||
// Bind the lifecycle record to the exact published bytes, including
|
||||
// the record CRC, without running the codec a second time.
|
||||
snapshot.lifecycle = self
|
||||
.partial_writes
|
||||
.checkpoint_records(|intent| snapshot.append(intent).map(|bytes| sha2::Sha256::digest(bytes).into()));
|
||||
snapshot
|
||||
}
|
||||
|
||||
async fn flush(&mut self) -> bool {
|
||||
@@ -1435,29 +1458,31 @@ impl MrfRuntime {
|
||||
if self.partial_writes.pending_lifecycle_transition.is_some() {
|
||||
return self.flush_pending_lifecycle(None).await;
|
||||
}
|
||||
let (authoritative, legacy) = self.snapshot();
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle,
|
||||
} = self.snapshot();
|
||||
if lifecycle.len() != self.partial_writes.depth() {
|
||||
return false;
|
||||
}
|
||||
let lifecycle_byte_limit = self.config.journal_max_bytes.saturating_mul(4);
|
||||
let lifecycle_checkpoint = if self.partial_writes.depth() == 0 {
|
||||
let lifecycle_checkpoint = if lifecycle.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let records = self.partial_writes.checkpoint_records(intent_digest);
|
||||
(records.len() == self.partial_writes.depth())
|
||||
.then(|| {
|
||||
encode_mrf_lifecycle_checkpoint(
|
||||
self.lifecycle_format_version,
|
||||
self.checkpoint_owner,
|
||||
self.next_checkpoint_sequence,
|
||||
records,
|
||||
lifecycle_byte_limit,
|
||||
)
|
||||
})
|
||||
.flatten()
|
||||
let Some(checkpoint) = encode_mrf_lifecycle_checkpoint(
|
||||
self.lifecycle_format_version,
|
||||
self.checkpoint_owner,
|
||||
self.next_checkpoint_sequence,
|
||||
lifecycle,
|
||||
lifecycle_byte_limit,
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
Some(checkpoint)
|
||||
};
|
||||
let lifecycle_ready = self.partial_writes.depth() == 0 || lifecycle_checkpoint.is_some();
|
||||
let (committed_persisted, committed_on_disk) = if authoritative.is_empty() {
|
||||
(true, false)
|
||||
} else if !lifecycle_ready {
|
||||
(false, false)
|
||||
} else {
|
||||
match snapshot::publish_committed_snapshot_with_companion(
|
||||
&journal_disks().await,
|
||||
@@ -1487,14 +1512,8 @@ impl MrfRuntime {
|
||||
}
|
||||
}
|
||||
};
|
||||
self.finish_flush(
|
||||
&authoritative,
|
||||
&legacy,
|
||||
committed_persisted,
|
||||
committed_on_disk,
|
||||
lifecycle_checkpoint.is_some(),
|
||||
)
|
||||
.await
|
||||
self.finish_flush(&authoritative, &legacy, committed_persisted, committed_on_disk)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn pending_lifecycle_commit_matches(
|
||||
@@ -1541,7 +1560,14 @@ impl MrfRuntime {
|
||||
.clamp(Duration::from_secs(5), Duration::from_secs(60));
|
||||
let intent = pending.intent.clone();
|
||||
let record = pending.record.clone();
|
||||
let mut records = self.partial_writes.checkpoint_records(intent_digest);
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle: mut records,
|
||||
} = self.snapshot();
|
||||
if records.len() != self.partial_writes.depth() {
|
||||
return false;
|
||||
}
|
||||
let Some(current) = records.iter_mut().find(|current| {
|
||||
current.responsibility_id == record.responsibility_id && current.intent_digest == record.intent_digest
|
||||
}) else {
|
||||
@@ -1563,15 +1589,14 @@ impl MrfRuntime {
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let (authoritative, legacy) = self.snapshot();
|
||||
// A lost publication result must not regenerate the body or downgrade
|
||||
// the owner. An exact committed readback resolves it without new writes.
|
||||
let already_committed = match self.pending_lifecycle_commit_matches(&authoritative, &lifecycle).await {
|
||||
Ok(committed) => committed,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let (authoritative, lifecycle) = if already_committed {
|
||||
(authoritative, lifecycle)
|
||||
let authoritative = if already_committed {
|
||||
authoritative
|
||||
} else {
|
||||
let proof = match proof {
|
||||
Some(proof) => proof,
|
||||
@@ -1636,7 +1661,7 @@ impl MrfRuntime {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
(authoritative, lifecycle)
|
||||
authoritative
|
||||
};
|
||||
if !self.partial_writes.restore_state(&intent, &record) {
|
||||
return false;
|
||||
@@ -1647,8 +1672,7 @@ impl MrfRuntime {
|
||||
self.next_checkpoint_sequence = self.next_checkpoint_sequence.saturating_add(1);
|
||||
self.journal_on_disk = true;
|
||||
self.dirty = true;
|
||||
self.finish_flush(&authoritative, &legacy, true, true, !lifecycle.is_empty())
|
||||
.await
|
||||
self.finish_flush(&authoritative, &legacy, true, true).await
|
||||
}
|
||||
|
||||
async fn finish_flush(
|
||||
@@ -1657,7 +1681,6 @@ impl MrfRuntime {
|
||||
legacy: &[u8],
|
||||
committed_persisted: bool,
|
||||
committed_on_disk: bool,
|
||||
lifecycle_ready: bool,
|
||||
) -> bool {
|
||||
let authoritative_persisted = write_journal(MRF_SCOPED_JOURNAL_PATH, authoritative).await;
|
||||
if !authoritative.is_empty() {
|
||||
@@ -1676,7 +1699,7 @@ impl MrfRuntime {
|
||||
}
|
||||
all_deleted
|
||||
} else {
|
||||
lifecycle_ready && committed_persisted
|
||||
committed_persisted
|
||||
};
|
||||
// Keep dirty until the committed checkpoint, authoritative snapshot,
|
||||
// and compatibility mirror have all been accepted; otherwise a
|
||||
@@ -1851,22 +1874,20 @@ impl MrfRuntime {
|
||||
.chain(self.partial_writes.anchors())
|
||||
.cloned()
|
||||
.collect();
|
||||
let mut buckets: Vec<Arc<str>> = anchors.iter().map(|anchor| anchor.bucket.clone()).collect();
|
||||
buckets.sort_unstable();
|
||||
buckets.dedup();
|
||||
for bucket in &buckets {
|
||||
rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events_for(bucket.as_ref(), &mut anchors);
|
||||
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
|
||||
let legacy = rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for_buckets(&buckets);
|
||||
if rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events(&mut anchors) != 0 {
|
||||
let remaining: HashSet<_> = anchors.into_iter().collect();
|
||||
let previous_replay_anchor_count = self.durable_replay_anchors.len();
|
||||
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
|
||||
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
|
||||
let partial_writes_changed = self.partial_writes.retain_unproven(&remaining);
|
||||
self.dirty |= replay_anchors_changed || partial_writes_changed;
|
||||
}
|
||||
let remaining: HashSet<_> = anchors.into_iter().collect();
|
||||
let previous_replay_anchor_count = self.durable_replay_anchors.len();
|
||||
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
|
||||
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
|
||||
self.dirty |= replay_anchors_changed || self.partial_writes.retain_unproven(&remaining);
|
||||
for bucket in buckets {
|
||||
for event in rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for(bucket.as_ref()) {
|
||||
if self.partial_writes.park_unverified_legacy(&event.anchor) {
|
||||
self.dirty = true;
|
||||
}
|
||||
// Exact discharge takes precedence over held notices from this batch.
|
||||
for event in legacy {
|
||||
if self.partial_writes.park_unverified_legacy(&event.anchor) {
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
self.publish_metrics();
|
||||
@@ -2389,6 +2410,9 @@ async fn run_mrf_consumer_with_stop(
|
||||
flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let mut batch: Vec<MrfIntent> = Vec::with_capacity(runtime.config.replay_batch);
|
||||
let mut durable_batch = Vec::with_capacity(runtime.config.replay_batch);
|
||||
let mut held_probe = tokio::task::JoinSet::new();
|
||||
let mut retirement_probe = tokio::task::JoinSet::new();
|
||||
let mut next_held_probe = tokio::time::Instant::now();
|
||||
|
||||
loop {
|
||||
if stop.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
|
||||
@@ -2504,8 +2528,61 @@ async fn run_mrf_consumer_with_stop(
|
||||
runtime.flush().await;
|
||||
}
|
||||
}
|
||||
Some(result) = retirement_probe.join_next(), if !retirement_probe.is_empty() => {
|
||||
let result = match result {
|
||||
Ok((generation, Ok(Ok(true)))) => {
|
||||
runtime.partial_writes.note_bucket_retired(&generation);
|
||||
"proved"
|
||||
}
|
||||
Ok((_, Ok(Ok(false)))) => "retained",
|
||||
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
|
||||
Ok((_, Err(_))) => "timed_out",
|
||||
};
|
||||
counter!("rustfs_heal_mrf_bucket_retirement_probe_total", "result" => result).increment(1);
|
||||
}
|
||||
Some(result) = held_probe.join_next(), if !held_probe.is_empty() => {
|
||||
let result = match result {
|
||||
Ok((anchor, Ok(Ok(true)))) => {
|
||||
if runtime.partial_writes.note_held_absence_proof(anchor) {
|
||||
"proved"
|
||||
} else {
|
||||
"superseded"
|
||||
}
|
||||
}
|
||||
Ok((_, Ok(Ok(false)))) => "retained",
|
||||
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
|
||||
Ok((_, Err(_))) => "timed_out",
|
||||
};
|
||||
counter!("rustfs_heal_mrf_held_absence_probe_total", "result" => result).increment(1);
|
||||
}
|
||||
_ = flush_tick.tick() => {
|
||||
runtime.partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
|
||||
let now = tokio::time::Instant::now();
|
||||
let can_probe = runtime.replay_readable && held_probe.is_empty() && now >= next_held_probe;
|
||||
let (retirement, held) = runtime.partial_writes.plan_maintenance(
|
||||
runtime.replay_readable && retirement_probe.is_empty(),
|
||||
can_probe,
|
||||
);
|
||||
if let Some(generation) = retirement {
|
||||
let manager = manager.clone();
|
||||
retirement_probe.spawn(async move {
|
||||
let outcome = tokio::time::timeout(
|
||||
MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT,
|
||||
manager.mrf_bucket_incarnation_retired(&generation.0, generation.1),
|
||||
).await;
|
||||
(generation, outcome)
|
||||
});
|
||||
}
|
||||
if let Some(anchor) = held {
|
||||
next_held_probe = tokio::time::Instant::now() + MRF_HELD_ABSENCE_PROBE_INTERVAL;
|
||||
let manager = manager.clone();
|
||||
held_probe.spawn(async move {
|
||||
let outcome = tokio::time::timeout(
|
||||
MRF_HELD_ABSENCE_PROBE_TIMEOUT,
|
||||
manager.probe_mrf_unversioned_absence(&anchor),
|
||||
).await;
|
||||
(anchor, outcome)
|
||||
});
|
||||
}
|
||||
runtime.discharge_durable_replay_anchors();
|
||||
match tick_action(
|
||||
runtime.dirty,
|
||||
@@ -3163,7 +3240,11 @@ mod tests {
|
||||
backoff_until: None,
|
||||
};
|
||||
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
|
||||
let (authoritative, legacy_mirror) = runtime.snapshot();
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy: legacy_mirror,
|
||||
..
|
||||
} = runtime.snapshot();
|
||||
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
|
||||
let (legacy_mirror_decoded, legacy_mirror_truncated) = decode_journal(&legacy_mirror);
|
||||
assert_eq!(authoritative_truncated, 0, "W13 authoritative scoped mirror must decode cleanly");
|
||||
@@ -4285,10 +4366,24 @@ mod tests {
|
||||
runtime_checkpoint: None,
|
||||
backoff_until: None,
|
||||
};
|
||||
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
|
||||
runtime
|
||||
.admit_partial_write(scoped.clone(), Some(Uuid::new_v4()))
|
||||
.expect("admit scoped responsibility");
|
||||
assert_eq!(runtime.queue.try_push_typed(compat.clone()), MrfQueuePushResult::Enqueued);
|
||||
|
||||
let (authoritative, legacy) = runtime.snapshot();
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle,
|
||||
} = runtime.snapshot();
|
||||
let plain_bytes = encoded_payload(&compat);
|
||||
let scoped_bytes = encoded_payload(&scoped);
|
||||
assert_eq!(legacy, plain_bytes, "mirror reuses the exact unscoped bytes");
|
||||
assert_eq!(authoritative, [plain_bytes, scoped_bytes].concat());
|
||||
let (_, consumed) = decode_one(&authoritative).expect("decode first record");
|
||||
let durable_digest: [u8; 32] = sha2::Sha256::digest(&authoritative[consumed..]).into();
|
||||
assert_eq!(lifecycle.len(), 1);
|
||||
assert_eq!(lifecycle[0].intent_digest, durable_digest);
|
||||
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
|
||||
assert_eq!(authoritative_truncated, 0);
|
||||
assert_eq!(authoritative_decoded.len(), 2);
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//! Bounded runtime observations. These values never authorize lifecycle changes or prove retirement.
|
||||
|
||||
use super::{GLOBAL_MRF_LIFECYCLE_SENDER, MrfLegacyResponsibility, MrfLifecycleCommand, MrfLifecycleControlError, MrfRuntime};
|
||||
use rustfs_heal_contracts::heal_channel::HealRequestSource;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock, RwLock};
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc, oneshot};
|
||||
use uuid::Uuid;
|
||||
@@ -12,6 +14,28 @@ use uuid::Uuid;
|
||||
const READ_CAPACITY: usize = 8;
|
||||
static READ_BUDGET: LazyLock<Arc<Semaphore>> = LazyLock::new(|| Arc::new(Semaphore::new(READ_CAPACITY)));
|
||||
static SUMMARY: RwLock<Option<MrfLifecycleSummary>> = RwLock::new(None);
|
||||
static SCANNER_HEAL_EXECUTED: AtomicU64 = AtomicU64::new(0);
|
||||
static READ_REPAIR_EXECUTED: AtomicU64 = AtomicU64::new(0);
|
||||
static MRF_RECREATE_FAILED_LOOPS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Records lifetime execution of a scheduled heal task by source for MRF
|
||||
/// anti-starvation and discharge telemetry.
|
||||
pub(crate) fn record_heal_source_executed(source: HealRequestSource) {
|
||||
match source {
|
||||
HealRequestSource::Scanner => {
|
||||
SCANNER_HEAL_EXECUTED.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
HealRequestSource::ReadRepair => {
|
||||
READ_REPAIR_EXECUTED.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records an MRF task retry/error caused by an absent-object recreate failure loop.
|
||||
pub(crate) fn record_mrf_recreate_failed_loop() {
|
||||
MRF_RECREATE_FAILED_LOOPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -28,6 +52,12 @@ pub struct MrfLifecycleSummary {
|
||||
pub operator_accepted_count: usize,
|
||||
pub best_effort_queue_depth: usize,
|
||||
pub responsibility_bytes: usize,
|
||||
#[serde(default)]
|
||||
pub scanner_heal_executed: u64,
|
||||
#[serde(default)]
|
||||
pub read_repair_executed: u64,
|
||||
#[serde(default)]
|
||||
pub recreate_failed_loops: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -47,11 +77,15 @@ pub fn lifecycle_summary() -> Result<MrfLifecycleSummary, MrfLifecycleControlErr
|
||||
if GLOBAL_MRF_LIFECYCLE_SENDER.get().is_none_or(mpsc::Sender::is_closed) {
|
||||
return Err(MrfLifecycleControlError::Unavailable);
|
||||
}
|
||||
SUMMARY
|
||||
let mut summary = SUMMARY
|
||||
.read()
|
||||
.map_err(|_| MrfLifecycleControlError::Unavailable)?
|
||||
.clone()
|
||||
.ok_or(MrfLifecycleControlError::Unavailable)
|
||||
.ok_or(MrfLifecycleControlError::Unavailable)?;
|
||||
summary.scanner_heal_executed = SCANNER_HEAL_EXECUTED.load(Ordering::Relaxed);
|
||||
summary.read_repair_executed = READ_REPAIR_EXECUTED.load(Ordering::Relaxed);
|
||||
summary.recreate_failed_loops = MRF_RECREATE_FAILED_LOOPS.load(Ordering::Relaxed);
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
/// Observes one current responsibility, including Active entries excluded from legacy lists.
|
||||
@@ -117,6 +151,9 @@ pub(super) fn publish_summary(runtime: &MrfRuntime, counts: &super::partial_writ
|
||||
operator_accepted_count: counts.operator_accepted_count,
|
||||
best_effort_queue_depth: runtime.queue.depth(),
|
||||
responsibility_bytes: runtime.partial_writes.bytes(),
|
||||
scanner_heal_executed: SCANNER_HEAL_EXECUTED.load(Ordering::Relaxed),
|
||||
read_repair_executed: READ_REPAIR_EXECUTED.load(Ordering::Relaxed),
|
||||
recreate_failed_loops: MRF_RECREATE_FAILED_LOOPS.load(Ordering::Relaxed),
|
||||
};
|
||||
if let Ok(mut published) = SUMMARY.write() {
|
||||
*published = Some(summary);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user