mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-01 21:54:23 +00:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bbb01de603 | |||
| 05bad624fe | |||
| 909d116183 |
@@ -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 = "2027-02-01T23:59:59Z"
|
||||
expires_at = "2026-11-30T23: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 = "2027-02-01T23:59:59Z"
|
||||
expires_at = "2026-11-30T23: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 = "2027-02-01T23:59:59Z"
|
||||
expires_at = "2026-11-30T23:59:59Z"
|
||||
approval_reference = "https://github.com/rustfs/rustfs/pull/9492"
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
sha256-darwin=2760507f6c38d1b4bb19aad9c333a9630bdd007fc0622427b069e81dae71c5e9
|
||||
sha256-linux=88dfb5119dd16fa0095f3dc3801dbd6c438526fa122f9871f87c8387bcdf7779
|
||||
sha256-linux=35319dec9d304310cb459b22cb59a9ee4418502a705c0516f3d474be649cdbc3
|
||||
|
||||
@@ -73,27 +73,6 @@ 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).
|
||||
@@ -179,24 +158,6 @@ 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'
|
||||
@@ -428,27 +389,6 @@ 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]]
|
||||
@@ -563,24 +503,6 @@ 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,8 +31,7 @@ selected_tests = [
|
||||
]
|
||||
expected_rejection = "Unsigned x-amz-* headers on presigned requests must fail with S3ErrorCode::AccessDenied"
|
||||
timeout_seconds = 120
|
||||
# The two cases share a baseline. Cold rustfs lib test builds can exceed 30 minutes.
|
||||
compile_timeout_seconds = 3600
|
||||
compile_timeout_seconds = 1800
|
||||
|
||||
[[cases]]
|
||||
id = "presigned_allow_duplicate_signed_headers"
|
||||
@@ -55,7 +54,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 = 3600
|
||||
compile_timeout_seconds = 1800
|
||||
|
||||
[[cases]]
|
||||
id = "notify_xml_allow_duplicate_queue"
|
||||
|
||||
@@ -184,7 +184,7 @@ jobs:
|
||||
needs.select-targets.outputs.has_targets == 'true'
|
||||
# Self-hosted runner required: nightly libFuzzer builds exceed hosted disk budget.
|
||||
runs-on: sm-standard-4
|
||||
# The full target set shares one instrumented dependency build.
|
||||
# A cold build links seven instrumented binaries, about 13 minutes each.
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
@@ -211,8 +211,6 @@ jobs:
|
||||
|
||||
- name: Build selected fuzz targets
|
||||
env:
|
||||
# Keep memory-intensive instrumented rustc processes from crowding out the runner.
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
|
||||
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
|
||||
|
||||
@@ -314,8 +312,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 three rustfs builds, two notify builds, runner setup and test execution.
|
||||
timeout-minutes: 270
|
||||
# Allow for the baseline and the isolated rebuilds, each with its own compile deadline.
|
||||
timeout-minutes: 150
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
|
||||
Generated
+191
-144
File diff suppressed because it is too large
Load Diff
+61
-64
@@ -75,7 +75,6 @@ members = [
|
||||
]
|
||||
exclude = [
|
||||
"vendor/hyper",
|
||||
"vendor/nkeys",
|
||||
"vendor/openidconnect",
|
||||
"vendor/rustfs-dst-faults",
|
||||
"vendor/rustfs-dst-runtime",
|
||||
@@ -87,7 +86,7 @@ edition = "2024"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/rustfs/rustfs"
|
||||
rust-version = "1.99.0"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
homepage = "https://rustfs.com"
|
||||
keywords = ["RustFS", "Minio", "object-storage", "filesystem", "s3"]
|
||||
categories = ["web-programming", "development-tools", "filesystem", "network-programming"]
|
||||
@@ -103,60 +102,60 @@ redundant_clone = "warn"
|
||||
|
||||
[workspace.dependencies]
|
||||
# RustFS Internal Crates
|
||||
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-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-dst-runtime = { path = "vendor/rustfs-dst-runtime", default-features = false }
|
||||
rustfs-dst-faults = { path = "vendor/rustfs-dst-faults", default-features = false }
|
||||
|
||||
@@ -261,7 +260,7 @@ rustls-native-certs = "0.8"
|
||||
rustls-pki-types = "1.16.0"
|
||||
x509-parser = "0.18.1"
|
||||
sha1 = "0.11.0"
|
||||
sha2 = "0.11.3"
|
||||
sha2 = "0.11.2"
|
||||
subtle = "2.6"
|
||||
zeroize = { version = "1.9.2" }
|
||||
proptest = "1"
|
||||
@@ -289,9 +288,9 @@ atomic_enum = "0.3.0"
|
||||
aws-config = { version = "1.13.4" }
|
||||
aws-credential-types = { version = "1.3.1" }
|
||||
aws-sdk-kms = { default-features = false, version = "1.134.0" }
|
||||
aws-sdk-s3 = { default-features = false, version = "1.163.0" }
|
||||
aws-sdk-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.52.0" }
|
||||
aws-sdk-s3vectors = { default-features = false, version = "=1.49.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" }
|
||||
@@ -381,7 +380,7 @@ snap = "1.1.2"
|
||||
starshard = { version = "2.4.1" }
|
||||
strum = { version = "0.28.0" }
|
||||
sync_wrapper = "1.0.2"
|
||||
sysinfo = "0.40.5"
|
||||
sysinfo = "0.40.4"
|
||||
temp-env = "0.3.6"
|
||||
tempfile = "3.27.0"
|
||||
test-case = "3.4.1"
|
||||
@@ -432,8 +431,8 @@ dav-server = "0.12.0"
|
||||
|
||||
# Performance Analysis and Memory Profiling
|
||||
rustfs-mimalloc = { version = "0.7.5" }
|
||||
# Hotpath 0.33 infers type-qualified names for methods without explicit labels or impl_type.
|
||||
hotpath = { version = "=0.33.1", default-features = false }
|
||||
# Preserve method names in existing HOTPATH_FOCUS filters and reports.
|
||||
hotpath = { version = "=0.32.1", default-features = false }
|
||||
# Snapshot testing for output format regression detection
|
||||
insta = { version = "1.49" }
|
||||
|
||||
@@ -486,8 +485,6 @@ strip = "none"
|
||||
# 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" }
|
||||
|
||||
@@ -45,9 +45,6 @@ pub const ENV_CAPACITY_METRICS_INTERVAL: &str = "RUSTFS_CAPACITY_METRICS_INTERVA
|
||||
/// Environment variable for following symbolic links during capacity calculation
|
||||
pub const ENV_CAPACITY_FOLLOW_SYMLINKS: &str = "RUSTFS_CAPACITY_FOLLOW_SYMLINKS";
|
||||
|
||||
/// Use filesystem-reported used space on dedicated drive mounts.
|
||||
pub const ENV_CAPACITY_USE_MOUNT_USAGE: &str = "RUSTFS_CAPACITY_USE_MOUNT_USAGE";
|
||||
|
||||
/// Environment variable for enabling dynamic timeout calculation
|
||||
pub const ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: &str = "RUSTFS_CAPACITY_ENABLE_DYNAMIC_TIMEOUT";
|
||||
|
||||
@@ -97,9 +94,6 @@ pub const DEFAULT_CAPACITY_METRICS_INTERVAL_SECS: u64 = 600;
|
||||
/// Default: false (disabled for safety)
|
||||
pub const DEFAULT_CAPACITY_FOLLOW_SYMLINKS: bool = false;
|
||||
|
||||
/// Use directory scans by default to preserve logical file-size accounting.
|
||||
pub const DEFAULT_CAPACITY_USE_MOUNT_USAGE: bool = false;
|
||||
|
||||
/// Enable dynamic timeout calculation based on directory characteristics
|
||||
/// Default: true (enabled)
|
||||
pub const DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: bool = true;
|
||||
|
||||
@@ -11,9 +11,9 @@ use std::fs::{self, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::Path;
|
||||
|
||||
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 MAX_BINARY_BYTES: u64 = 1_073_741_824;
|
||||
const MAX_CATALOG_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_SYMBOLS: usize = 200_000;
|
||||
const NORMALIZATION: &str = "pyroscope-2.1.1-symbolic-demangle-13.9.0";
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -251,14 +251,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn release_sized_catalog_retains_all_function_names() {
|
||||
// Exercises above the observed release GNU binary footprint (~268,737 symbols / ~62.5 MiB JSON).
|
||||
let binary = bulk_executable(280_000, 200);
|
||||
let binary = bulk_executable(110_000, 160);
|
||||
let encoded = catalog(&binary, &"a".repeat(40), "x86_64-unknown-linux-gnu", vec!["pyroscope".into()])
|
||||
.expect("retain complete bounded symbol catalog");
|
||||
assert!(encoded.len() > 60 * 1024 * 1024);
|
||||
assert!(encoded.len() > 16 * 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(), 280_000);
|
||||
assert_eq!(value["symbols"].as_array().expect("symbol array").len(), 110_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -274,7 +273,7 @@ mod tests {
|
||||
assert!(too_many.to_string().contains("reviewed symbol limit"));
|
||||
|
||||
let too_large = catalog(
|
||||
&bulk_executable(38_000, 3_500),
|
||||
&bulk_executable(10_000, 3_500),
|
||||
&source,
|
||||
"x86_64-unknown-linux-gnu",
|
||||
vec!["pyroscope".into()],
|
||||
|
||||
@@ -613,130 +613,6 @@ 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();
|
||||
|
||||
@@ -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 = "0.4.0"
|
||||
rustfs-uring = { git = "https://github.com/rustfs/uring.git", rev = "eb8fc160e71d804427de1e905f5c226d580f71bf" }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dev-dependencies]
|
||||
rustfs-uring = { version = "0.4.0", features = ["fault-injection"] }
|
||||
rustfs-uring = { git = "https://github.com/rustfs/uring.git", rev = "eb8fc160e71d804427de1e905f5c226d580f71bf", features = ["fault-injection"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winapi-util.workspace = true
|
||||
|
||||
@@ -672,7 +672,6 @@ 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.
|
||||
|
||||
@@ -629,7 +629,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_for_options_under_guard(bucket, &guard).await
|
||||
sys.get_bucket_incarnation_id_under_transaction_lock(bucket, &guard).await
|
||||
}
|
||||
|
||||
pub(crate) async fn get_cached_bucket_incarnation_id_in(
|
||||
@@ -2496,7 +2496,6 @@ 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 {
|
||||
@@ -2520,7 +2519,6 @@ 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>,
|
||||
@@ -2580,7 +2578,6 @@ 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()),
|
||||
}),
|
||||
@@ -3673,75 +3670,19 @@ 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?;
|
||||
Self::ensure_transaction_lock_held(bucket, transaction_guard)?;
|
||||
if transaction_guard.is_lock_lost() {
|
||||
return Err(Error::other(format!("bucket incarnation metadata transaction lock was lost: {bucket}")));
|
||||
}
|
||||
Ok(incarnation_id)
|
||||
}
|
||||
|
||||
@@ -7766,42 +7707,12 @@ mod tests {
|
||||
let guard = acquire_bucket_metadata_transaction_read_lock_in(&ecstore.ctx, bucket)
|
||||
.await
|
||||
.expect("transaction read lock");
|
||||
let warm_bm = match sys
|
||||
let _ = sys
|
||||
.read_authoritative_metadata_from_disk_under_guard(bucket, &guard)
|
||||
.await
|
||||
.expect("warm cached read")
|
||||
{
|
||||
BucketMetadataAuthority::Authoritative(bm) => bm,
|
||||
_ => panic!("expected Authoritative metadata"),
|
||||
};
|
||||
.expect("warm cached read");
|
||||
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
@@ -1007,65 +1007,6 @@ 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>()
|
||||
@@ -1107,7 +1048,6 @@ fn apply_peer_capabilities_response(
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn apply_peer_capabilities_response_for_connection(
|
||||
audience: String,
|
||||
sent_state: PeerReplayStateSnapshot,
|
||||
@@ -1115,36 +1055,17 @@ 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
|
||||
&& (force_boot_epoch_update || sent_state.replay.boot_epoch == current_state.boot_epoch)
|
||||
&& sent_state.replay.boot_epoch == current_state.boot_epoch
|
||||
{
|
||||
next_state.boot_epoch = Some(response.boot_epoch);
|
||||
}
|
||||
|
||||
if force_boot_epoch_update || sent_state.replay.boot_epoch == current_state.boot_epoch {
|
||||
if sent_state.replay.boot_epoch == current_state.boot_epoch {
|
||||
let response_capability = replay_response
|
||||
.as_ref()
|
||||
.ok()
|
||||
@@ -1185,9 +1106,6 @@ fn apply_peer_capabilities_response_for_connection_inner(
|
||||
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);
|
||||
@@ -1215,10 +1133,7 @@ fn apply_peer_capabilities_response_for_connection_inner(
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
states.replay.insert(audience, next_state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1264,7 +1179,6 @@ 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>()
|
||||
@@ -1296,16 +1210,14 @@ where
|
||||
.expect("static msgpack capability must be a valid header value"),
|
||||
);
|
||||
}
|
||||
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()),
|
||||
)
|
||||
{
|
||||
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()),
|
||||
) {
|
||||
match rpc_background_admission(request.headers()).and_then(|background| {
|
||||
gen_tonic_replay_scope_headers_with_admission(
|
||||
audience,
|
||||
@@ -1393,13 +1305,12 @@ where
|
||||
} else {
|
||||
None
|
||||
};
|
||||
apply_peer_capabilities_response_for_connection_inner(
|
||||
apply_peer_capabilities_response_for_connection(
|
||||
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,42 +15,9 @@
|
||||
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,
|
||||
}
|
||||
@@ -97,10 +64,9 @@ fn fallback_request_id() -> String {
|
||||
format!("req-{}", &uuid::Uuid::new_v4().to_string()[..8])
|
||||
}
|
||||
|
||||
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}")))
|
||||
fn propagated_request_id() -> String {
|
||||
current_trace_id()
|
||||
.map(|trace_id| format!("trace-{trace_id}"))
|
||||
.unwrap_or_else(fallback_request_id)
|
||||
}
|
||||
|
||||
@@ -185,23 +151,6 @@ 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,13 +12,11 @@
|
||||
// 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, 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,
|
||||
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,
|
||||
};
|
||||
use crate::disk::error::{Error, Result};
|
||||
use crate::disk::{FileReader, FileWriter};
|
||||
@@ -47,7 +45,7 @@ use rustfs_rio::{
|
||||
ChunkReader, ChunkReaderBox, HttpChunkReader, HttpReader, HttpWriter, HttpWriterMemoryReservation, HttpWriterMemoryReserver,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
@@ -56,7 +54,6 @@ 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(
|
||||
@@ -76,7 +73,6 @@ 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";
|
||||
|
||||
@@ -103,11 +99,7 @@ fn unsupported_transport_message(transport: &str) -> String {
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum PutFileCapabilityState {
|
||||
LegacyUntil(Instant),
|
||||
V1 {
|
||||
server_epoch: Uuid,
|
||||
peer_boot_epoch: Option<Uuid>,
|
||||
revalidate_after: Instant,
|
||||
},
|
||||
V1 { server_epoch: Uuid, revalidate_after: Instant },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -130,7 +122,6 @@ 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>>,
|
||||
}
|
||||
|
||||
@@ -154,119 +145,19 @@ 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 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()));
|
||||
// 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()));
|
||||
|
||||
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() {
|
||||
return;
|
||||
if !key.is_empty() && !STREAM_AUTH_PINNED_ENDPOINTS.read().contains(&key) {
|
||||
STREAM_AUTH_PINNED_ENDPOINTS.write().insert(key);
|
||||
}
|
||||
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> {
|
||||
@@ -276,17 +167,7 @@ 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 {
|
||||
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);
|
||||
}
|
||||
if strict || STREAM_AUTH_PINNED_ENDPOINTS.read().contains(&key) {
|
||||
return Err(Error::other("internode stream response auth missing or downgraded"));
|
||||
}
|
||||
Ok(false)
|
||||
@@ -294,40 +175,6 @@ 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,
|
||||
@@ -575,7 +422,6 @@ 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,
|
||||
@@ -779,9 +625,7 @@ 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_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -803,9 +647,7 @@ 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_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -826,9 +668,7 @@ 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_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
Ok(Some(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -855,9 +695,7 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
request.stall_timeout,
|
||||
)
|
||||
.await?;
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
Ok(Some(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -897,9 +735,7 @@ 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_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -1250,14 +1086,9 @@ 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,
|
||||
pinned_boot_epoch,
|
||||
v1_was_pinned: matches!(state.cached, Some(PutFileCapabilityState::V1 { .. })),
|
||||
outcome: Arc::new(OnceCell::new()),
|
||||
};
|
||||
state.in_flight = Some(flight.clone());
|
||||
@@ -1270,33 +1101,6 @@ 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
|
||||
@@ -1311,13 +1115,11 @@ 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 || rollback_verified => {
|
||||
Ok(None) if !flight.v1_was_pinned => {
|
||||
state.cached = Some(PutFileCapabilityState::LegacyUntil(Instant::now() + PUT_FILE_LEGACY_CAPABILITY_TTL));
|
||||
state.rejected_server_epoch = None;
|
||||
}
|
||||
Ok(None) | Err(_) => {}
|
||||
}
|
||||
@@ -1327,9 +1129,7 @@ where
|
||||
|
||||
match outcome {
|
||||
Ok(Some(server_epoch)) => Ok(Some(*server_epoch)),
|
||||
Ok(None) if flight.v1_was_pinned && !rollback_verified => {
|
||||
Err(Error::other("remote put_file capability downgrade rejected"))
|
||||
}
|
||||
Ok(None) if flight.v1_was_pinned => Err(Error::other("remote put_file capability downgrade rejected")),
|
||||
Ok(None) => Ok(None),
|
||||
Err(failure) => Err(failure.to_error()),
|
||||
}
|
||||
@@ -1694,7 +1494,6 @@ 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 {
|
||||
@@ -2676,7 +2475,6 @@ 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!(
|
||||
@@ -2696,7 +2494,6 @@ 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!(
|
||||
@@ -2980,7 +2777,6 @@ 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;
|
||||
@@ -3653,7 +3449,6 @@ 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);
|
||||
@@ -3727,112 +3522,4 @@ 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,7 +33,6 @@ 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,8 +63,6 @@ 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
|
||||
@@ -430,7 +428,6 @@ async fn send_segment(
|
||||
request: WriteStreamRequest,
|
||||
buffers: Vec<(LentBuffer, usize)>,
|
||||
append: bool,
|
||||
offset: Option<u64>,
|
||||
last: bool,
|
||||
timeout: Duration,
|
||||
) -> io::Result<()> {
|
||||
@@ -446,7 +443,7 @@ async fn send_segment(
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let mut url = format!(
|
||||
let 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),
|
||||
@@ -458,9 +455,6 @@ 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,
|
||||
@@ -515,7 +509,6 @@ struct WriterState {
|
||||
reserving: Option<ReserveFuture>,
|
||||
sending: Option<SegmentFuture>,
|
||||
segments_sent: usize,
|
||||
bytes_sent: u64,
|
||||
shut_down: bool,
|
||||
}
|
||||
|
||||
@@ -523,16 +516,12 @@ 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,
|
||||
)));
|
||||
@@ -606,26 +595,6 @@ 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);
|
||||
@@ -654,7 +623,6 @@ impl NixlFileWriter {
|
||||
reserving: None,
|
||||
sending: None,
|
||||
segments_sent: 0,
|
||||
bytes_sent: 0,
|
||||
shut_down: false,
|
||||
}),
|
||||
}
|
||||
@@ -889,14 +857,6 @@ 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)
|
||||
@@ -1008,23 +968,4 @@ 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,87 +1463,6 @@ 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()));
|
||||
|
||||
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;
|
||||
@@ -2435,7 +2354,6 @@ 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,
|
||||
@@ -2462,22 +2380,14 @@ 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 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")
|
||||
};
|
||||
let became_online = 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"
|
||||
);
|
||||
@@ -2501,31 +2411,6 @@ 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(&self) {
|
||||
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
|
||||
}
|
||||
|
||||
/// 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;
|
||||
};
|
||||
clear_host_timeout_degradation(&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 {
|
||||
@@ -2643,9 +2528,6 @@ 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");
|
||||
return Err(err);
|
||||
@@ -2722,14 +2604,6 @@ 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)
|
||||
@@ -2741,7 +2615,6 @@ impl RemoteDisk {
|
||||
if timeout_duration == Duration::ZERO {
|
||||
let operation_result = operation().await;
|
||||
if operation_result.is_ok() {
|
||||
clear_host_timeout_degradation(&self.addr);
|
||||
self.health.record_operation_success(&self.endpoint, "operation_success");
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
|
||||
}
|
||||
@@ -2757,7 +2630,6 @@ impl RemoteDisk {
|
||||
Ok(operation_result) => {
|
||||
// Log success; the waiting guard balances every exit path.
|
||||
if operation_result.is_ok() {
|
||||
clear_host_timeout_degradation(&self.addr);
|
||||
self.health.record_operation_success(&self.endpoint, "operation_success");
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
|
||||
}
|
||||
@@ -2768,7 +2640,6 @@ impl RemoteDisk {
|
||||
Err(_) => {
|
||||
self.record_timeout(op, timeout_duration);
|
||||
if failure_health_action == FailureHealthAction::MarkFailure {
|
||||
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
|
||||
self.mark_faulty_and_evict("operation_timeout").await;
|
||||
}
|
||||
Err(DiskError::Timeout)
|
||||
@@ -4239,8 +4110,7 @@ impl DiskAPI for RemoteDisk {
|
||||
"Remote disk RPC started"
|
||||
);
|
||||
|
||||
self.execute_with_timeout_for_op(
|
||||
"stat_volume",
|
||||
self.execute_with_timeout(
|
||||
|| async {
|
||||
let mut client = self.get_client().await?;
|
||||
let request = Request::new(StatVolumeRequest {
|
||||
@@ -15003,35 +14873,4 @@ 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1472,23 +1472,6 @@ 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();
|
||||
@@ -2499,22 +2482,17 @@ impl LocalDiskWrapper {
|
||||
&& self.disk.has_clean_active_multipart_source(upload_or_part_path, part_path)
|
||||
}
|
||||
|
||||
pub(crate) fn check_active_multipart_source_matching_and_clean_part(
|
||||
pub(crate) fn has_active_multipart_source_matching(
|
||||
&self,
|
||||
upload_path: &str,
|
||||
expected_data_dir: Option<uuid::Uuid>,
|
||||
expected_mod_time: Option<::time::OffsetDateTime>,
|
||||
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,
|
||||
)
|
||||
) -> bool {
|
||||
!self.health.is_faulty()
|
||||
&& !self.retired.is_cancelled()
|
||||
&& self
|
||||
.disk
|
||||
.has_active_multipart_source_matching(upload_path, expected_data_dir, expected_mod_time)
|
||||
}
|
||||
|
||||
pub(crate) async fn try_publish_prepared_delete_local(
|
||||
|
||||
@@ -62,15 +62,14 @@ 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,
|
||||
PART_TRANSACTION_NEW_META, PART_TRANSACTION_OLD_META, PART_TRANSACTION_ROLLBACK, PartTransactionAction, RUSTFS_META_BUCKET,
|
||||
FORMAT_CONFIG_FILE, FileInfoVersions, FileReader, FileWriter, GuardedFileInfoVersions, OldCurrentSize, 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,
|
||||
part_transaction_path, validate_delete_recovery_options, validate_format_control_path,
|
||||
validate_delete_recovery_options, validate_format_control_path,
|
||||
};
|
||||
use crate::erasure::coding::{self, bitrot_verify};
|
||||
use crate::runtime::instance::InstanceContext;
|
||||
@@ -227,7 +226,6 @@ 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 {
|
||||
@@ -282,19 +280,9 @@ 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
|
||||
}
|
||||
@@ -1484,22 +1472,12 @@ 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 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;
|
||||
let has_external_parts = !file_info.inline_data() && file_info.data.is_none() && file_info.size > 0;
|
||||
if has_external_parts
|
||||
&& let Some(data_dir) = file_info.data_dir
|
||||
&& !data_dir.is_nil()
|
||||
{
|
||||
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 src_data = format!("{src_dir}/{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)?;
|
||||
@@ -1541,62 +1519,13 @@ impl DiskAPI for DstSimDisk {
|
||||
|
||||
self.fsync_parent_chain(&dst_dir).await?;
|
||||
let _ = self.sim.remove_file(&bkp_meta).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
|
||||
};
|
||||
let _ = self.sim.remove_dir_all(&src_dir).await;
|
||||
|
||||
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()
|
||||
})
|
||||
}
|
||||
@@ -1703,149 +1632,20 @@ 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)?;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.sim.fsync_file(&src).await.map_err(map_sim_err)?;
|
||||
self.sim.rename(&src, &dst).await.map_err(map_sim_err)?;
|
||||
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?;
|
||||
|
||||
@@ -426,7 +426,6 @@ 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>,
|
||||
@@ -448,29 +447,6 @@ 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,7 +375,6 @@ 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,
|
||||
@@ -389,25 +388,6 @@ 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,
|
||||
@@ -1522,18 +1502,6 @@ 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())
|
||||
@@ -1617,16 +1585,6 @@ 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"),
|
||||
|
||||
@@ -493,23 +493,17 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn check_active_multipart_source_matching_and_clean_part(
|
||||
pub(crate) fn has_active_multipart_source_matching(
|
||||
&self,
|
||||
upload_path: &str,
|
||||
expected_data_dir: Option<Uuid>,
|
||||
expected_mod_time: Option<time::OffsetDateTime>,
|
||||
part_number: usize,
|
||||
) -> (bool, bool) {
|
||||
) -> bool {
|
||||
match self {
|
||||
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),
|
||||
Self::Local(disk) => disk.has_active_multipart_source_matching(upload_path, expected_data_dir, expected_mod_time),
|
||||
Self::Remote(_) => false,
|
||||
#[cfg(feature = "dst")]
|
||||
Self::Sim(_) => (false, false),
|
||||
Self::Sim(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1758,7 +1752,7 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_faulty(&self) -> bool {
|
||||
pub(crate) fn is_faulty(&self) -> bool {
|
||||
match self {
|
||||
Disk::Local(local_disk) => local_disk.is_faulty(),
|
||||
Disk::Remote(remote_disk) => remote_disk.is_faulty(),
|
||||
@@ -1767,15 +1761,6 @@ 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,7 +186,6 @@ pub(crate) fn bind_multipart_proof_snapshot(
|
||||
if sim.disk_index() != slot {
|
||||
return Err(DiskError::InconsistentDisk);
|
||||
}
|
||||
sim.bind_multipart_proof_authority(authority)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,18 +302,6 @@ 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());
|
||||
@@ -328,71 +316,6 @@ 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();
|
||||
@@ -427,64 +350,21 @@ impl PreparedIntegrity {
|
||||
}
|
||||
Spool::File(file) => file,
|
||||
};
|
||||
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);
|
||||
}
|
||||
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),
|
||||
}
|
||||
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<_>>()
|
||||
};
|
||||
}))
|
||||
.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))?;
|
||||
@@ -532,8 +412,9 @@ impl PreparedIntegrity {
|
||||
}
|
||||
}
|
||||
|
||||
/// A shared, two-stripe cache coalesces the N readers' external proof fetches.
|
||||
/// A missing local index may use any authenticated replica.
|
||||
/// 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.
|
||||
pub(crate) struct PartProofReader {
|
||||
pub(crate) part: PartIntegrity,
|
||||
sources: Vec<(DiskStore, String)>,
|
||||
@@ -548,33 +429,32 @@ struct ProofCache {
|
||||
preferred: usize,
|
||||
}
|
||||
|
||||
// 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;
|
||||
type VerifiedStripeKey = (uuid::Uuid, [u8; 32], u32);
|
||||
|
||||
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.clone(), stripe)).cloned()
|
||||
VERIFIED_STRIPE_RECORDS
|
||||
.lock()
|
||||
.get(&(part.generation, part.root, 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().cloned()
|
||||
&& let Some(evict_key) = map.keys().next().copied()
|
||||
{
|
||||
map.remove(&evict_key);
|
||||
}
|
||||
map.insert(key, record);
|
||||
map.insert((part.generation, part.root, stripe), record);
|
||||
}
|
||||
|
||||
pub(crate) fn invalidate_verified_stripe_records(generation: uuid::Uuid) {
|
||||
VERIFIED_STRIPE_RECORDS
|
||||
.lock()
|
||||
.retain(|(part, _), _| part.generation != generation);
|
||||
.retain(|(stored_gen, _, _), _| *stored_gen != generation);
|
||||
}
|
||||
|
||||
impl PartProofReader {
|
||||
@@ -654,31 +534,67 @@ impl PartProofReader {
|
||||
|
||||
pub(crate) async fn record(&self, stripe: u32) -> io::Result<Bytes> {
|
||||
let offset = self.part.record_offset(stripe).map_err(|_| corrupt())?;
|
||||
let size = self.part.record_size();
|
||||
// Inline records are immutable and authenticated at construction.
|
||||
if let Some(inline) = &self.inline {
|
||||
return Ok(inline.slice(offset..offset + size));
|
||||
if let Some(bytes) = get_verified_stripe_record(&self.part, stripe) {
|
||||
return Ok(bytes);
|
||||
}
|
||||
let mut cached = self.cached.lock().await;
|
||||
if let Some((_, bytes)) = cached.records.iter().find(|(number, _)| *number == stripe) {
|
||||
return Ok(bytes.clone());
|
||||
}
|
||||
let share = self.part.stripes <= MAX_SHARED_CACHE_STRIPES;
|
||||
let shared = if share {
|
||||
get_verified_stripe_record(&self.part, stripe)
|
||||
let size = self.part.record_size();
|
||||
let record = if let Some(inline) = &self.inline {
|
||||
inline.slice(offset..offset + size)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let record = if let Some(record) = shared {
|
||||
record
|
||||
} else {
|
||||
let (replica, record) = self.read_verified_record(stripe, offset, size, cached.preferred).await?;
|
||||
cached.preferred = replica;
|
||||
if share {
|
||||
put_verified_stripe_record(&self.part, stripe, record.clone());
|
||||
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());
|
||||
}
|
||||
record
|
||||
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
|
||||
};
|
||||
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();
|
||||
}
|
||||
@@ -686,49 +602,6 @@ impl PartProofReader {
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
async fn read_verified_record(
|
||||
&self,
|
||||
stripe: u32,
|
||||
offset: usize,
|
||||
size: usize,
|
||||
preferred: usize,
|
||||
) -> io::Result<(usize, Bytes)> {
|
||||
if self.sources.is_empty() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let read = |index: usize| async move {
|
||||
let (disk, path) = &self.sources[index];
|
||||
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((index, Bytes::from(bytes)))
|
||||
})
|
||||
.await
|
||||
};
|
||||
let mut pending = FuturesUnordered::new();
|
||||
pending.push(read(preferred));
|
||||
tokio::select! {
|
||||
result = pending.next() => {
|
||||
if let Some(Ok(Ok(record))) = result {
|
||||
return Ok(record);
|
||||
}
|
||||
}
|
||||
() = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}
|
||||
}
|
||||
pending.extend((0..self.sources.len()).filter(|&index| index != preferred).map(read));
|
||||
while let Some(result) = pending.next().await {
|
||||
if let Ok(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
|
||||
@@ -1125,36 +998,36 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn verified_stripe_record_cache_requires_exact_part_descriptor_and_verifies_payload() {
|
||||
async fn verified_stripe_record_cache_serves_verified_record_and_still_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");
|
||||
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 prepared = builder.finish(8).await.expect("index");
|
||||
let inline_bytes = prepared.inline_bytes().expect("inline 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 mut shortened = part.clone();
|
||||
shortened.size = 8;
|
||||
shortened.stripes = 1;
|
||||
let mismatched_reader =
|
||||
PartProofReader::new(shortened, &[], &[], "bucket", "object").expect("the altered descriptor is structurally valid");
|
||||
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");
|
||||
assert!(
|
||||
mismatched_reader.verify(0, 0, shards[0]).await.is_err(),
|
||||
"a matching generation and root must not admit a shortened part"
|
||||
get_verified_stripe_record(&part, 0).is_some(),
|
||||
"small verified stripe record should populate the verified stripe cache"
|
||||
);
|
||||
|
||||
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object").expect("matching descriptor");
|
||||
let cached_reader = Arc::new(PartProofReader {
|
||||
part,
|
||||
sources: Vec::new(),
|
||||
volume: "bucket".to_owned(),
|
||||
inline: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
});
|
||||
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"
|
||||
|
||||
@@ -1130,7 +1130,6 @@ impl std::fmt::Debug for GetObjectSinkSegments {
|
||||
struct GetObjectSinkInner {
|
||||
writer: Option<GetObjectSinkWriter>,
|
||||
segments: Option<GetObjectSinkSegments>,
|
||||
max_bytes: Option<u64>,
|
||||
taken: bool,
|
||||
}
|
||||
|
||||
@@ -1149,7 +1148,6 @@ impl GetObjectSink {
|
||||
inner: Arc::new(std::sync::Mutex::new(GetObjectSinkInner {
|
||||
writer: Some(writer),
|
||||
segments: None,
|
||||
max_bytes: None,
|
||||
taken: false,
|
||||
})),
|
||||
}
|
||||
@@ -1161,24 +1159,11 @@ 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())
|
||||
}
|
||||
|
||||
@@ -4421,60 +4421,19 @@ 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 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,
|
||||
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,
|
||||
}
|
||||
} else {
|
||||
futures::StreamExt::next(&mut pending).await
|
||||
};
|
||||
let Some((idx, lease)) = next else {
|
||||
break;
|
||||
};
|
||||
if lease.is_some() {
|
||||
acquired = acquired.saturating_add(1);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}))
|
||||
.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;
|
||||
@@ -5622,22 +5581,16 @@ impl SetDisks {
|
||||
let plan = producers.plan();
|
||||
let mut results = Vec::with_capacity(disk_count);
|
||||
let mut successful = 0;
|
||||
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(_))) {
|
||||
let mut accept = |outcome: SlotRenameOutcome| {
|
||||
if let Some(tx) = dispatch_deadline_tx.as_ref()
|
||||
&& matches!(&outcome.completion, Ok(Ok(_)))
|
||||
{
|
||||
successful += 1;
|
||||
if let Some(tx) = dispatch_deadline_tx.as_ref()
|
||||
&& successful == write_quorum
|
||||
{
|
||||
if 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.
|
||||
@@ -5660,77 +5613,25 @@ impl SetDisks {
|
||||
tasks.spawn(crate::disk::with_detached_disk_io_context(producer));
|
||||
}
|
||||
drop((producers, resource_unit, successful_completion_rank));
|
||||
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 };
|
||||
while let Some(joined) = tasks.join_next().await {
|
||||
// A missing outcome still has the original conservative rollback state.
|
||||
if let Ok(outcome) = joined
|
||||
&& let Some(deadline) = accept(outcome)
|
||||
{
|
||||
post_quorum_completion_deadline = Some(deadline);
|
||||
if let Ok(outcome) = joined {
|
||||
accept(outcome);
|
||||
}
|
||||
}
|
||||
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);
|
||||
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 let Some(outcome) = outcome_rx.recv().await {
|
||||
accept(outcome);
|
||||
}
|
||||
while tasks.join_next().await.is_some() {}
|
||||
}
|
||||
#[cfg(test)]
|
||||
rollback_fault_injection::after_fanout(&fanout_paths.dst_object);
|
||||
(results, fanout_file_infos, post_quorum_detached)
|
||||
(results, fanout_file_infos)
|
||||
};
|
||||
let fanout_future = crate::disk::with_detached_disk_io_context(fanout_future);
|
||||
let fanout = if protected_multipart {
|
||||
@@ -5760,7 +5661,7 @@ impl SetDisks {
|
||||
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_QUORUM_WAIT,
|
||||
quorum_wait_started,
|
||||
);
|
||||
let (results, file_infos, post_quorum_detached) = match fanout_result {
|
||||
let (results, file_infos) = match fanout_result {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
drop(disk_snapshot);
|
||||
@@ -5848,13 +5749,6 @@ 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();
|
||||
@@ -6741,7 +6635,6 @@ 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(
|
||||
@@ -6754,43 +6647,13 @@ 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);
|
||||
|
||||
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 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);
|
||||
@@ -11149,82 +11012,6 @@ 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
|
||||
@@ -12909,36 +12696,6 @@ 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;
|
||||
@@ -12961,7 +12718,51 @@ mod tests {
|
||||
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
|
||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
|
||||
],
|
||||
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)),
|
||||
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));
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -13142,7 +12943,51 @@ mod tests {
|
||||
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
|
||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
|
||||
],
|
||||
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, &object, bounded_spare_disk_index(bucket, &object, 2, 2)),
|
||||
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));
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -13163,7 +13008,46 @@ mod tests {
|
||||
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", Some("true")),
|
||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", Some("true")),
|
||||
],
|
||||
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2),
|
||||
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));
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -13184,7 +13068,48 @@ mod tests {
|
||||
("RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE", None::<&str>),
|
||||
("RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT", None::<&str>),
|
||||
],
|
||||
assert_metadata_fanout_bounds_a_paused_disk(&disks, bucket, object, 2),
|
||||
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));
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
|
||||
@@ -724,17 +724,6 @@ 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,
|
||||
@@ -1036,7 +1025,7 @@ impl SetDisks {
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
#[allow(clippy::redundant_locals)]
|
||||
let diagnostic_context = diagnostic_context;
|
||||
AbortOnDropJoinHandle(tokio::spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
AbortOnDropJoinHandle(tokio::spawn(async move {
|
||||
let read = async move {
|
||||
let response_start = observe.then(Instant::now);
|
||||
let result = if let Some(disk) = disk {
|
||||
@@ -1064,137 +1053,34 @@ impl SetDisks {
|
||||
.await;
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
read.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};
|
||||
// Wait for all futures to complete
|
||||
let results = join_all(futures).await;
|
||||
|
||||
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,
|
||||
}
|
||||
} 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));
|
||||
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));
|
||||
}
|
||||
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));
|
||||
slots[index].result = Some(Ok(file_info));
|
||||
}
|
||||
}
|
||||
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();
|
||||
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::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));
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Unexpected, Duration::ZERO));
|
||||
}
|
||||
slots[index].result = Some(Err(DiskError::Unexpected));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1263,8 +1149,6 @@ 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(
|
||||
@@ -1283,7 +1167,7 @@ impl SetDisks {
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
#[allow(clippy::redundant_locals)]
|
||||
let diagnostic_context = diagnostic_context;
|
||||
let task = join_set.spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
let task = join_set.spawn(async move {
|
||||
let read = async move {
|
||||
let response_start = stage_metrics_enabled.then(Instant::now);
|
||||
let result = if let Some(disk) = disk {
|
||||
@@ -1319,7 +1203,7 @@ impl SetDisks {
|
||||
.await;
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
read.await
|
||||
}));
|
||||
});
|
||||
task_ids[index] = Some(task.id());
|
||||
};
|
||||
|
||||
@@ -1340,130 +1224,37 @@ 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 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 {
|
||||
let result = if let Some(deadline) = single_pending_hedge_deadline.take() {
|
||||
tokio::select! {
|
||||
result = join_set.join_next_with_id() => result,
|
||||
_ = async {
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
#[cfg(test)]
|
||||
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;
|
||||
}
|
||||
rename_fanout_barrier::checkpoint(
|
||||
object.as_ref(),
|
||||
0,
|
||||
rename_fanout_barrier::PHASE_NON_INLINE_HEDGE_TIMER,
|
||||
)
|
||||
.await;
|
||||
} => {
|
||||
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;
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -1679,49 +1470,7 @@ impl SetDisks {
|
||||
&& accumulator.can_still_reach_early_stop_with_pending(join_set.len())
|
||||
&& next_fanout_index < disks.len()
|
||||
{
|
||||
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;
|
||||
single_pending_hedge_deadline = Some(tokio::time::Instant::now() + NON_INLINE_SINGLE_PENDING_HEDGE_DELAY);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4434,8 +4434,7 @@ fn record_lock_acquire(bucket: &str, object: &str, lock_type: &str) -> String {
|
||||
return lock_id;
|
||||
}
|
||||
|
||||
let request_id =
|
||||
crate::cluster::rpc::context_propagation::current_request_id_or_fallback(|| format!("get-{}-{}", bucket, object));
|
||||
let request_id = format!("get-{}-{}", bucket, object);
|
||||
let resource = format!("{}/{}", bucket, object);
|
||||
|
||||
// Log with structured fields for analysis
|
||||
@@ -4457,8 +4456,7 @@ fn record_lock_release(bucket: &str, object: &str, lock_id: &str, lock_type: &st
|
||||
return;
|
||||
}
|
||||
|
||||
let request_id =
|
||||
crate::cluster::rpc::context_propagation::current_request_id_or_fallback(|| format!("get-{}-{}", bucket, object));
|
||||
let request_id = format!("get-{}-{}", bucket, object);
|
||||
|
||||
debug!(
|
||||
request_id = %request_id,
|
||||
|
||||
@@ -114,62 +114,31 @@ 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 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 probes = disks.into_iter().map(|disk| stat_bucket_volume(disk, bucket));
|
||||
let results = join_all(probes).await;
|
||||
let mut first_info = None;
|
||||
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);
|
||||
let mut errs = Vec::with_capacity(results.len());
|
||||
for result in results {
|
||||
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 {
|
||||
BucketInfoQuorum::Read => reduce_read_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, required),
|
||||
// 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::Write | BucketInfoQuorum::HealCandidates => {
|
||||
reduce_write_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, required)
|
||||
reduce_write_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, disk_count / 2 + 1)
|
||||
}
|
||||
};
|
||||
if let Some(err) = error {
|
||||
|
||||
@@ -3769,12 +3769,15 @@ impl SetDisks {
|
||||
proof: AbsenceProofRequest<'_>,
|
||||
) -> Result<(HealResultItem, Option<Error>)> {
|
||||
*absence = None;
|
||||
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 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.
|
||||
let can_commit = || proof.retirement.is_none_or(|context| !context.lifecycle_guard.is_lock_lost());
|
||||
let mut read_opts = *opts;
|
||||
loop {
|
||||
@@ -5978,127 +5981,6 @@ 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,
|
||||
@@ -11827,51 +11709,32 @@ mod shard_identity_tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_heal_rejects_complete_donor_shards_ec12_4() {
|
||||
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 (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(16, 0, 4).await;
|
||||
let bucket = "donor-shard-identity";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("create fixture bucket");
|
||||
}
|
||||
let expected = vec![0x5a; size];
|
||||
let expected = vec![0x5a; 5 * 1024 * 1024 + 123];
|
||||
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 cases.iter().enumerate() {
|
||||
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()
|
||||
{
|
||||
let target = format!("target-{case}");
|
||||
let donor = format!("donor-{case}");
|
||||
set.put_object(bucket, &target, &mut PutObjReader::from_vec(expected.clone()), &options)
|
||||
@@ -11894,10 +11757,7 @@ mod shard_identity_tests {
|
||||
.expect("donor metadata"),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
(target_meta[0].erasure.data_blocks, target_meta[0].erasure.parity_blocks),
|
||||
(data_shards, parity_shards)
|
||||
);
|
||||
assert_eq!((target_meta[0].erasure.data_blocks, target_meta[0].erasure.parity_blocks), (12, 4));
|
||||
let mut before = Vec::new();
|
||||
let mut paths = Vec::new();
|
||||
let mut meta_before = Vec::new();
|
||||
@@ -11910,7 +11770,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)
|
||||
@@ -11948,37 +11808,18 @@ mod shard_identity_tests {
|
||||
}
|
||||
}
|
||||
let version = target_meta[0].version_id.expect("versioned fixture").to_string();
|
||||
if coding_indexes.len() <= parity_shards {
|
||||
let explicit_version = ObjectOptions {
|
||||
version_id: Some(version.clone()),
|
||||
..options.clone()
|
||||
};
|
||||
let range_start = size / 5 + 17;
|
||||
let range_end = 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");
|
||||
}
|
||||
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");
|
||||
}
|
||||
let heal = set
|
||||
.heal_object(
|
||||
@@ -11992,7 +11833,7 @@ mod shard_identity_tests {
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if coding_indexes.len() <= parity_shards {
|
||||
if coding_indexes.len() <= 4 {
|
||||
let (result, error) = heal.expect("recoverable donor mismatch");
|
||||
assert!(error.is_none(), "{error:?}");
|
||||
assert_eq!(
|
||||
@@ -12007,10 +11848,42 @@ 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()),
|
||||
"read quorum minus one authoritative sources must not produce a successful heal"
|
||||
"eleven authoritative sources must not produce a successful heal"
|
||||
);
|
||||
let read = set
|
||||
.get_object_reader(bucket, &target, None, Default::default(), &options)
|
||||
|
||||
@@ -1054,23 +1054,6 @@ 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
|
||||
@@ -3747,39 +3730,15 @@ 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, 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 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 commit_fi = if fast_commit_head_verified {
|
||||
fi.clone()
|
||||
} else {
|
||||
@@ -3886,7 +3845,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_with_clean_hint(
|
||||
.rename_part(
|
||||
&shuffle_disks,
|
||||
RUSTFS_META_TMP_BUCKET,
|
||||
&tmp_part_path,
|
||||
@@ -3901,7 +3860,6 @@ 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);
|
||||
@@ -5818,15 +5776,6 @@ 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;
|
||||
@@ -6029,15 +5978,6 @@ 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();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1926,7 +1926,7 @@ impl SetDisks {
|
||||
);
|
||||
}
|
||||
}
|
||||
let (mut reader_setup, mut reader_setup_elapsed) = match setup_result {
|
||||
let (reader_setup, 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.clone(),
|
||||
sync_spec,
|
||||
erasure.shard_size(),
|
||||
erasure.data_shards,
|
||||
erasure.parity_shards,
|
||||
@@ -1949,55 +1949,6 @@ 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).
|
||||
@@ -2022,7 +1973,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(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
let handle = tokio::task::spawn(async move {
|
||||
setup_multipart_part_readers(
|
||||
&files,
|
||||
&disks,
|
||||
@@ -2040,7 +1991,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());
|
||||
@@ -2052,17 +2003,13 @@ 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,
|
||||
@@ -2090,10 +2037,8 @@ 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,
|
||||
@@ -2120,10 +2065,8 @@ 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,
|
||||
@@ -2921,7 +2864,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(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
tokio::task::spawn(async move {
|
||||
SetDisks::build_codec_streaming_part_reader(
|
||||
&ctx.bucket,
|
||||
&ctx.object,
|
||||
@@ -2949,7 +2892,7 @@ impl SetDisks {
|
||||
ctx.metrics_path,
|
||||
)
|
||||
.await
|
||||
}))
|
||||
})
|
||||
});
|
||||
|
||||
Ok(GetCodecStreamingReaderBuildOutcome::Reader(Box::new(
|
||||
@@ -3267,7 +3210,6 @@ 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,
|
||||
|
||||
@@ -326,18 +326,7 @@ impl ECStore {
|
||||
));
|
||||
}
|
||||
// Lock order: bucket lifecycle, then bucket/object and capacity locks used by healing.
|
||||
// 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 fence = self.acquire_bucket_incarnation_fence(bucket, expected).await?;
|
||||
let scope = Arc::new(BucketHealScope {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: expected,
|
||||
|
||||
@@ -1022,13 +1022,6 @@ impl PreparedGetObjectReader {
|
||||
self
|
||||
}
|
||||
|
||||
/// Attaches or clears the one-shot body sink before constructing the reader.
|
||||
#[must_use]
|
||||
pub fn with_sink(mut self, sink: Option<crate::object_api::GetObjectSink>) -> Self {
|
||||
self.opts.get_object_sink = sink;
|
||||
self
|
||||
}
|
||||
|
||||
/// Constructs the body reader while retaining the metadata snapshot's read
|
||||
/// lock, then transfers that lock to the returned stream as usual. The
|
||||
/// staged caller already performed the authoritative app-layer cache probe,
|
||||
|
||||
@@ -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, 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,
|
||||
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,
|
||||
};
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
@@ -742,284 +742,3 @@ 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,9 +106,7 @@ pub(crate) mod local_drive_retirement {
|
||||
|
||||
#[cfg(feature = "dst")]
|
||||
pub(crate) mod dst_production_ecstore {
|
||||
pub(crate) use super::storage_contracts::{
|
||||
BucketOperations, CompletePart, HealOperations, MakeBucketOptions, MultipartOperations, ObjectIO, ObjectOperations,
|
||||
};
|
||||
pub(crate) use super::storage_contracts::{BucketOperations, HealOperations, MakeBucketOptions, ObjectIO, ObjectOperations};
|
||||
pub(crate) use super::{DiskAPI, Error, ObjectOptions, PutObjReader, STORAGE_FORMAT_FILE};
|
||||
pub(crate) use rustfs_ecstore::api::{
|
||||
disk::ReadOptions,
|
||||
|
||||
@@ -2275,9 +2275,7 @@ impl MetaObjectV1 {
|
||||
|
||||
rmp::encode::write_str(wr, "Meta")?;
|
||||
rmp::encode::write_map_len(wr, self.meta.len() as u32)?;
|
||||
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 {
|
||||
for (k, v) in &self.meta {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -2592,9 +2590,7 @@ 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)?;
|
||||
let mut sorted_checksums: Vec<(&String, &String)> = checksums.iter().collect();
|
||||
sorted_checksums.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_checksums {
|
||||
for (k, v) in checksums {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -2805,29 +2801,25 @@ 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; sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
// MetaSys (write nil when empty)
|
||||
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)?;
|
||||
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 {
|
||||
for (k, v) in &self.meta_sys {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_bin(wr, v)?;
|
||||
}
|
||||
}
|
||||
|
||||
// MetaUsr (write nil when empty; sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
// MetaUsr (write nil when empty)
|
||||
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)?;
|
||||
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 {
|
||||
for (k, v) in &self.meta_user {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -3899,15 +3891,13 @@ impl MetaDeleteMarker {
|
||||
let nanos = self.mod_time.unwrap_or(OffsetDateTime::UNIX_EPOCH).unix_timestamp_nanos();
|
||||
rmp::encode::write_sint(wr, nanos as i64)?;
|
||||
|
||||
// MetaSys (sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
// MetaSys
|
||||
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)?;
|
||||
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 {
|
||||
for (k, v) in &self.meta_sys {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_bin(wr, v)?;
|
||||
}
|
||||
@@ -7059,80 +7049,4 @@ 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -539,7 +539,7 @@ impl PriorityHealQueue {
|
||||
|
||||
let chosen_index = first_runnable.filter(|index| {
|
||||
let item = &items[*index];
|
||||
matches!(item.priority, HealPriority::Normal | HealPriority::High)
|
||||
item.priority == HealPriority::Normal
|
||||
&& 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)
|
||||
&& matches!(request.priority, HealPriority::Normal | HealPriority::High)
|
||||
&& request.priority == HealPriority::Normal
|
||||
{
|
||||
self.mrf_normal_dispatches_since_best_effort = self.mrf_normal_dispatches_since_best_effort.saturating_add(1);
|
||||
}
|
||||
|
||||
@@ -274,12 +274,6 @@ 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 {
|
||||
|
||||
@@ -2580,48 +2580,6 @@ 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();
|
||||
|
||||
@@ -4,9 +4,7 @@
|
||||
//! 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;
|
||||
@@ -14,28 +12,6 @@ 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")]
|
||||
@@ -52,12 +28,6 @@ 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)]
|
||||
@@ -77,15 +47,11 @@ pub fn lifecycle_summary() -> Result<MrfLifecycleSummary, MrfLifecycleControlErr
|
||||
if GLOBAL_MRF_LIFECYCLE_SENDER.get().is_none_or(mpsc::Sender::is_closed) {
|
||||
return Err(MrfLifecycleControlError::Unavailable);
|
||||
}
|
||||
let mut summary = SUMMARY
|
||||
SUMMARY
|
||||
.read()
|
||||
.map_err(|_| MrfLifecycleControlError::Unavailable)?
|
||||
.clone()
|
||||
.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)
|
||||
.ok_or(MrfLifecycleControlError::Unavailable)
|
||||
}
|
||||
|
||||
/// Observes one current responsibility, including Active entries excluded from legacy lists.
|
||||
@@ -151,9 +117,6 @@ 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);
|
||||
|
||||
@@ -1565,7 +1565,6 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
|
||||
match self.live_ecstore().get_bucket_info(bucket, &Default::default()).await {
|
||||
Ok(info) => Ok(Some(info)),
|
||||
Err(StorageError::VolumeNotFound | StorageError::BucketNotFound(_)) => Ok(None),
|
||||
Err(e) => {
|
||||
error!(
|
||||
target: "rustfs::heal::storage",
|
||||
@@ -1584,8 +1583,13 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
}
|
||||
|
||||
async fn mrf_bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
|
||||
// A missing identity leaves the source generation unresolved for MRF replay.
|
||||
self.bucket_incarnation_id(bucket).await
|
||||
match self.live_ecstore().bucket_incarnation_id(bucket).await {
|
||||
Ok(incarnation) => Ok(Some(incarnation)),
|
||||
// A missing bucket leaves the current identity unresolved. It is
|
||||
// not a retirement receipt for an unknown source generation.
|
||||
Err(StorageError::BucketNotFound(_)) => Ok(None),
|
||||
Err(error) => Err(Error::Storage(error)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn replacement_bucket_incarnation(&self, bucket: &str) -> Result<Option<Uuid>> {
|
||||
@@ -1830,11 +1834,11 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
}
|
||||
|
||||
async fn bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
|
||||
match self.live_ecstore().bucket_incarnation_id(bucket).await {
|
||||
Ok(id) => Ok(Some(id)),
|
||||
Err(StorageError::BucketNotFound(_)) => Ok(None),
|
||||
Err(error) => Err(Error::Storage(error)),
|
||||
}
|
||||
self.live_ecstore()
|
||||
.bucket_incarnation_id(bucket)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(Error::Storage)
|
||||
}
|
||||
|
||||
async fn heal_object(
|
||||
@@ -1895,10 +1899,7 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
self.live_ecstore()
|
||||
.recover_delete_transactions_at_incarnation(bucket, object, expected, opts)
|
||||
.await
|
||||
.map_err(|error| match expected {
|
||||
Some(expected) => incarnation_storage_error(bucket, expected, error),
|
||||
None => Error::Storage(error),
|
||||
})
|
||||
.map_err(Error::Storage)
|
||||
}
|
||||
|
||||
async fn recover_delete_prefix_transactions(
|
||||
@@ -1911,10 +1912,7 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
self.live_ecstore()
|
||||
.recover_delete_prefix_at_incarnation(bucket, prefix, expected, opts)
|
||||
.await
|
||||
.map_err(|error| match expected {
|
||||
Some(expected) => incarnation_storage_error(bucket, expected, error),
|
||||
None => Error::Storage(error),
|
||||
})
|
||||
.map_err(Error::Storage)
|
||||
}
|
||||
|
||||
async fn heal_bucket(&self, bucket: &str, opts: &HealOpts) -> Result<HealResultItem> {
|
||||
|
||||
@@ -461,15 +461,12 @@ impl HealTask {
|
||||
}
|
||||
|
||||
// Step 3: Heal bucket structure
|
||||
// Non-replacement AutoHeal runs (crash recovery and directory-backed fallback)
|
||||
// operate on a bucket-name snapshot taken earlier. Fence each bucket's repair
|
||||
// by its live incarnation so a concurrently deleted bucket is never recreated.
|
||||
let auto_bucket_fence = self.source == HealRequestSource::AutoHeal && replacement_resume.is_none();
|
||||
// Check control flags before each iteration to ensure timely cancellation.
|
||||
let bucket_heal_opts = HealOpts {
|
||||
recursive: false,
|
||||
dry_run: self.options.dry_run,
|
||||
remove: false,
|
||||
recreate: self.options.recreate_missing && !auto_bucket_fence,
|
||||
recreate: self.options.recreate_missing,
|
||||
scan_mode: self.options.scan_mode,
|
||||
update_parity: self.options.update_parity,
|
||||
no_lock: self.options.no_lock,
|
||||
@@ -488,11 +485,6 @@ impl HealTask {
|
||||
}
|
||||
let expected = if let Some((_, manager, _)) = replacement_resume.as_ref() {
|
||||
Some(manager.replacement_bucket_incarnation(bucket).await?)
|
||||
} else if auto_bucket_fence {
|
||||
let Some(incarnation) = self.await_with_control(self.storage.bucket_incarnation_id(bucket)).await? else {
|
||||
continue;
|
||||
};
|
||||
Some(incarnation)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -508,7 +500,6 @@ impl HealTask {
|
||||
Ok(result) => {
|
||||
self.record_result_item(result).await;
|
||||
}
|
||||
Err(Error::StaleBucketIncarnation { .. }) if auto_bucket_fence => continue,
|
||||
Err(err) => {
|
||||
// Cancellation and timeout keep their classification; only
|
||||
// a storage failure may be reclassified as a namespace change.
|
||||
@@ -533,20 +524,15 @@ impl HealTask {
|
||||
}
|
||||
}
|
||||
// Adopt delete proofs only after their publication bucket exists.
|
||||
match self
|
||||
if let Some(result) = self
|
||||
.await_with_control(
|
||||
self.storage
|
||||
.recover_delete_transactions(bucket, None, expected, &bucket_heal_opts),
|
||||
)
|
||||
.await
|
||||
.await?
|
||||
{
|
||||
Ok(Some(result)) => {
|
||||
unresolved_delete_recovery |= result.delete_recovery.is_some_and(|status| status.has_unresolved());
|
||||
self.record_result_item(result).await;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(Error::StaleBucketIncarnation { .. }) if auto_bucket_fence => continue,
|
||||
Err(err) => return Err(err),
|
||||
unresolved_delete_recovery |= result.delete_recovery.is_some_and(|status| status.has_unresolved());
|
||||
self.record_result_item(result).await;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1712,7 +1712,6 @@ struct MockStorage {
|
||||
object_heal_detail: Option<String>,
|
||||
object_heal_item: Option<HealResultItem>,
|
||||
bucket_incarnation_id: Mutex<Option<Uuid>>,
|
||||
bucket_incarnation_by_name: Mutex<HashMap<String, Option<Uuid>>>,
|
||||
bucket_incarnation_after_object_heal: Mutex<Option<Uuid>>,
|
||||
bucket_incarnation_after_listing: Mutex<Option<Uuid>>,
|
||||
bucket_incarnation_unavailable: Mutex<bool>,
|
||||
@@ -2461,13 +2460,10 @@ impl HealStorageAPI for MockStorage {
|
||||
Ok(self.object_exists.lock().unwrap().unwrap_or(true))
|
||||
}
|
||||
|
||||
async fn bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
|
||||
async fn bucket_incarnation_id(&self, _bucket: &str) -> Result<Option<Uuid>> {
|
||||
if *self.bucket_incarnation_unavailable.lock().unwrap() {
|
||||
return Err(Error::Other("bucket incarnation unavailable".to_string()));
|
||||
}
|
||||
if let Some(incarnation) = self.bucket_incarnation_by_name.lock().unwrap().get(bucket).copied() {
|
||||
return Ok(incarnation);
|
||||
}
|
||||
Ok(*self.bucket_incarnation_id.lock().unwrap())
|
||||
}
|
||||
|
||||
@@ -5936,129 +5932,3 @@ async fn replacement_owned_mutation_panic_keeps_manager_join_failed() {
|
||||
assert!(manager.stop().await.is_err(), "actual child panic must fail the manager owner");
|
||||
assert!(manager.stop().await.is_err(), "repeat drain cannot erase the child panic");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn crash_recovery_skips_deleted_bucket_and_fences_live_bucket_without_recreate() {
|
||||
let temp = TempDir::new().expect("temporary resume disk directory should be created");
|
||||
let disk = make_resume_disk(&temp).await;
|
||||
let live_incarnation = Uuid::from_u128(101);
|
||||
let storage = Arc::new(MockStorage {
|
||||
resume_disk: Mutex::new(Some(disk)),
|
||||
bucket_incarnation_by_name: Mutex::new(HashMap::from([
|
||||
("deleted-bucket".to_string(), None),
|
||||
("live-bucket".to_string(), Some(live_incarnation)),
|
||||
])),
|
||||
..Default::default()
|
||||
});
|
||||
let mut request = HealRequest::new(
|
||||
HealType::ErasureSet {
|
||||
buckets: vec!["deleted-bucket".to_string(), "live-bucket".to_string()],
|
||||
set_disk_id: "pool_0_set_0".to_string(),
|
||||
},
|
||||
HealOptions {
|
||||
recreate_missing: true,
|
||||
timeout: None,
|
||||
..Default::default()
|
||||
},
|
||||
HealPriority::Low,
|
||||
);
|
||||
request.source = HealRequestSource::AutoHeal;
|
||||
let task = HealTask::from_request(request, storage.clone());
|
||||
|
||||
task.execute()
|
||||
.await
|
||||
.expect("crash-recovery erasure set heal should skip deleted buckets and complete");
|
||||
|
||||
assert_eq!(
|
||||
storage.bucket_heal_calls.lock().expect("bucket heal calls").as_slice(),
|
||||
&["live-bucket".to_string()],
|
||||
"deleted bucket must not invoke bucket-structure heal"
|
||||
);
|
||||
assert_eq!(
|
||||
storage
|
||||
.delete_recovery_calls
|
||||
.lock()
|
||||
.expect("delete recovery calls")
|
||||
.as_slice(),
|
||||
&["live-bucket".to_string()],
|
||||
"deleted bucket must not invoke delete-transaction recovery"
|
||||
);
|
||||
let opts = storage.bucket_heal_opts.lock().expect("bucket heal opts");
|
||||
assert_eq!(opts.len(), 1);
|
||||
assert!(
|
||||
!opts[0].recreate,
|
||||
"crash-recovery bucket prepass must keep recreate=false so only validated partial loss reconstructs"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn crash_recovery_skips_stale_incarnation_during_bucket_heal_and_delete_recovery() {
|
||||
let temp = TempDir::new().expect("temporary resume disk directory should be created");
|
||||
let disk = make_resume_disk(&temp).await;
|
||||
let stale_prepass = Uuid::from_u128(201);
|
||||
let stale_recovery = Uuid::from_u128(202);
|
||||
let live = Uuid::from_u128(203);
|
||||
let storage = Arc::new(MockStorage {
|
||||
resume_disk: Mutex::new(Some(disk)),
|
||||
bucket_incarnation_by_name: Mutex::new(HashMap::from([
|
||||
("deleted-during-prepass".to_string(), Some(stale_prepass)),
|
||||
("deleted-during-recovery".to_string(), Some(stale_recovery)),
|
||||
("live-bucket".to_string(), Some(live)),
|
||||
])),
|
||||
typed_bucket_heal_errors: Mutex::new(HashMap::from([(
|
||||
"deleted-during-prepass".to_string(),
|
||||
VecDeque::from([Error::StaleBucketIncarnation {
|
||||
bucket: "deleted-during-prepass".to_string(),
|
||||
expected: Some(stale_prepass),
|
||||
}]),
|
||||
)])),
|
||||
delete_recovery_results: Mutex::new(HashMap::from([(
|
||||
"deleted-during-recovery".to_string(),
|
||||
Err(Error::StaleBucketIncarnation {
|
||||
bucket: "deleted-during-recovery".to_string(),
|
||||
expected: Some(stale_recovery),
|
||||
}),
|
||||
)])),
|
||||
..Default::default()
|
||||
});
|
||||
let mut request = HealRequest::new(
|
||||
HealType::ErasureSet {
|
||||
buckets: vec![
|
||||
"deleted-during-prepass".to_string(),
|
||||
"deleted-during-recovery".to_string(),
|
||||
"live-bucket".to_string(),
|
||||
],
|
||||
set_disk_id: "pool_0_set_0".to_string(),
|
||||
},
|
||||
HealOptions {
|
||||
recreate_missing: true,
|
||||
timeout: None,
|
||||
..Default::default()
|
||||
},
|
||||
HealPriority::Low,
|
||||
);
|
||||
request.source = HealRequestSource::AutoHeal;
|
||||
let task = HealTask::from_request(request, storage.clone());
|
||||
|
||||
task.execute()
|
||||
.await
|
||||
.expect("concurrent bucket deletion during prepass or delete recovery must not fail crash recovery");
|
||||
|
||||
assert_eq!(
|
||||
storage.bucket_heal_calls.lock().expect("bucket heal calls").as_slice(),
|
||||
&[
|
||||
"deleted-during-prepass".to_string(),
|
||||
"deleted-during-recovery".to_string(),
|
||||
"live-bucket".to_string(),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
storage
|
||||
.delete_recovery_calls
|
||||
.lock()
|
||||
.expect("delete recovery calls")
|
||||
.as_slice(),
|
||||
&["deleted-during-recovery".to_string(), "live-bucket".to_string()],
|
||||
"prepass StaleBucketIncarnation must skip delete recovery for that bucket while continuing live buckets"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1088,240 +1088,3 @@ async fn bucket_removal_recovers_delete_proofs_before_removing_empty_volumes() {
|
||||
"all empty replicas should be removed after proof settlement"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn crash_recovery_erasure_set_does_not_recreate_deleted_bucket_and_repairs_live_bucket() {
|
||||
const STACK_SIZE: usize = 8 * 1024 * 1024;
|
||||
std::thread::Builder::new()
|
||||
.name("crash-recovery-deleted-bucket".to_owned())
|
||||
.stack_size(STACK_SIZE)
|
||||
.spawn(|| {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(4)
|
||||
.thread_stack_size(STACK_SIZE)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("crash recovery runtime");
|
||||
runtime.block_on(crash_recovery_erasure_set_does_not_recreate_deleted_bucket_and_repairs_live_bucket_case());
|
||||
})
|
||||
.expect("crash recovery test thread")
|
||||
.join()
|
||||
.expect("crash recovery test result");
|
||||
}
|
||||
|
||||
async fn crash_recovery_erasure_set_does_not_recreate_deleted_bucket_and_repairs_live_bucket_case() {
|
||||
use storage_api::integration::EcstoreStorageError;
|
||||
|
||||
let (disk_paths, ecstore, storage) = heal_env(TestECStoreEnvBuilder::default()).await;
|
||||
let deleted_bucket = "crash-recovery-deleted";
|
||||
let live_bucket = "crash-recovery-live";
|
||||
let payload = non_inline_test_data();
|
||||
|
||||
create_test_bucket(&ecstore, deleted_bucket).await;
|
||||
create_test_bucket(&ecstore, live_bucket).await;
|
||||
upload_test_object(&ecstore, deleted_bucket, "temp.bin", &payload).await;
|
||||
upload_test_object(&ecstore, live_bucket, "keep.bin", &payload).await;
|
||||
wait_for_object_copies(&disk_paths, deleted_bucket, "temp.bin").await;
|
||||
wait_for_object_copies(&disk_paths, live_bucket, "keep.bin").await;
|
||||
|
||||
// Mirror `HealManager::process_unclean_shutdown`: snapshot existing buckets at startup
|
||||
// with default `recreate_missing: true` and empty `heal_endpoints`.
|
||||
let mut request = HealRequest::new(
|
||||
HealType::ErasureSet {
|
||||
buckets: vec![deleted_bucket.to_owned(), live_bucket.to_owned()],
|
||||
set_disk_id: "pool_0_set_0".to_owned(),
|
||||
},
|
||||
HealOptions {
|
||||
timeout: None,
|
||||
..HealOptions::default()
|
||||
},
|
||||
HealPriority::Low,
|
||||
);
|
||||
request.source = HealRequestSource::AutoHeal;
|
||||
|
||||
// Client deletes all objects and deletes the bucket before the queued heal runs.
|
||||
ecstore
|
||||
.delete_object(deleted_bucket, "temp.bin", ObjectOptions::default())
|
||||
.await
|
||||
.expect("delete object before DeleteBucket");
|
||||
ecstore
|
||||
.delete_bucket(deleted_bucket, &Default::default())
|
||||
.await
|
||||
.expect("DeleteBucket should succeed");
|
||||
assert!(
|
||||
disk_paths.iter().all(|path| !path.join(deleted_bucket).exists()),
|
||||
"DeleteBucket must remove the deleted bucket directory from every drive"
|
||||
);
|
||||
|
||||
// Simulate a live bucket missing its directory on one drive so the same crash-recovery
|
||||
// run also proves partial directory loss is still repaired.
|
||||
fs::remove_dir_all(disk_paths[0].join(live_bucket))
|
||||
.await
|
||||
.expect("remove live bucket directory on disk 0");
|
||||
assert!(!disk_paths[0].join(live_bucket).exists());
|
||||
|
||||
HealTask::from_request(request, storage.clone())
|
||||
.execute()
|
||||
.await
|
||||
.expect("crash-recovery erasure set heal must complete without recreating deleted bucket");
|
||||
|
||||
assert!(
|
||||
disk_paths.iter().all(|path| !path.join(deleted_bucket).exists()),
|
||||
"deleted bucket directory must stay absent on every drive after crash-recovery heal"
|
||||
);
|
||||
let listed = ecstore
|
||||
.list_bucket(&Default::default())
|
||||
.await
|
||||
.expect("list buckets after crash-recovery heal");
|
||||
assert!(
|
||||
!listed.iter().any(|bucket| bucket.name == deleted_bucket),
|
||||
"deleted bucket must not reappear in ListBuckets"
|
||||
);
|
||||
assert!(listed.iter().any(|bucket| bucket.name == live_bucket), "live bucket must remain listed");
|
||||
|
||||
let mut reader = PutObjReader::from_vec(b"should-fail".to_vec());
|
||||
let put_err = ecstore
|
||||
.put_object(deleted_bucket, "after-delete.bin", &mut reader, &ObjectOptions::default())
|
||||
.await
|
||||
.expect_err("PUT to a deleted bucket must fail after crash-recovery heal");
|
||||
assert!(
|
||||
matches!(put_err, EcstoreStorageError::BucketNotFound(_) | EcstoreStorageError::VolumeNotFound),
|
||||
"expected missing-bucket error for deleted bucket PUT, got: {put_err:?}"
|
||||
);
|
||||
|
||||
assert!(
|
||||
disk_paths[0].join(live_bucket).is_dir(),
|
||||
"crash-recovery heal must still reconstruct a missing directory for a live bucket"
|
||||
);
|
||||
assert!(
|
||||
disk_paths[0].join(live_bucket).join("keep.bin").join("xl.meta").exists(),
|
||||
"crash-recovery heal must repair missing object shards on the live bucket"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn fenced_bucket_heal_and_delete_recovery_classify_retired_bucket_as_stale() {
|
||||
const STACK_SIZE: usize = 8 * 1024 * 1024;
|
||||
std::thread::Builder::new()
|
||||
.name("fenced-retired-bucket-heal".to_owned())
|
||||
.stack_size(STACK_SIZE)
|
||||
.spawn(|| {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(4)
|
||||
.thread_stack_size(STACK_SIZE)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("fenced retired bucket runtime");
|
||||
runtime.block_on(fenced_bucket_heal_and_delete_recovery_classify_retired_bucket_as_stale_case());
|
||||
})
|
||||
.expect("fenced retired bucket test thread")
|
||||
.join()
|
||||
.expect("fenced retired bucket test result");
|
||||
}
|
||||
|
||||
async fn fenced_bucket_heal_and_delete_recovery_classify_retired_bucket_as_stale_case() {
|
||||
use rustfs_heal::Error;
|
||||
|
||||
let (disk_paths, ecstore, storage) = heal_env(TestECStoreEnvBuilder::default()).await;
|
||||
|
||||
// 1. Concurrent DeleteBucket after incarnation lookup (TOCTOU window): retired generation
|
||||
// must classify as StaleBucketIncarnation and must never recreate directories.
|
||||
let retired_bucket = "retired-toctou-bucket";
|
||||
create_test_bucket(&ecstore, retired_bucket).await;
|
||||
let retired_incarnation = storage
|
||||
.bucket_incarnation_id(retired_bucket)
|
||||
.await
|
||||
.expect("lookup live incarnation")
|
||||
.expect("new bucket has an authoritative incarnation");
|
||||
ecstore
|
||||
.delete_bucket(retired_bucket, &Default::default())
|
||||
.await
|
||||
.expect("delete bucket after incarnation snapshot");
|
||||
|
||||
assert_eq!(
|
||||
storage
|
||||
.bucket_incarnation_id(retired_bucket)
|
||||
.await
|
||||
.expect("missing bucket incarnation should return Ok(None)"),
|
||||
None
|
||||
);
|
||||
|
||||
let heal_err = storage
|
||||
.heal_bucket_at_incarnation(
|
||||
retired_bucket,
|
||||
retired_incarnation,
|
||||
&HealOpts {
|
||||
recreate: false,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("fenced bucket heal must reject a retired generation");
|
||||
assert!(
|
||||
matches!(
|
||||
&heal_err,
|
||||
Error::StaleBucketIncarnation { bucket, expected }
|
||||
if bucket == retired_bucket && *expected == Some(retired_incarnation)
|
||||
),
|
||||
"expected StaleBucketIncarnation for retired bucket heal, got: {heal_err:?}"
|
||||
);
|
||||
assert!(
|
||||
disk_paths.iter().all(|path| !path.join(retired_bucket).exists()),
|
||||
"fenced bucket heal must not recreate a retired bucket directory"
|
||||
);
|
||||
|
||||
let recovery_err = storage
|
||||
.recover_delete_transactions(retired_bucket, None, Some(retired_incarnation), &HealOpts::default())
|
||||
.await
|
||||
.expect_err("fenced delete recovery must reject a retired generation");
|
||||
assert!(
|
||||
matches!(
|
||||
&recovery_err,
|
||||
Error::StaleBucketIncarnation { bucket, expected }
|
||||
if bucket == retired_bucket && *expected == Some(retired_incarnation)
|
||||
),
|
||||
"expected StaleBucketIncarnation for retired delete recovery, got: {recovery_err:?}"
|
||||
);
|
||||
|
||||
// 2. Fail-closed negative case: removing `.bucket-incarnation` on a live non-retired bucket
|
||||
// must NOT be misclassified as StaleBucketIncarnation.
|
||||
let corrupt_bucket = "live-missing-incarnation-bucket";
|
||||
create_test_bucket(&ecstore, corrupt_bucket).await;
|
||||
let live_incarnation = storage
|
||||
.bucket_incarnation_id(corrupt_bucket)
|
||||
.await
|
||||
.expect("lookup live incarnation")
|
||||
.expect("live bucket has an authoritative incarnation");
|
||||
ecstore
|
||||
.delete_object(
|
||||
".rustfs.sys",
|
||||
&format!("buckets/{corrupt_bucket}/.bucket-incarnation"),
|
||||
ObjectOptions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("simulate missing incarnation sidecar on a live non-retired bucket");
|
||||
|
||||
let corrupt_err = storage
|
||||
.heal_bucket_at_incarnation(
|
||||
corrupt_bucket,
|
||||
live_incarnation,
|
||||
&HealOpts {
|
||||
recreate: false,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("missing incarnation sidecar on a live non-retired bucket must fail closed");
|
||||
assert!(
|
||||
!matches!(corrupt_err, Error::StaleBucketIncarnation { .. }),
|
||||
"live non-retired bucket with missing incarnation metadata must not be treated as deleted: {corrupt_err:?}"
|
||||
);
|
||||
assert!(
|
||||
corrupt_err
|
||||
.to_string()
|
||||
.contains("bucket incarnation metadata is not authoritative"),
|
||||
"expected authoritative-metadata failure for live corrupted bucket, got: {corrupt_err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
+13
-291
@@ -28,10 +28,6 @@ use crate::{
|
||||
|
||||
/// Default shard count for guard storage (must be power of 2)
|
||||
const DEFAULT_GUARD_SHARD_COUNT: usize = 64;
|
||||
/// Default interval for reaping expired local lease guards.
|
||||
/// Kept independent of `fast_lock::CLEANUP_INTERVAL` (which sweeps idle state pools)
|
||||
/// so expired leases are released promptly even when the cluster is quiescent.
|
||||
pub(crate) const DEFAULT_LEASE_REAPER_INTERVAL: Duration = Duration::from_secs(1);
|
||||
const EVENT_NAMESPACE_LOCK_ACQUIRE: &str = "namespace_lock_acquire";
|
||||
const EVENT_NAMESPACE_LOCK_RELEASE: &str = "namespace_lock_release";
|
||||
const EVENT_LOCK_GUARD_RECLAIMED: &str = "lock_guard_reclaimed";
|
||||
@@ -471,7 +467,7 @@ impl LocalClient {
|
||||
|
||||
let guard_storage: Vec<GuardShard> = (0..shard_count).map(|_| Arc::new(GuardRegistry::default())).collect();
|
||||
|
||||
Self::with_storage(Arc::new(guard_storage), None, DEFAULT_LEASE_REAPER_INTERVAL)
|
||||
Self::with_storage(Arc::new(guard_storage), None, crate::fast_lock::CLEANUP_INTERVAL)
|
||||
}
|
||||
|
||||
fn with_storage(guard_storage: GuardStorage, manager: Option<Arc<GlobalLockManager>>, reaper_interval: Duration) -> Self {
|
||||
@@ -522,7 +518,7 @@ impl LocalClient {
|
||||
let guard_storage = (0..DEFAULT_GUARD_SHARD_COUNT)
|
||||
.map(|_| Arc::new(GuardRegistry::default()))
|
||||
.collect();
|
||||
Self::with_storage(Arc::new(guard_storage), Some(manager), DEFAULT_LEASE_REAPER_INTERVAL)
|
||||
Self::with_storage(Arc::new(guard_storage), Some(manager), crate::fast_lock::CLEANUP_INTERVAL)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -565,35 +561,25 @@ impl LocalClient {
|
||||
reclaimed_for_resource
|
||||
}
|
||||
|
||||
async fn reclaim_expired_guards(storage: &GuardStorage) -> usize {
|
||||
let mut total_reclaimed = 0;
|
||||
async fn extract_expired_guards(storage: &GuardStorage) -> Vec<LocalGuardEntry> {
|
||||
let mut expired_entries = Vec::new();
|
||||
for shard in storage.iter() {
|
||||
if !shard.read().await.sweep_due() {
|
||||
continue;
|
||||
}
|
||||
let expired_entries = {
|
||||
let mut guards = shard.write().await;
|
||||
guards.extract_expired()
|
||||
};
|
||||
// Drop physical guards outside the shard lock immediately so contention on a later
|
||||
// shard cannot delay releasing expired guards extracted from earlier shards.
|
||||
total_reclaimed += Self::release_reclaimed_guards_unlogged(expired_entries);
|
||||
let mut guards = shard.write().await;
|
||||
expired_entries.extend(guards.extract_expired());
|
||||
}
|
||||
Self::log_reclaimed_guards(total_reclaimed);
|
||||
total_reclaimed
|
||||
expired_entries
|
||||
}
|
||||
|
||||
fn release_reclaimed_guards_unlogged(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
|
||||
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
|
||||
let mut reclaimed = 0;
|
||||
for mut entry in entries {
|
||||
let _ = entry.guard.release();
|
||||
rustfs_io_metrics::record_lock_reclaimed();
|
||||
reclaimed += 1;
|
||||
}
|
||||
reclaimed
|
||||
}
|
||||
|
||||
fn log_reclaimed_guards(reclaimed: usize) {
|
||||
if reclaimed > 0 {
|
||||
tracing::debug!(
|
||||
event = EVENT_LOCK_GUARD_RECLAIMED,
|
||||
@@ -604,11 +590,6 @@ impl LocalClient {
|
||||
"Expired lock guards reclaimed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
|
||||
let reclaimed = Self::release_reclaimed_guards_unlogged(entries);
|
||||
Self::log_reclaimed_guards(reclaimed);
|
||||
reclaimed
|
||||
}
|
||||
|
||||
@@ -620,13 +601,13 @@ impl LocalClient {
|
||||
let interval = self.reaper_interval;
|
||||
tokio::spawn(async move {
|
||||
let mut ticker = tokio::time::interval(interval);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
let Some(storage) = storage.upgrade() else {
|
||||
break;
|
||||
};
|
||||
Self::reclaim_expired_guards(&storage).await;
|
||||
let expired_entries = Self::extract_expired_guards(&storage).await;
|
||||
Self::release_reclaimed_guards(expired_entries);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -991,7 +972,7 @@ mod tests {
|
||||
assert!(client.acquire_lock(&request).await.expect("register shared lease").success);
|
||||
requests.push(request);
|
||||
}
|
||||
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 0);
|
||||
assert!(LocalClient::extract_expired_guards(&client.guard_storage).await.is_empty());
|
||||
{
|
||||
let registry = client.get_shard(&requests[0].lock_id).read().await;
|
||||
assert_eq!(registry.entries.len(), 512);
|
||||
@@ -1098,7 +1079,8 @@ mod tests {
|
||||
assert_eq!(backend.get_shard(&resource).active_guard_count(), 1);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(5)).await;
|
||||
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 1);
|
||||
let expired = LocalClient::extract_expired_guards(&client.guard_storage).await;
|
||||
assert_eq!(LocalClient::release_reclaimed_guards(expired), 1);
|
||||
assert_eq!(backend.get_shard(&resource).active_guard_count(), 0);
|
||||
assert!(
|
||||
client
|
||||
@@ -1831,264 +1813,4 @@ mod tests {
|
||||
.expect("second collision stamp");
|
||||
assert_eq!(after.generation(), before.generation() + 1);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn default_reaper_reclaims_expired_read_lock_without_reacquire_or_diagnostics() {
|
||||
assert_eq!(DEFAULT_LEASE_REAPER_INTERVAL, Duration::from_secs(1));
|
||||
assert_eq!(LocalClient::new().reaper_interval, DEFAULT_LEASE_REAPER_INTERVAL);
|
||||
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let client = LocalClient::with_manager(manager.clone());
|
||||
let resource = crate::ObjectKey::new("jepsen-xpool-worm", ".rustfs-table/warehouses/default/publication.lock");
|
||||
let read_req =
|
||||
LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&read_req)
|
||||
.await
|
||||
.expect("acquire default-ttl shared lock")
|
||||
.success
|
||||
);
|
||||
|
||||
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
|
||||
tokio::time::advance(Duration::from_secs(29)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
backend.get_shard(&resource).active_guard_count(),
|
||||
1,
|
||||
"unexpired read lock must remain held before its 30s lease deadline"
|
||||
);
|
||||
|
||||
// Advance just past the 30s lease plus one 1s reaper interval without calling
|
||||
// list_lock_leases() or issuing any acquire on the same shard.
|
||||
tokio::time::advance(Duration::from_secs(2)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
backend.get_shard(&resource).active_guard_count(),
|
||||
0,
|
||||
"default 1s reaper must release the physical guard within 2s after expiry"
|
||||
);
|
||||
assert!(
|
||||
client
|
||||
.check_status(&read_req.lock_id)
|
||||
.await
|
||||
.expect("check reaped read lock status")
|
||||
.is_none()
|
||||
);
|
||||
let writer = manager
|
||||
.acquire_lock(crate::ObjectLockRequest::new_write(resource, "writer"))
|
||||
.await
|
||||
.expect("conflicting writer must succeed immediately once the expired read guard is reaped");
|
||||
drop(writer);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn default_reaper_preserves_refreshed_read_lock_and_reclaims_after_extended_deadline() {
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let client = LocalClient::with_manager(manager.clone());
|
||||
let resource = crate::ObjectKey::new("jepsen-xpool-worm", "");
|
||||
let read_req =
|
||||
LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&read_req)
|
||||
.await
|
||||
.expect("acquire default-ttl bucket read lock")
|
||||
.success
|
||||
);
|
||||
|
||||
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
|
||||
tokio::time::advance(Duration::from_secs(20)).await;
|
||||
assert!(
|
||||
client
|
||||
.refresh(&read_req.lock_id)
|
||||
.await
|
||||
.expect("refresh shared lease before deadline")
|
||||
);
|
||||
|
||||
// Cross the original 30s deadline (which triggers one due-hint rescan on the shard)
|
||||
// and verify the refreshed lease remains held until t=50s.
|
||||
tokio::time::advance(Duration::from_secs(15)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
backend.get_shard(&resource).active_guard_count(),
|
||||
1,
|
||||
"refreshed read lock must survive past its original deadline"
|
||||
);
|
||||
assert!(
|
||||
client
|
||||
.check_status(&read_req.lock_id)
|
||||
.await
|
||||
.expect("read refreshed lease status")
|
||||
.is_some()
|
||||
);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(17)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(
|
||||
backend.get_shard(&resource).active_guard_count(),
|
||||
0,
|
||||
"default 1s reaper must release the physical guard promptly after the refreshed deadline"
|
||||
);
|
||||
let writer = manager
|
||||
.acquire_lock(crate::ObjectLockRequest::new_write(resource, "writer"))
|
||||
.await
|
||||
.expect("conflicting writer must succeed after the refreshed lease expires");
|
||||
drop(writer);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn reaper_releases_earlier_shard_before_waiting_on_contended_later_shard() {
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let client = LocalClient::with_manager(manager.clone());
|
||||
client.reaper_started.store(true, Ordering::Release);
|
||||
|
||||
let mut early_resource = None;
|
||||
let mut later_resource = None;
|
||||
for index in 0..4096 {
|
||||
let candidate = crate::ObjectKey::new("bucket", format!("shard-order-{index}"));
|
||||
let shard_idx = client.get_resource_shard_index(&candidate);
|
||||
if shard_idx == 0 && early_resource.is_none() {
|
||||
early_resource = Some(candidate);
|
||||
} else if shard_idx > 0 && later_resource.is_none() {
|
||||
later_resource = Some(candidate);
|
||||
}
|
||||
if early_resource.is_some() && later_resource.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let early_resource = early_resource.expect("find resource hashed to shard 0");
|
||||
let later_resource = later_resource.expect("find resource hashed to a later shard");
|
||||
let later_shard_idx = client.get_resource_shard_index(&later_resource);
|
||||
|
||||
let early_req =
|
||||
LockRequest::new(early_resource.clone(), LockType::Shared, "owner-early").with_ttl(Duration::from_secs(5));
|
||||
let later_req =
|
||||
LockRequest::new(later_resource.clone(), LockType::Shared, "owner-later").with_ttl(Duration::from_secs(5));
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&early_req)
|
||||
.await
|
||||
.expect("acquire early shard lock")
|
||||
.success
|
||||
);
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&later_req)
|
||||
.await
|
||||
.expect("acquire later shard lock")
|
||||
.success
|
||||
);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(5)).await;
|
||||
|
||||
let (release_later, later_owner) = hold_guard_shard(client.guard_storage[later_shard_idx].clone());
|
||||
let mut sweep = Box::pin(LocalClient::reclaim_expired_guards(&client.guard_storage));
|
||||
assert!(
|
||||
matches!(futures::poll!(&mut sweep), Poll::Pending),
|
||||
"sweep must pause while the later shard is contended"
|
||||
);
|
||||
|
||||
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
|
||||
assert_eq!(
|
||||
backend.get_shard(&early_resource).active_guard_count(),
|
||||
0,
|
||||
"expired physical guard from earlier shard must already be released outside the shard lock"
|
||||
);
|
||||
let writer = manager
|
||||
.acquire_lock(crate::ObjectLockRequest::new_write(early_resource, "writer"))
|
||||
.await
|
||||
.expect("writer on earlier shard must not be blocked by later shard contention");
|
||||
drop(writer);
|
||||
|
||||
release_later.send(()).expect("release contended later shard");
|
||||
later_owner.join().expect("later shard owner must finish");
|
||||
assert_eq!(sweep.await, 2);
|
||||
assert_eq!(backend.get_shard(&later_resource).active_guard_count(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn default_reaper_reclaims_expired_read_lock_under_hot_shard_contention_within_budget() {
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let client = Arc::new(LocalClient::with_manager(manager.clone()));
|
||||
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
|
||||
let expired_resource = crate::ObjectKey::new("jepsen-xpool-worm", "expired-hot-target");
|
||||
let hot_shard = client.get_resource_shard_index(&expired_resource);
|
||||
let contending_resource = (0..4096)
|
||||
.map(|index| crate::ObjectKey::new("jepsen-xpool-worm", format!("hot-peer-{index}")))
|
||||
.find(|candidate| {
|
||||
candidate != &expired_resource
|
||||
&& client.get_resource_shard_index(candidate) == hot_shard
|
||||
&& !Arc::ptr_eq(backend.get_shard(candidate), backend.get_shard(&expired_resource))
|
||||
})
|
||||
.expect("find sibling resource sharing the hot guard shard on a distinct backend shard");
|
||||
|
||||
// Pre-register sibling leases on the same guard shard and continuously refresh/inspect
|
||||
// them. Unlike acquire_lock(), refresh() contends on the shard write lock without running
|
||||
// eager reclaim, so only the background 1s reaper can release `expired_resource`.
|
||||
let mut sibling_ids = Vec::with_capacity(8);
|
||||
for worker_idx in 0..8 {
|
||||
let req = LockRequest::new(contending_resource.clone(), LockType::Shared, format!("hot-{worker_idx}"))
|
||||
.with_ttl(Duration::from_secs(30));
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&req)
|
||||
.await
|
||||
.expect("register contending sibling read lock")
|
||||
.success
|
||||
);
|
||||
sibling_ids.push(req.lock_id);
|
||||
}
|
||||
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let mut workers = tokio::task::JoinSet::new();
|
||||
for lock_id in sibling_ids.clone() {
|
||||
let client = client.clone();
|
||||
let stop = stop.clone();
|
||||
workers.spawn(async move {
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
assert!(client.refresh(&lock_id).await.expect("hot worker refresh"));
|
||||
let _ = client.check_status(&lock_id).await.expect("hot worker status");
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let ttl = Duration::from_millis(100);
|
||||
let expired_req = LockRequest::new(expired_resource.clone(), LockType::Shared, "peer-n6").with_ttl(ttl);
|
||||
let acquired_at = Instant::now();
|
||||
assert!(
|
||||
client
|
||||
.acquire_lock(&expired_req)
|
||||
.await
|
||||
.expect("acquire target read lock on hot shard")
|
||||
.success
|
||||
);
|
||||
|
||||
let expiry_at = acquired_at + ttl;
|
||||
let deadline = expiry_at + Duration::from_secs(3);
|
||||
while backend.get_lock_info(&expired_resource).is_some() {
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"default 1s reaper failed to release expired read guard within 3s under hot-shard contention"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert_eq!(backend.get_shard(&expired_resource).active_guard_count(), 0);
|
||||
|
||||
let writer = manager
|
||||
.acquire_lock(crate::ObjectLockRequest::new_write(expired_resource, "writer"))
|
||||
.await
|
||||
.expect("writer must succeed once the expired read guard is physically released");
|
||||
drop(writer);
|
||||
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
while let Some(joined) = workers.join_next().await {
|
||||
joined.expect("hot-shard worker must exit cleanly");
|
||||
}
|
||||
for lock_id in sibling_ids {
|
||||
assert!(client.release(&lock_id).await.expect("release contending sibling read lock"));
|
||||
}
|
||||
assert_eq!(backend.get_shard(&contending_resource).active_guard_count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,16 +343,7 @@ impl FastObjectLockManager {
|
||||
|
||||
/// Return aggregate live holder and waiter counts without collecting lock names.
|
||||
pub fn current_lock_counts(&self) -> (u64, u64) {
|
||||
self.count_locks(None)
|
||||
}
|
||||
|
||||
/// Return live holder and waiter counts for namespace keys in `bucket`.
|
||||
pub fn current_lock_counts_for_bucket(&self, bucket: &str) -> (u64, u64) {
|
||||
self.count_locks(Some(bucket))
|
||||
}
|
||||
|
||||
fn count_locks(&self, bucket: Option<&str>) -> (u64, u64) {
|
||||
self.shards.iter().map(|shard| shard.current_lock_counts(bucket)).fold(
|
||||
self.shards.iter().map(|shard| shard.current_lock_counts()).fold(
|
||||
(0, 0),
|
||||
|(holders, waiters), (shard_holders, shard_waiters)| {
|
||||
(holders.saturating_add(shard_holders), waiters.saturating_add(shard_waiters))
|
||||
|
||||
@@ -814,12 +814,11 @@ impl LockShard {
|
||||
objects.values().filter(|state| state.is_locked()).count()
|
||||
}
|
||||
|
||||
pub(crate) fn current_lock_counts(&self, bucket: Option<&str>) -> (u64, u64) {
|
||||
pub(crate) fn current_lock_counts(&self) -> (u64, u64) {
|
||||
self.objects
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|(key, _)| bucket.is_none_or(|bucket| key.bucket.as_ref() == bucket))
|
||||
.map(|(_, state)| state.atomic_state.holder_and_waiter_counts())
|
||||
.values()
|
||||
.map(|state| state.atomic_state.holder_and_waiter_counts())
|
||||
.fold((0, 0), |(holders, waiters), (state_holders, state_waiters)| {
|
||||
(holders.saturating_add(state_holders), waiters.saturating_add(state_waiters))
|
||||
})
|
||||
|
||||
@@ -123,16 +123,12 @@ mod fast_lock_tests {
|
||||
.acquire_read_lock(key.clone(), Arc::<str>::from("second-holder"))
|
||||
.await
|
||||
.expect("second read holder");
|
||||
let unrelated = manager
|
||||
.acquire_write_lock(ObjectKey::new("other-bucket", "contended-object"), "unrelated")
|
||||
.await
|
||||
.expect("an unrelated bucket can hold a lock");
|
||||
|
||||
let waiter_manager = manager.clone();
|
||||
let waiter = tokio::spawn(async move { waiter_manager.acquire_write_lock(key, Arc::<str>::from("waiter")).await });
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
loop {
|
||||
if manager.current_lock_counts_for_bucket("test-bucket") == (2, 1) {
|
||||
if manager.current_lock_counts() == (2, 1) {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
@@ -140,16 +136,12 @@ mod fast_lock_tests {
|
||||
})
|
||||
.await
|
||||
.expect("writer waiter should be observed");
|
||||
assert_eq!(manager.current_lock_counts(), (3, 1));
|
||||
|
||||
drop(holder);
|
||||
drop(second_holder);
|
||||
let acquired = waiter.await.expect("waiter task").expect("waiting writer should acquire");
|
||||
assert_eq!(manager.current_lock_counts_for_bucket("test-bucket"), (1, 0));
|
||||
assert_eq!(manager.current_lock_counts(), (1, 0));
|
||||
drop(acquired);
|
||||
assert_eq!(manager.current_lock_counts_for_bucket("test-bucket"), (0, 0));
|
||||
assert_eq!(manager.current_lock_counts_for_bucket("other-bucket"), (1, 0));
|
||||
drop(unrelated);
|
||||
assert_eq!(manager.current_lock_counts(), (0, 0));
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ nixl-sys = { workspace = true, optional = true }
|
||||
parking_lot = { workspace = true, optional = true }
|
||||
quick-xml = { workspace = true, features = ["serialize"], optional = true }
|
||||
# Match the native rc transport so it can retain its alias TLS and proxy policy.
|
||||
reqwest = { version = "0.13.5", default-features = false, optional = true }
|
||||
reqwest = { version = ">=0.12, <0.13", default-features = false, optional = true }
|
||||
rustix = { workspace = true, features = ["fs"], optional = true }
|
||||
serde = { workspace = true, features = ["derive"], optional = true }
|
||||
thiserror = { workspace = true, optional = true }
|
||||
|
||||
+10
-67
@@ -36,10 +36,9 @@ pub mod devices;
|
||||
mod mem;
|
||||
mod remotes;
|
||||
|
||||
pub use remotes::PeerRole;
|
||||
|
||||
use mem::HostBuffer;
|
||||
use std::collections::VecDeque;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use thiserror::Error;
|
||||
@@ -119,8 +118,6 @@ impl ClientMemory {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RdmaToken {
|
||||
raw: String,
|
||||
role: PeerRole,
|
||||
expected_metadata_sha256: Option<[u8; 32]>,
|
||||
/// The client's agent name.
|
||||
pub agent: String,
|
||||
/// The client's agent metadata when the request carried it.
|
||||
@@ -187,8 +184,6 @@ impl RdmaToken {
|
||||
}
|
||||
Ok(Self {
|
||||
raw: format!("{agent}:{}", buffer.trim()),
|
||||
role: PeerRole::S3Client,
|
||||
expected_metadata_sha256: None,
|
||||
agent: agent.to_owned(),
|
||||
metadata,
|
||||
memory,
|
||||
@@ -198,32 +193,6 @@ impl RdmaToken {
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds an internode peer token bound to a caller-verified SHA-256 metadata digest.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`NixlError::Token`] when `metadata_base64` is empty, invalid
|
||||
/// base64, or when the agent or buffer descriptor is malformed.
|
||||
pub fn for_internode(
|
||||
agent: &str,
|
||||
metadata_base64: &str,
|
||||
verified_metadata_sha256: [u8; 32],
|
||||
buffer: &str,
|
||||
) -> Result<Self, NixlError> {
|
||||
let mut token = Self::from_headers(agent, Some(metadata_base64), buffer)?;
|
||||
if token.metadata.is_none() {
|
||||
return Err(NixlError::Token(format!("agent {agent:?} needs {NIXL_METADATA_HEADER}")));
|
||||
}
|
||||
token.role = PeerRole::Internode;
|
||||
token.expected_metadata_sha256 = Some(verified_metadata_sha256);
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Trust domain of this token (`S3Client` or `Internode`).
|
||||
pub fn role(&self) -> PeerRole {
|
||||
self.role
|
||||
}
|
||||
|
||||
/// Agent name and buffer, for logs.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.raw
|
||||
@@ -317,11 +286,7 @@ pub struct ArenaRanges {
|
||||
|
||||
impl ArenaRanges {
|
||||
pub fn total_len(&self) -> usize {
|
||||
self.ranges.iter().fold(0usize, |total, (_, len)| total.saturating_add(*len))
|
||||
}
|
||||
|
||||
pub fn checked_total_len(&self) -> Option<usize> {
|
||||
self.ranges.iter().try_fold(0usize, |total, (_, len)| total.checked_add(*len))
|
||||
self.ranges.iter().map(|(_, len)| *len).sum()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -550,6 +515,12 @@ impl std::fmt::Debug for NixlServer {
|
||||
}
|
||||
}
|
||||
|
||||
fn metadata_hash(metadata: &[u8]) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
metadata.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
impl NixlServer {
|
||||
fn register_staging<B: nixl_sys::MemoryRegion + nixl_sys::NixlDescriptor>(
|
||||
config: &NixlConfig,
|
||||
@@ -848,18 +819,13 @@ impl NixlServer {
|
||||
if source.ranges.len() > MAX_SG_RANGES {
|
||||
return Err(NixlError::Token("too many scatter-gather ranges".to_owned()));
|
||||
}
|
||||
let total = source
|
||||
.checked_total_len()
|
||||
.ok_or_else(|| NixlError::Token("scatter-gather length overflow".to_owned()))?;
|
||||
let total = source.total_len();
|
||||
if total == 0 {
|
||||
return Ok((0, keep));
|
||||
}
|
||||
let remote_base = Self::client_window(token, remote_offset, total as u64)?;
|
||||
let remote_base =
|
||||
usize::try_from(remote_base).map_err(|_| NixlError::Token("remote address exceeds the platform".to_owned()))?;
|
||||
remote_base
|
||||
.checked_add(total)
|
||||
.ok_or_else(|| NixlError::Token("remote address exceeds the platform".to_owned()))?;
|
||||
let arena_base = source.arena.buffer.addr();
|
||||
for (local_offset, len) in &source.ranges {
|
||||
if local_offset.checked_add(*len).is_none_or(|end| end > source.arena.len) {
|
||||
@@ -937,13 +903,7 @@ impl Engine {
|
||||
}
|
||||
|
||||
fn admit(&self, mut job: Job, pending: &mut Vec<Pending>, remotes: &mut remotes::RemoteCache) {
|
||||
let lease = match remotes.acquire(
|
||||
&self.agent,
|
||||
job.token.role,
|
||||
&job.token.agent,
|
||||
job.token.metadata.as_deref(),
|
||||
job.token.expected_metadata_sha256,
|
||||
) {
|
||||
let lease = match remotes.acquire(&self.agent, &job.token.agent, job.token.metadata.as_deref()) {
|
||||
Ok(lease) => lease,
|
||||
Err(error) => {
|
||||
job.completion.fail(error);
|
||||
@@ -1124,7 +1084,6 @@ mod tests {
|
||||
#[test]
|
||||
fn client_window_checks_the_buffer_bounds() {
|
||||
let token = RdmaToken::from_headers("a", None, "dram:0:1000:100").expect("token");
|
||||
assert_eq!(token.role(), PeerRole::S3Client);
|
||||
assert_eq!(NixlServer::client_window(&token, 40, 60).expect("fits"), 1040);
|
||||
assert!(matches!(
|
||||
NixlServer::client_window(&token, 50, 60),
|
||||
@@ -1134,20 +1093,4 @@ mod tests {
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internode_token_requires_metadata_and_binds_signed_digest() {
|
||||
let raw_md = b"rustfs-peer-1:ib0";
|
||||
let encoded_md = base64_simd::STANDARD.encode_to_string(raw_md);
|
||||
let digest = [0x5a; 32];
|
||||
|
||||
let token =
|
||||
RdmaToken::for_internode("rustfs-peer-1", &encoded_md, digest, "dram:0:0x1000:4096").expect("valid internode token");
|
||||
assert_eq!(token.role(), PeerRole::Internode);
|
||||
assert_eq!(token.expected_metadata_sha256, Some(digest));
|
||||
assert_eq!(token.metadata.as_deref(), Some(&raw_md[..]));
|
||||
|
||||
assert!(RdmaToken::for_internode("rustfs-peer-1", "", digest, "dram:0:0x1000:4096").is_err());
|
||||
assert!(RdmaToken::for_internode("rustfs-peer-1", " ", digest, "dram:0:0x1000:4096").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+20
-88
@@ -1,24 +1,14 @@
|
||||
//! Native peer registrations owned by one NIXL completion thread.
|
||||
|
||||
use super::{Agent, NIXL_METADATA_HEADER, NixlError, nixl_err};
|
||||
use super::{Agent, NIXL_METADATA_HEADER, NixlError, metadata_hash, nixl_err};
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const IDLE_TTL: Duration = Duration::from_secs(300);
|
||||
pub(super) const SWEEP_INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Trust domain of a remote NIXL agent registration.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PeerRole {
|
||||
/// External S3-over-RDMA client (`x-rustfs-nixl-*` headers).
|
||||
S3Client,
|
||||
/// Authenticated cluster peer (`read_file_nixl` / `write_file_nixl`).
|
||||
Internode,
|
||||
}
|
||||
|
||||
pub(super) trait MetadataRegistry {
|
||||
fn load(&self, bytes: &[u8]) -> Result<String, NixlError>;
|
||||
fn unload(&self, name: &str) -> Result<(), NixlError>;
|
||||
@@ -36,9 +26,7 @@ impl MetadataRegistry for Agent {
|
||||
}
|
||||
|
||||
struct Peer {
|
||||
role: PeerRole,
|
||||
metadata: Option<Arc<[u8]>>,
|
||||
signed_digest: Option<[u8; 32]>,
|
||||
hash: Option<u64>,
|
||||
idle_since: Rc<Cell<Instant>>,
|
||||
}
|
||||
|
||||
@@ -47,15 +35,6 @@ impl Peer {
|
||||
Rc::strong_count(&self.idle_since) == 1
|
||||
}
|
||||
|
||||
fn is_fresh(&self) -> bool {
|
||||
self.metadata.is_some()
|
||||
}
|
||||
|
||||
fn clear_fresh(&mut self) {
|
||||
self.metadata = None;
|
||||
self.signed_digest = None;
|
||||
}
|
||||
|
||||
fn acquire(&self) -> RemoteLease {
|
||||
RemoteLease(Rc::clone(&self.idle_since))
|
||||
}
|
||||
@@ -93,59 +72,32 @@ impl RemoteCache {
|
||||
pub(super) fn acquire(
|
||||
&mut self,
|
||||
registry: &impl MetadataRegistry,
|
||||
role: PeerRole,
|
||||
name: &str,
|
||||
metadata: Option<&[u8]>,
|
||||
expected_digest: Option<[u8; 32]>,
|
||||
) -> Result<RemoteLease, NixlError> {
|
||||
if role == PeerRole::Internode && expected_digest.is_none() {
|
||||
return Err(NixlError::Token(
|
||||
"internode agent registration requires a signed metadata digest".to_owned(),
|
||||
));
|
||||
}
|
||||
|
||||
let hash = metadata.map(metadata_hash);
|
||||
if let Some(peer) = self.peers.get(name) {
|
||||
if peer.role != role {
|
||||
// An S3 client must never reuse, evict, or collide with a cluster peer.
|
||||
// Conversely, an authenticated internode peer preempts an idle S3 squatter.
|
||||
if role == PeerRole::S3Client {
|
||||
return Err(NixlError::Token(format!("agent {name:?} is reserved for internode transport")));
|
||||
}
|
||||
if !peer.idle() {
|
||||
return Err(NixlError::Token(format!("agent {name:?} has active transfers under another role")));
|
||||
}
|
||||
} else if let Some(cached) = peer.metadata.as_deref() {
|
||||
let expected_matches = role != PeerRole::Internode || peer.signed_digest == expected_digest;
|
||||
if expected_matches && metadata.is_none_or(|incoming| incoming == cached) {
|
||||
return Ok(peer.acquire());
|
||||
}
|
||||
if !expected_matches && metadata.is_none() {
|
||||
return Err(NixlError::Token("agent metadata digest mismatch".to_owned()));
|
||||
}
|
||||
if !peer.idle() {
|
||||
return Err(NixlError::Token("peer metadata changed while transfers are active".to_owned()));
|
||||
}
|
||||
} else if !peer.idle() {
|
||||
if peer.hash.is_some() && (hash.is_none() || hash == peer.hash) {
|
||||
return Ok(peer.acquire());
|
||||
}
|
||||
if !peer.idle() {
|
||||
return Err(NixlError::Token("peer metadata changed while transfers are active".to_owned()));
|
||||
}
|
||||
self.evict(registry, name)?;
|
||||
}
|
||||
|
||||
let metadata = metadata.ok_or_else(|| NixlError::Token(format!("agent {name:?} needs {NIXL_METADATA_HEADER}")))?;
|
||||
// Retry outstanding cleanup before loading another registration.
|
||||
self.trim_stale(registry)?;
|
||||
self.trim(registry, |peer| peer.hash.is_none())?;
|
||||
let loaded = registry.load(metadata)?;
|
||||
if loaded != name {
|
||||
if let Some(peer) = self.peers.get_mut(&loaded) {
|
||||
// Native loads can merge descriptors into an existing registration.
|
||||
peer.clear_fresh();
|
||||
peer.hash = None;
|
||||
} else if let Err(error) = registry.unload(&loaded) {
|
||||
self.peers.insert(
|
||||
loaded,
|
||||
Peer {
|
||||
role,
|
||||
metadata: None,
|
||||
signed_digest: None,
|
||||
hash: None,
|
||||
idle_since: Rc::new(Cell::new(Instant::now())),
|
||||
},
|
||||
);
|
||||
@@ -154,43 +106,23 @@ impl RemoteCache {
|
||||
return Err(NixlError::Token(format!("metadata belongs to agent {loaded:?}, request names {name:?}")));
|
||||
}
|
||||
let peer = Peer {
|
||||
role,
|
||||
metadata: Some(Arc::from(metadata)),
|
||||
signed_digest: if role == PeerRole::Internode { expected_digest } else { None },
|
||||
hash,
|
||||
idle_since: Rc::new(Cell::new(Instant::now())),
|
||||
};
|
||||
let lease = peer.acquire();
|
||||
self.peers.insert(loaded, peer);
|
||||
// Only a successful registration displaces an idle peer of the same role.
|
||||
// Failed cleanup leaves the victim stale for the next admission or periodic sweep.
|
||||
let _ = self.trim_role(registry, role);
|
||||
// Only a successful registration displaces an idle peer. Failed cleanup
|
||||
// leaves the victim stale for the next admission or periodic sweep.
|
||||
let _ = self.trim(registry, |_| true);
|
||||
Ok(lease)
|
||||
}
|
||||
|
||||
fn trim_stale(&mut self, registry: &impl MetadataRegistry) -> Result<(), NixlError> {
|
||||
if let Some((stale, _)) = self
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|(_, peer)| peer.idle() && !peer.is_fresh())
|
||||
.min_by_key(|(_, peer)| peer.idle_since.get())
|
||||
{
|
||||
let stale = stale.clone();
|
||||
self.evict(registry, &stale)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trim_role(&mut self, registry: &impl MetadataRegistry, role: PeerRole) -> Result<(), NixlError> {
|
||||
let role_count = self
|
||||
.peers
|
||||
.values()
|
||||
.filter(|peer| peer.role == role && peer.is_fresh())
|
||||
.count();
|
||||
if role_count > self.capacity
|
||||
fn trim(&mut self, registry: &impl MetadataRegistry, eligible: impl Fn(&Peer) -> bool) -> Result<(), NixlError> {
|
||||
if self.peers.len() > self.capacity
|
||||
&& let Some((oldest, _)) = self
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|(_, peer)| peer.idle() && peer.role == role && peer.is_fresh())
|
||||
.filter(|(_, peer)| peer.idle() && eligible(peer))
|
||||
.min_by_key(|(_, peer)| peer.idle_since.get())
|
||||
{
|
||||
let oldest = oldest.clone();
|
||||
@@ -210,16 +142,16 @@ impl RemoteCache {
|
||||
|
||||
pub(super) fn mark_stale(&mut self, name: &str) {
|
||||
if let Some(peer) = self.peers.get_mut(name) {
|
||||
peer.clear_fresh();
|
||||
peer.hash = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sweep(&mut self, registry: &impl MetadataRegistry, now: Instant) {
|
||||
self.peers.retain(|name, peer| {
|
||||
if !peer.idle() || (peer.is_fresh() && now.duration_since(peer.idle_since.get()) < IDLE_TTL) {
|
||||
if !peer.idle() || (peer.hash.is_some() && now.duration_since(peer.idle_since.get()) < IDLE_TTL) {
|
||||
return true;
|
||||
}
|
||||
peer.clear_fresh();
|
||||
peer.hash = None;
|
||||
registry.unload(name).is_err()
|
||||
});
|
||||
}
|
||||
|
||||
@@ -35,36 +35,18 @@ impl MetadataRegistry for Registry {
|
||||
fn pressure_and_expiry_skip_live_transfers_and_unload_native_metadata() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(2);
|
||||
let active = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("pin a");
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "b", Some(b"b"), None)
|
||||
.expect("cache b"),
|
||||
);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "c", Some(b"c"), None)
|
||||
.expect("evict b"),
|
||||
);
|
||||
let active = cache.acquire(&backend, "a", Some(b"a")).expect("pin a");
|
||||
drop(cache.acquire(&backend, "b", Some(b"b")).expect("cache b"));
|
||||
drop(cache.acquire(&backend, "c", Some(b"c")).expect("evict b"));
|
||||
assert!(!backend.peers.borrow().contains("b"));
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "b", None, None).is_err());
|
||||
assert!(cache.acquire(&backend, "b", None).is_err());
|
||||
let later = Instant::now() + IDLE_TTL;
|
||||
cache.sweep(&backend, later);
|
||||
assert_eq!(*backend.peers.borrow(), HashSet::from(["a".to_owned()]));
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a:new"), None)
|
||||
.is_err()
|
||||
);
|
||||
assert!(cache.acquire(&backend, "a", Some(b"a:new")).is_err());
|
||||
drop(active);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a:new"), None)
|
||||
.expect("replace idle generation"),
|
||||
);
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_ok());
|
||||
drop(cache.acquire(&backend, "a", Some(b"a:new")).expect("replace idle generation"));
|
||||
assert!(cache.acquire(&backend, "a", None).is_ok());
|
||||
cache.sweep(&backend, later + IDLE_TTL);
|
||||
assert!(backend.peers.borrow().is_empty());
|
||||
}
|
||||
@@ -73,23 +55,13 @@ fn pressure_and_expiry_skip_live_transfers_and_unload_native_metadata() {
|
||||
fn a_failed_transfer_requires_fresh_metadata_after_its_siblings_finish() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(2);
|
||||
let active = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("in flight");
|
||||
let active = cache.acquire(&backend, "a", Some(b"a")).expect("in flight");
|
||||
cache.mark_stale("a");
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None).is_err());
|
||||
assert!(cache.acquire(&backend, "a", None).is_err());
|
||||
assert!(cache.acquire(&backend, "a", Some(b"a")).is_err());
|
||||
drop(active);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("reconnect"),
|
||||
);
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "wrong", Some(b"another"), None)
|
||||
.is_err()
|
||||
);
|
||||
drop(cache.acquire(&backend, "a", Some(b"a")).expect("reconnect"));
|
||||
assert!(cache.acquire(&backend, "wrong", Some(b"another")).is_err());
|
||||
assert!(!backend.peers.borrow().contains("another"));
|
||||
}
|
||||
|
||||
@@ -97,36 +69,20 @@ fn a_failed_transfer_requires_fresh_metadata_after_its_siblings_finish() {
|
||||
fn failed_eviction_cannot_reuse_a_partially_invalidated_registration() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(1);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("initial registration"),
|
||||
);
|
||||
drop(cache.acquire(&backend, "a", Some(b"a")).expect("initial registration"));
|
||||
backend.fail_next_unload.set(true);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "b", Some(b"b"), None)
|
||||
.expect("new registration is usable"),
|
||||
);
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "b", None, None).is_ok());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_err());
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("reload peer"),
|
||||
);
|
||||
drop(cache.acquire(&backend, "b", Some(b"b")).expect("new registration is usable"));
|
||||
assert!(cache.acquire(&backend, "b", None).is_ok());
|
||||
assert!(cache.acquire(&backend, "a", None).is_err());
|
||||
drop(cache.acquire(&backend, "a", Some(b"a")).expect("reload peer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_lifetime_starts_after_the_last_native_request_finishes() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(2);
|
||||
let first = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("first lease");
|
||||
let last = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", None, None)
|
||||
.expect("second lease");
|
||||
let first = cache.acquire(&backend, "a", Some(b"a")).unwrap();
|
||||
let last = cache.acquire(&backend, "a", None).unwrap();
|
||||
// The last idle timestamp predates both transfers.
|
||||
last.0.set(Instant::now() - IDLE_TTL - SWEEP_INTERVAL);
|
||||
drop(first);
|
||||
@@ -134,7 +90,7 @@ fn idle_lifetime_starts_after_the_last_native_request_finishes() {
|
||||
assert!(backend.peers.borrow().contains("a"));
|
||||
drop(last);
|
||||
cache.sweep(&backend, Instant::now() + SWEEP_INTERVAL);
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_ok());
|
||||
assert!(cache.acquire(&backend, "a", None).is_ok());
|
||||
cache.sweep(&backend, Instant::now() + IDLE_TTL);
|
||||
assert!(backend.peers.borrow().is_empty());
|
||||
}
|
||||
@@ -143,17 +99,13 @@ fn idle_lifetime_starts_after_the_last_native_request_finishes() {
|
||||
fn unsuccessful_registration_preserves_idle_peers_at_capacity() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(1);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("cache a"),
|
||||
);
|
||||
drop(cache.acquire(&backend, "a", Some(b"a")).expect("cache a"));
|
||||
|
||||
backend.fail_next_load.set(true);
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "b", Some(b"b"), None).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_ok());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "b", Some(b"c"), None).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_ok());
|
||||
assert!(cache.acquire(&backend, "b", Some(b"b")).is_err());
|
||||
assert!(cache.acquire(&backend, "a", None).is_ok());
|
||||
assert!(cache.acquire(&backend, "b", Some(b"c")).is_err());
|
||||
assert!(cache.acquire(&backend, "a", None).is_ok());
|
||||
assert_eq!(*backend.peers.borrow(), HashSet::from(["a".to_owned()]));
|
||||
}
|
||||
|
||||
@@ -161,92 +113,11 @@ fn unsuccessful_registration_preserves_idle_peers_at_capacity() {
|
||||
fn unexpected_loaded_name_requires_a_refresh_after_its_transfers_finish() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(2);
|
||||
let active = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("pin a");
|
||||
let active = cache.acquire(&backend, "a", Some(b"a")).expect("pin a");
|
||||
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "b", Some(b"a:new"), None)
|
||||
.is_err()
|
||||
);
|
||||
assert!(cache.acquire(&backend, "b", Some(b"a:new")).is_err());
|
||||
assert!(backend.peers.borrow().contains("a"));
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_err());
|
||||
assert!(cache.acquire(&backend, "a", None).is_err());
|
||||
drop(active);
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internode_peers_require_signed_digests_and_resist_s3_client_collisions_or_eviction() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(1);
|
||||
let peer_md = b"rustfs-node1:rail0";
|
||||
let peer_digest = [0x11; 32];
|
||||
let wrong_digest = [0x22; 32];
|
||||
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", Some(peer_md), None)
|
||||
.is_err(),
|
||||
"internode registrations must require a signed digest"
|
||||
);
|
||||
|
||||
// Pre-existing idle S3 squatter is preempted by an authenticated internode peer.
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "rustfs-node1", Some(b"rustfs-node1:squatter"), None)
|
||||
.expect("s3 squatter"),
|
||||
);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", Some(peer_md), Some(peer_digest))
|
||||
.expect("authenticated internode peer preempts idle squatter"),
|
||||
);
|
||||
|
||||
// An S3 client cannot overwrite, reuse, or evict an internode registration.
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "rustfs-node1", Some(b"rustfs-node1:attacker"), None)
|
||||
.is_err(),
|
||||
"s3 client must not overwrite internode peer"
|
||||
);
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "rustfs-node1", None, None)
|
||||
.is_err(),
|
||||
"s3 client must not reuse internode peer"
|
||||
);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "client-1", Some(b"client-1"), None)
|
||||
.expect("s3 client 1"),
|
||||
);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "client-2", Some(b"client-2"), None)
|
||||
.expect("s3 client 2 evicts client-1, not internode peer"),
|
||||
);
|
||||
assert!(backend.peers.borrow().contains("rustfs-node1"));
|
||||
assert!(!backend.peers.borrow().contains("client-1"));
|
||||
|
||||
// Cached internode lookup enforces the signed digest without evicting the valid peer.
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", None, Some(wrong_digest))
|
||||
.is_err(),
|
||||
"cached internode lookup must reject mismatched digest"
|
||||
);
|
||||
assert!(backend.peers.borrow().contains("rustfs-node1"));
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", None, Some(peer_digest))
|
||||
.is_ok(),
|
||||
"cached internode lookup with matching digest succeeds"
|
||||
);
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", Some(peer_md), Some(peer_digest))
|
||||
.is_ok(),
|
||||
"cached internode lookup with matching metadata and digest reuses registration"
|
||||
);
|
||||
assert!(cache.acquire(&backend, "a", Some(b"a")).is_ok());
|
||||
}
|
||||
|
||||
@@ -169,24 +169,34 @@ Refreshing only dirty disks is safe only when:
|
||||
|
||||
- `disk_cache_complete == true`
|
||||
- which means the system has already completed at least one full refresh without partial errors
|
||||
- and the per-disk cache covers the current local disk set
|
||||
- and the per-disk cache is fully populated
|
||||
|
||||
The first refresh builds an aggregate baseline. Scheduled refreshes stay idle when there are no dirty disks and the baseline still applies. A change in local disk membership triggers a full refresh, including replacements that keep the same disk count. Dirty disks with an incomplete per-disk baseline also trigger a full refresh.
|
||||
If no aggregate cache exists yet, the system performs a full refresh to establish an initial value. Once an aggregate cache exists, a scheduled refresh with no dirty disks stays idle instead of repeatedly walking unchanged disks. If disks are dirty while the per-disk cache is incomplete, the system performs a full refresh because a subset cannot be merged safely.
|
||||
|
||||
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. A bounded or degraded full refresh after a topology change discards the old per-disk baseline and publishes the available current aggregate. A timeout estimate acknowledges dirty marks that predate the scan. Marks recorded during the scan remain pending.
|
||||
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. That bounded estimate acknowledges dirty marks that predate the scan, while marks recorded during the scan remain pending. This prevents one old dirty mark from causing an endless timeout loop without treating the estimate as exact.
|
||||
|
||||
### Merge Rules After a Subset Refresh
|
||||
|
||||
- On a successful full refresh, `per_disk` replaces the entire `disk_cache`.
|
||||
- On a successful dirty-subset refresh, only the affected per-disk entries are updated.
|
||||
- The total capacity is recomputed from the updated `disk_cache` instead of trusting the subset sum directly.
|
||||
- If a dirty-subset refresh reports partial errors, that cycle fails and preserves the last published cache and pending dirty marks.
|
||||
- If a dirty-subset refresh reports partial errors, that cycle fails and the caller falls back to a full refresh to recover consistency.
|
||||
|
||||
## Relationship to the RustFS Main Flow
|
||||
|
||||
`rustfs/src/capacity/service.rs` starts the background capacity manager with a provider that discovers local disks on each scheduled refresh. The manager publishes the cached estimate as `rustfs_capacity_current_bytes`. The admin storage usage view comes from the storage information API.
|
||||
This crate provides capacity primitives only. The actual RustFS integration lives in `rustfs/src/capacity/service.rs`.
|
||||
|
||||
`crates/ecstore/src/set_disk/mod.rs` records capacity scopes so object writes, heal operations, and data movement can mark affected disks dirty.
|
||||
The high-level flow is:
|
||||
|
||||
1. Startup calls `init_capacity_management_for_local_disks()`.
|
||||
2. It collects all local disks and calls `capacity_manager::start_background_task(...)`.
|
||||
3. Admin used-capacity queries first try the `HybridCapacityManager` cache.
|
||||
4. If the cache is fresh enough, the cached value is returned directly.
|
||||
5. If the cache is stale but still acceptable, the stale value is served and a background refresh is triggered.
|
||||
6. If the cache is very stale and the write rate is high, the request blocks on a foreground refresh.
|
||||
7. If the initial real-time scan fails, the service falls back to externally supplied disk-used capacity and stores it as `Fallback`.
|
||||
|
||||
`crates/ecstore/src/set_disk.rs` is responsible for recording capacity scopes during object writes, heal operations, data movement, and related flows, so this crate can learn which disks were affected.
|
||||
|
||||
## Public API
|
||||
|
||||
@@ -278,7 +288,6 @@ The configuration constants are defined in `crates/config/src/constants/capacity
|
||||
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | Cache age required before fast refresh is considered |
|
||||
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | Exact-count file threshold |
|
||||
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Base scan timeout |
|
||||
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | On Linux, use filesystem-reported used space on eligible dedicated drive mounts |
|
||||
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | Overflow-file sampling interval |
|
||||
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | Runtime summary emission interval |
|
||||
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | Whether to follow symlinks |
|
||||
@@ -287,8 +296,6 @@ The configuration constants are defined in `crates/config/src/constants/capacity
|
||||
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Dynamic-timeout upper bound |
|
||||
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | Stall-detection threshold |
|
||||
|
||||
On Linux, `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true` enables direct readings on whole XFS, ext-family, and tmpfs mounts used exclusively by RustFS. The fast path requires kernel mount IDs and the process mount table. A symlink used as the drive root resolves to its target. Subdirectory bind mounts, multiple views of a device, mounts with child mounts, and pooled filesystems such as Btrfs or ZFS use directory scanning. The reading estimates used capacity from allocated filesystem blocks, which can include metadata and differ from summed file lengths. Direct readings do not count files. When a directory scan in this mode times out, it estimates usage from available file samples. Other platforms and configurations that follow symlinks within the drive use the default scan behavior. Restart RustFS after changing this setting.
|
||||
|
||||
Explicit `RUSTFS_CAPACITY_STAT_TIMEOUT` and `RUSTFS_CAPACITY_MAX_TIMEOUT` values
|
||||
take precedence over the drive-timeout profile.
|
||||
|
||||
|
||||
@@ -169,24 +169,34 @@ crate 不是“超时就直接失败”的设计:
|
||||
|
||||
- `disk_cache_complete == true`
|
||||
- 也就是系统已经完成过一次“无部分错误”的全盘刷新
|
||||
- 并且每盘缓存覆盖当前本地盘集合
|
||||
- 并且成功拿到了每盘缓存
|
||||
|
||||
首次刷新会建立聚合基线。没有脏盘且原基线仍适用时,定时刷新保持空闲。本地盘成员变化时触发全量刷新,包括盘数相同的替换。存在脏盘但每盘基线不完整时,也执行全量刷新。
|
||||
若当前还没有任何聚合缓存,系统会先执行一次全盘刷新来建立初始值。已有聚合缓存后,定时刷新在没有脏盘时会保持 idle,不再重复遍历未变化的磁盘。若 per-disk cache 尚不完整但存在脏盘,系统仍执行全盘刷新,因为此时不能安全合并子集结果。
|
||||
|
||||
全盘刷新达到时间预算后,可以发布估算聚合值。拓扑变化后的全量刷新若超时或降级,会丢弃旧的每盘基线,并发布当前可用的聚合值。超时估算会确认扫描开始前的脏标记,扫描过程中记录的新标记仍会保留。
|
||||
全盘刷新达到时间预算后,可以发布估算聚合值,但不会借此建立完整 per-disk 基线。该有界估算会确认扫描开始前的脏标记;扫描过程中记录的新标记仍会保留。这样既不会把估算值当成精确值,也不会让一个旧脏标记永久触发超时循环。
|
||||
|
||||
### 子集刷新后的合并规则
|
||||
|
||||
- 全盘刷新成功时,`per_disk` 会完整替换 `disk_cache`。
|
||||
- dirty subset 刷新成功时,只更新对应脏盘的缓存条目。
|
||||
- 总容量会基于更新后的 `disk_cache` 重新求和,而不是盲信子集扫描返回的局部和。
|
||||
- 若脏盘子集刷新出现部分错误,则本轮失败,保留上次发布的缓存和待处理脏标记。
|
||||
- 若 dirty subset 刷新出现 partial errors,则当前轮次失败,并回退到全盘刷新恢复一致性。
|
||||
|
||||
## 与 RustFS 主流程的关系
|
||||
|
||||
`rustfs/src/capacity/service.rs` 启动后台容量管理器,并在每轮定时刷新时发现当前本地盘。管理器通过 `rustfs_capacity_current_bytes` 发布缓存的容量估算值。管理接口的存储用量取自存储信息 API。
|
||||
这个 crate 本身只提供容量能力,真正把它接到 RustFS 主流程的是 `rustfs/src/capacity/service.rs`。
|
||||
|
||||
`crates/ecstore/src/set_disk/mod.rs` 记录容量作用域,以便对象写入、修复和数据迁移标记受影响的磁盘。
|
||||
上层使用方式大致如下:
|
||||
|
||||
1. 启动时调用 `init_capacity_management_for_local_disks()`。
|
||||
2. 它收集所有本地盘,调用 `capacity_manager::start_background_task(...)`。
|
||||
3. 管理接口查询 used capacity 时,优先读 `HybridCapacityManager` 缓存。
|
||||
4. 缓存足够新时直接返回。
|
||||
5. 缓存过旧但还可容忍时,先返回 stale cache,再后台刷新。
|
||||
6. 缓存极旧且写入频率高时,前台阻塞刷新。
|
||||
7. 若首次实时扫描失败,则退回外部已有的磁盘 used capacity,并写入 `Fallback` 缓存。
|
||||
|
||||
`crates/ecstore/src/set_disk.rs` 中则负责在对象写入、heal、data movement 等流程里记录 capacity scope,把“这次写影响了哪些盘”传播给本 crate。
|
||||
|
||||
## 公开 API
|
||||
|
||||
@@ -278,7 +288,6 @@ get_capacity_manager()
|
||||
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | 缓存超过该年龄后才考虑快速刷新 |
|
||||
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | 精确统计文件数阈值 |
|
||||
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` | 基础扫描超时 |
|
||||
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | 在 Linux 上直接读取符合条件的独占挂载用量 |
|
||||
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | overflow 文件采样间隔 |
|
||||
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | runtime summary 打点间隔 |
|
||||
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | 是否跟随符号链接 |
|
||||
@@ -287,8 +296,6 @@ get_capacity_manager()
|
||||
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` | 动态超时上界 |
|
||||
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | 无进展 stall 判定阈值 |
|
||||
|
||||
在 Linux 上设置 `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true`,可直接读取 RustFS 独占的 XFS、ext 系列和 tmpfs 整卷挂载。快速路径依赖内核挂载 ID 和进程挂载表,磁盘根路径是符号链接时会解析到目标。子目录 bind mount、同一设备的多个挂载视图、带子挂载的卷,以及 Btrfs、ZFS 等共享池文件系统走目录扫描。直接读取按已分配块估算容量,可能包含元数据,也可能与文件长度之和不同,无文件计数。此模式下目录扫描超时时,使用已有的文件样本估算。其他平台或启用盘内符号链接跟随时走默认扫描。更改设置后需重启 RustFS。
|
||||
|
||||
### 配置缓存注意事项
|
||||
|
||||
在非测试构建中,配置通过 `OnceLock` 缓存:
|
||||
|
||||
@@ -29,8 +29,6 @@ use rustfs_config::{
|
||||
ENV_CAPACITY_STAT_TIMEOUT, ENV_CAPACITY_WRITE_FREQUENCY_THRESHOLD, ENV_CAPACITY_WRITE_TRIGGER_DELAY,
|
||||
ENV_DRIVE_TIMEOUT_PROFILE,
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
use rustfs_config::{DEFAULT_CAPACITY_USE_MOUNT_USAGE, ENV_CAPACITY_USE_MOUNT_USAGE};
|
||||
use rustfs_io_metrics::capacity_metrics::{
|
||||
record_capacity_current_bytes, record_capacity_degraded_reading, record_capacity_dirty_disk_count,
|
||||
record_capacity_refresh_inflight, record_capacity_refresh_joiner, record_capacity_refresh_result,
|
||||
@@ -88,8 +86,6 @@ struct CachedCapacityConfig {
|
||||
metrics_interval: Duration,
|
||||
/// Follow symlinks flag
|
||||
follow_symlinks: bool,
|
||||
#[cfg(target_os = "linux")]
|
||||
use_mount_usage: bool,
|
||||
/// Enable dynamic timeout flag
|
||||
enable_dynamic_timeout: bool,
|
||||
/// Min timeout
|
||||
@@ -157,8 +153,6 @@ impl CachedCapacityConfig {
|
||||
DEFAULT_CAPACITY_METRICS_INTERVAL_SECS,
|
||||
)),
|
||||
follow_symlinks: get_env_bool(ENV_CAPACITY_FOLLOW_SYMLINKS, DEFAULT_CAPACITY_FOLLOW_SYMLINKS),
|
||||
#[cfg(target_os = "linux")]
|
||||
use_mount_usage: get_env_bool(ENV_CAPACITY_USE_MOUNT_USAGE, DEFAULT_CAPACITY_USE_MOUNT_USAGE),
|
||||
enable_dynamic_timeout: get_env_bool(ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT, DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT),
|
||||
min_timeout: Duration::from_secs(env_u64_at_least(ENV_CAPACITY_MIN_TIMEOUT, DEFAULT_CAPACITY_MIN_TIMEOUT_SECS, 1)),
|
||||
max_timeout: Duration::from_secs(env_u64_at_least(
|
||||
@@ -291,11 +285,6 @@ pub fn get_follow_symlinks() -> bool {
|
||||
get_cached_config().follow_symlinks
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn get_use_mount_usage() -> bool {
|
||||
get_cached_config().use_mount_usage
|
||||
}
|
||||
|
||||
/// Get enable dynamic timeout flag from environment or default
|
||||
#[cfg(not(test))]
|
||||
pub fn get_enable_dynamic_timeout() -> bool {
|
||||
@@ -364,7 +353,8 @@ pub struct CapacityUpdate {
|
||||
/// Whether the value is estimated instead of exact.
|
||||
pub is_estimated: bool,
|
||||
/// Whether the refresh behind this update had partial disk failures.
|
||||
/// Independent of `is_estimated`, which describes how bytes were measured.
|
||||
/// `is_estimated` only reflects sampling; this flag is the only carrier of
|
||||
/// the "some disks failed to scan" fact (backlog#1014).
|
||||
pub degraded: bool,
|
||||
/// Whether the scan reached its time budget and returned a fallback estimate.
|
||||
pub timed_out: bool,
|
||||
@@ -764,6 +754,7 @@ pub struct HybridCapacityManager {
|
||||
/// Per-disk cache populated after a successful full refresh and updated by dirty subset refreshes.
|
||||
disk_cache: Arc<RwLock<HashMap<CapacityScopeDisk, CachedDiskCapacity>>>,
|
||||
/// Whether the per-disk cache currently covers all known disks.
|
||||
disk_cache_complete: Arc<RwLock<bool>>,
|
||||
/// Configuration
|
||||
config: HybridStrategyConfig,
|
||||
/// Shared singleflight refresh state
|
||||
@@ -796,6 +787,7 @@ impl HybridCapacityManager {
|
||||
write_record: Arc::new(WriteRecord::new()),
|
||||
dirty_disks: Arc::new(RwLock::new(HashMap::new())),
|
||||
disk_cache: Arc::new(RwLock::new(HashMap::new())),
|
||||
disk_cache_complete: Arc::new(RwLock::new(false)),
|
||||
config,
|
||||
refresh_state: Arc::new(Mutex::new(RefreshState::default())),
|
||||
}
|
||||
@@ -819,46 +811,18 @@ impl HybridCapacityManager {
|
||||
/// only the scanned subset's totals; callers that publish or return this value (e.g. the
|
||||
/// `refresh_or_join` leader and joiners, admin used-capacity) must use the reconciled copy
|
||||
/// so they never report the subset bytes as the whole-cluster total.
|
||||
pub async fn update_capacity(&self, update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
|
||||
self.commit_capacity(update, source, None).await
|
||||
}
|
||||
|
||||
async fn commit_capacity(
|
||||
&self,
|
||||
mut update: CapacityUpdate,
|
||||
source: DataSource,
|
||||
full_scan_disks: Option<&[CapacityDiskRef]>,
|
||||
) -> CapacityUpdate {
|
||||
pub async fn update_capacity(&self, mut update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
|
||||
let start = Instant::now();
|
||||
|
||||
if !update.per_disk.is_empty() || update.degraded {
|
||||
let mut disk_cache = self.disk_cache.write().await;
|
||||
let replaces_cache = !update.per_disk.is_empty()
|
||||
&& update.replaces_disk_cache
|
||||
&& update.expected_disk_count == Some(update.per_disk.len());
|
||||
if replaces_cache {
|
||||
disk_cache.clear();
|
||||
} else if !disk_cache.is_empty()
|
||||
&& let Some(disks) = full_scan_disks
|
||||
{
|
||||
// A bounded full scan may publish bytes without establishing a
|
||||
// baseline. Do not merge a previous topology into that result.
|
||||
let local: HashSet<_> = disks
|
||||
.iter()
|
||||
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
|
||||
.collect();
|
||||
if disk_cache.len() != local.len()
|
||||
|| !disk_cache
|
||||
.keys()
|
||||
.all(|disk| local.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
|
||||
{
|
||||
disk_cache.clear();
|
||||
}
|
||||
}
|
||||
let mut disk_cache_complete = self.disk_cache_complete.write().await;
|
||||
|
||||
// A nonempty disk cache always covers one complete topology. A
|
||||
// degraded refresh on that topology keeps last-known disk entries.
|
||||
if replaces_cache || !disk_cache.is_empty() {
|
||||
let recompute = if !update.per_disk.is_empty()
|
||||
&& update.replaces_disk_cache
|
||||
&& update.expected_disk_count == Some(update.per_disk.len())
|
||||
{
|
||||
disk_cache.clear();
|
||||
for entry in &update.per_disk {
|
||||
disk_cache.insert(
|
||||
entry.disk.clone(),
|
||||
@@ -869,12 +833,35 @@ impl HybridCapacityManager {
|
||||
},
|
||||
);
|
||||
}
|
||||
let (bytes, files, estimated) = disk_cache.values().fold((0, 0, false), |(bytes, files, estimated), entry| {
|
||||
(bytes + entry.used_bytes, files + entry.file_count, estimated || entry.is_estimated)
|
||||
});
|
||||
update.total_used = bytes;
|
||||
update.file_count = files;
|
||||
update.is_estimated = estimated;
|
||||
*disk_cache_complete = true;
|
||||
true
|
||||
} else if *disk_cache_complete {
|
||||
// Merging over a complete cache also covers a degraded
|
||||
// (partial-failure) full refresh: successfully scanned disks
|
||||
// are refreshed while failed disks keep their last-known
|
||||
// values, so the published total does not dip to the
|
||||
// surviving-subset sum and bounce back on the next refresh.
|
||||
for entry in &update.per_disk {
|
||||
disk_cache.insert(
|
||||
entry.disk.clone(),
|
||||
CachedDiskCapacity {
|
||||
used_bytes: entry.used_bytes,
|
||||
file_count: entry.file_count,
|
||||
is_estimated: entry.is_estimated,
|
||||
},
|
||||
);
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if recompute {
|
||||
// Reconcile cluster-wide aggregates from the full per-disk cache so a
|
||||
// dirty-subset refresh reports the merged cluster totals, not the subset sum.
|
||||
update.total_used = disk_cache.values().map(|entry| entry.used_bytes).sum();
|
||||
update.file_count = disk_cache.values().map(|entry| entry.file_count).sum();
|
||||
update.is_estimated = disk_cache.values().any(|entry| entry.is_estimated);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1064,33 +1051,15 @@ impl HybridCapacityManager {
|
||||
|
||||
/// Returns true if the manager has a complete per-disk cache and can safely refresh only dirty disks.
|
||||
pub async fn can_refresh_dirty_subset(&self) -> bool {
|
||||
!self.disk_cache.read().await.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) async fn disk_cache_matches(&self, local: &HashSet<CapacityScopeDisk>) -> Option<bool> {
|
||||
let cache = self.disk_cache.read().await;
|
||||
(!cache.is_empty()).then(|| cache.len() == local.len() && cache.keys().all(|disk| local.contains(disk)))
|
||||
*self.disk_cache_complete.read().await
|
||||
}
|
||||
|
||||
/// Run a singleflight refresh. Callers either join an existing in-flight refresh or become the leader.
|
||||
///
|
||||
/// Joiners subscribe to the watch channel *before* releasing the mutex, which guarantees
|
||||
/// they cannot miss the completion notification even if the leader finishes very quickly.
|
||||
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Result<CapacityUpdate, String>>,
|
||||
{
|
||||
self.refresh_or_join_for_disks(source, None, refresh_fn).await
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
async fn refresh_or_join_for_disks<F, Fut>(
|
||||
&self,
|
||||
source: DataSource,
|
||||
full_scan_disks: Option<&[CapacityDiskRef]>,
|
||||
refresh_fn: F,
|
||||
) -> Result<CapacityUpdate, String>
|
||||
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Result<CapacityUpdate, String>>,
|
||||
@@ -1172,7 +1141,7 @@ impl HybridCapacityManager {
|
||||
// returned to this caller and the one published to joiners carry the cluster totals
|
||||
// rather than a dirty-subset's partial bytes.
|
||||
let result = match result {
|
||||
Ok(update) => Ok(self.commit_capacity(update, source, full_scan_disks).await),
|
||||
Ok(update) => Ok(self.update_capacity(update, source).await),
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
let refresh_duration = refresh_start.elapsed();
|
||||
@@ -1458,8 +1427,8 @@ async fn run_scheduled_capacity_refresh(manager: Arc<HybridCapacityManager>, dis
|
||||
"capacity refresh scheduled"
|
||||
);
|
||||
let result = manager
|
||||
.refresh_or_join_for_disks(DataSource::Scheduled, (!dirty_subset).then_some(disks.as_slice()), || {
|
||||
refresh_capacity_with_scope(&disks, dirty_subset)
|
||||
.refresh_or_join(DataSource::Scheduled, move || async move {
|
||||
refresh_capacity_with_scope(disks, dirty_subset).await
|
||||
})
|
||||
.await;
|
||||
scheduled_refresh_was_clean(&result)
|
||||
@@ -2507,84 +2476,6 @@ mod tests {
|
||||
assert!(!cached.degraded);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_degraded_refresh_after_replacement_drops_retired_capacity() {
|
||||
let manager = create_isolated_manager(HybridStrategyConfig::default());
|
||||
let temp = tempfile::TempDir::new().expect("create capacity fixture");
|
||||
let active = temp.path().join("active");
|
||||
let replacement = temp.path().join("replacement");
|
||||
std::fs::create_dir(&active).expect("create active disk");
|
||||
std::fs::write(active.join("object"), b"abc").expect("write active disk data");
|
||||
let active = active.to_str().expect("UTF-8 active path");
|
||||
let replacement_path = replacement.to_str().expect("UTF-8 replacement path");
|
||||
let mut old = full_two_disk_update();
|
||||
old.per_disk[0] = disk_entry("active", active, 100, 1);
|
||||
manager.update_capacity(old, DataSource::Scheduled).await;
|
||||
|
||||
let current = vec![
|
||||
CapacityDiskRef {
|
||||
endpoint: "active".into(),
|
||||
drive_path: active.into(),
|
||||
},
|
||||
CapacityDiskRef {
|
||||
endpoint: "replacement".into(),
|
||||
drive_path: replacement_path.into(),
|
||||
},
|
||||
];
|
||||
assert!(!run_scheduled_capacity_refresh(manager.clone(), current.clone()).await);
|
||||
let published = manager.get_capacity().await.expect("publish degraded refresh");
|
||||
assert!(published.degraded);
|
||||
assert_eq!(published.total_used, 3);
|
||||
assert!(!manager.can_refresh_dirty_subset().await);
|
||||
assert_eq!(
|
||||
select_scheduled_capacity_refresh(&manager, ¤t).await,
|
||||
ScheduledCapacityRefresh::Idle
|
||||
);
|
||||
|
||||
std::fs::create_dir(&replacement).expect("make replacement readable");
|
||||
std::fs::write(replacement.join("object"), b"12345").expect("write replacement disk data");
|
||||
manager
|
||||
.mark_dirty_scope(&CapacityScope {
|
||||
disks: vec![scope_disk("replacement", replacement_path)],
|
||||
})
|
||||
.await;
|
||||
assert!(run_scheduled_capacity_refresh(manager.clone(), current).await);
|
||||
let published = manager.get_capacity().await.expect("publish recovered refresh");
|
||||
assert_eq!(published.total_used, 8);
|
||||
assert!(!published.degraded);
|
||||
assert!(manager.can_refresh_dirty_subset().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_timed_out_full_refresh_after_replacement_uses_current_estimate() {
|
||||
let manager = create_isolated_manager(HybridStrategyConfig::default());
|
||||
manager.update_capacity(full_two_disk_update(), DataSource::Scheduled).await;
|
||||
let current = [
|
||||
CapacityDiskRef {
|
||||
endpoint: "node-a".into(),
|
||||
drive_path: "/tmp/disk-a".into(),
|
||||
},
|
||||
CapacityDiskRef {
|
||||
endpoint: "node-c".into(),
|
||||
drive_path: "/tmp/disk-c".into(),
|
||||
},
|
||||
];
|
||||
let mut timed_out = CapacityUpdate::estimated(160, 2);
|
||||
timed_out.timed_out = true;
|
||||
timed_out.per_disk = vec![
|
||||
disk_entry("node-a", "/tmp/disk-a", 60, 1),
|
||||
disk_entry("node-c", "/tmp/disk-c", 100, 1),
|
||||
];
|
||||
let published = manager
|
||||
.refresh_or_join_for_disks(DataSource::Scheduled, Some(¤t), || async { Ok(timed_out) })
|
||||
.await
|
||||
.expect("publish bounded full refresh");
|
||||
assert_eq!(published.total_used, 160);
|
||||
assert!(published.timed_out);
|
||||
assert!(published.is_estimated);
|
||||
assert!(!manager.can_refresh_dirty_subset().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_update_capacity_degraded_with_empty_per_disk_serves_merged_cache() {
|
||||
let manager = create_isolated_manager(HybridStrategyConfig::default());
|
||||
|
||||
@@ -12,8 +12,6 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::capacity_manager::get_use_mount_usage;
|
||||
use super::capacity_manager::{
|
||||
CapacityUpdate, DiskCapacityUpdate, HybridCapacityManager, get_enable_dynamic_timeout, get_follow_symlinks,
|
||||
get_max_files_threshold, get_max_timeout, get_min_timeout, get_sample_rate, get_stat_timeout,
|
||||
@@ -25,8 +23,6 @@ use rustfs_io_metrics::capacity_metrics::{
|
||||
record_capacity_dynamic_timeout, record_capacity_scan_disk, record_capacity_scan_mode, record_capacity_scan_sampling,
|
||||
record_capacity_timeout_fallback,
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
use rustfs_utils::os::MountUsageSnapshot;
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsStr;
|
||||
use std::path::{Component, Path};
|
||||
@@ -202,10 +198,10 @@ fn is_tmp_trash_metadata_not_found(scan_root: &Path, entry_path: &Path, error_ki
|
||||
&& components.all(|component| matches!(component, Component::Normal(_)))
|
||||
}
|
||||
|
||||
async fn scan_disk_used_capacity(disk: CapacityDiskRef, limits: ScanLimits) -> DiskScanOutcome {
|
||||
async fn scan_disk_used_capacity(disk: CapacityDiskRef) -> DiskScanOutcome {
|
||||
let disk_label = disk_metric_label(&disk);
|
||||
let start = Instant::now();
|
||||
let result = get_dir_size_async(Path::new(&disk.drive_path), limits).await;
|
||||
let result = get_dir_size_async(Path::new(&disk.drive_path)).await;
|
||||
let disk = CapacityScopeDisk {
|
||||
endpoint: disk.endpoint,
|
||||
drive_path: disk.drive_path,
|
||||
@@ -236,14 +232,7 @@ async fn calculate_data_dir_used_capacity_report(
|
||||
let mut per_disk = Vec::with_capacity(disks.len());
|
||||
|
||||
let concurrency_limit = disks.len().clamp(1, MAX_CAPACITY_SCAN_CONCURRENCY);
|
||||
let limits = ScanLimits::from_env();
|
||||
let mut scans = stream::iter(
|
||||
disks
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|disk| scan_disk_used_capacity(disk, limits.clone())),
|
||||
)
|
||||
.buffer_unordered(concurrency_limit);
|
||||
let mut scans = stream::iter(disks.iter().cloned().map(scan_disk_used_capacity)).buffer_unordered(concurrency_limit);
|
||||
|
||||
while let Some(outcome) = scans.next().await {
|
||||
match outcome.result {
|
||||
@@ -362,43 +351,38 @@ pub(crate) async fn select_scheduled_capacity_refresh(
|
||||
// entries so the dirty gauge reflects local pending work (backlog#1020).
|
||||
let local_set: HashSet<CapacityScopeDisk> = disks.iter().map(disk_scope_key).collect();
|
||||
capacity_manager.retain_dirty_disks_within(&local_set).await;
|
||||
if disks.is_empty() {
|
||||
return ScheduledCapacityRefresh::Idle;
|
||||
}
|
||||
|
||||
let full_scan = || ScheduledCapacityRefresh::Scan {
|
||||
disks: disks.to_vec(),
|
||||
dirty_subset: false,
|
||||
};
|
||||
let cached_topology_matches = capacity_manager.disk_cache_matches(&local_set).await;
|
||||
if cached_topology_matches == Some(false) {
|
||||
return full_scan();
|
||||
}
|
||||
let dirty_disks = capacity_manager.get_dirty_disks().await;
|
||||
if dirty_disks.is_empty() {
|
||||
return if capacity_manager.get_capacity().await.is_some() {
|
||||
return if disks.is_empty() || capacity_manager.get_capacity().await.is_some() {
|
||||
ScheduledCapacityRefresh::Idle
|
||||
} else {
|
||||
full_scan()
|
||||
ScheduledCapacityRefresh::Scan {
|
||||
disks: disks.to_vec(),
|
||||
dirty_subset: false,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if cached_topology_matches.is_none() {
|
||||
return full_scan();
|
||||
if !capacity_manager.can_refresh_dirty_subset().await {
|
||||
return ScheduledCapacityRefresh::Scan {
|
||||
disks: disks.to_vec(),
|
||||
dirty_subset: false,
|
||||
};
|
||||
}
|
||||
|
||||
let dirty_set: HashSet<_> = dirty_disks
|
||||
.iter()
|
||||
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
|
||||
.collect();
|
||||
let dirty_set: HashSet<CapacityScopeDisk> = dirty_disks.into_iter().collect();
|
||||
let selected: Vec<_> = disks
|
||||
.iter()
|
||||
.filter(|disk| dirty_set.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
|
||||
.filter(|disk| dirty_set.contains(&disk_scope_key(disk)))
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if selected.is_empty() || selected.len() >= disks.len() {
|
||||
full_scan()
|
||||
ScheduledCapacityRefresh::Scan {
|
||||
disks: disks.to_vec(),
|
||||
dirty_subset: false,
|
||||
}
|
||||
} else {
|
||||
ScheduledCapacityRefresh::Scan {
|
||||
disks: selected,
|
||||
@@ -420,13 +404,9 @@ pub async fn select_capacity_refresh_disks(
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
pub async fn refresh_capacity_with_scope(
|
||||
disks: impl AsRef<[CapacityDiskRef]>,
|
||||
dirty_subset: bool,
|
||||
) -> Result<CapacityUpdate, String> {
|
||||
let disks = disks.as_ref();
|
||||
pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subset: bool) -> Result<CapacityUpdate, String> {
|
||||
let scan_started_at = Instant::now();
|
||||
let report = calculate_data_dir_used_capacity_report(disks)
|
||||
let report = calculate_data_dir_used_capacity_report(&disks)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -441,8 +421,8 @@ pub async fn refresh_capacity_with_scope(
|
||||
|
||||
/// Scan the provided local disk roots and return a summarized used-capacity result.
|
||||
///
|
||||
/// This is intended for benchmarks and operational tooling that need the same scan path
|
||||
/// as background capacity refreshes. Direct filesystem readings do not count files.
|
||||
/// This is primarily intended for benchmarks and operational tooling that need to exercise
|
||||
/// the same scan path as admin capacity queries without going through the full admin stack.
|
||||
pub async fn scan_used_capacity_disks(
|
||||
disks: &[CapacityDiskRef],
|
||||
) -> Result<CapacityScanSummary, Box<dyn std::error::Error + Send + Sync>> {
|
||||
@@ -571,8 +551,6 @@ struct ScanLimits {
|
||||
sample_rate: usize,
|
||||
enable_dynamic_timeout: bool,
|
||||
follow_symlinks: bool,
|
||||
#[cfg(target_os = "linux")]
|
||||
mount_usage: Option<Arc<MountUsageSnapshot>>,
|
||||
}
|
||||
|
||||
impl ScanLimits {
|
||||
@@ -594,7 +572,6 @@ impl ScanLimits {
|
||||
sample_rate
|
||||
};
|
||||
|
||||
let follow_symlinks = get_follow_symlinks();
|
||||
Self {
|
||||
max_files_threshold: get_max_files_threshold(),
|
||||
base_timeout: get_stat_timeout(),
|
||||
@@ -602,15 +579,15 @@ impl ScanLimits {
|
||||
max_timeout: get_max_timeout(),
|
||||
sample_rate: effective_sample_rate,
|
||||
enable_dynamic_timeout: get_enable_dynamic_timeout(),
|
||||
follow_symlinks,
|
||||
#[cfg(target_os = "linux")]
|
||||
mount_usage: (get_use_mount_usage() && !follow_symlinks).then(|| Arc::new(MountUsageSnapshot::default())),
|
||||
follow_symlinks: get_follow_symlinks(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Filesystem usage at a device boundary. This check cannot establish sole
|
||||
/// ownership or distinguish a whole filesystem from a cross-device bind mount.
|
||||
/// Filesystem-level used bytes for `path`, only when `path` is a dedicated
|
||||
/// mount point. On a shared filesystem (several logical disks per filesystem,
|
||||
/// common in dev deployments) statvfs counts unrelated data and would badly
|
||||
/// overcount, so `None` is returned and callers keep scan-based estimates.
|
||||
fn mount_point_used_bytes(path: &Path) -> Option<u64> {
|
||||
let parent = path.parent()?;
|
||||
let dedicated = !rustfs_utils::os::same_disk(path.to_str()?, parent.to_str()?).ok()?;
|
||||
@@ -647,7 +624,7 @@ fn combine_timeout_estimates(seen_estimate: Option<u64>, disk_used: Option<u64>,
|
||||
/// then propagates the original error, as before.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn timeout_fallback_estimate(
|
||||
fallback_mount_path: Option<&Path>,
|
||||
path: &Path,
|
||||
reason: &'static str,
|
||||
exact_prefix_bytes: u64,
|
||||
overflow_sampled_bytes: u64,
|
||||
@@ -662,7 +639,7 @@ fn timeout_fallback_estimate(
|
||||
let estimated_overflow = estimate_overflow_bytes(overflow_sampled_bytes, overflow_count as u64, sampled_count as u64);
|
||||
exact_prefix_bytes.saturating_add(estimated_overflow)
|
||||
});
|
||||
let disk_used = fallback_mount_path.and_then(mount_point_used_bytes);
|
||||
let disk_used = mount_point_used_bytes(path);
|
||||
let used_bytes = combine_timeout_estimates(seen_estimate, disk_used, exact_prefix_bytes)?;
|
||||
|
||||
info!(
|
||||
@@ -722,8 +699,9 @@ impl Drop for ScanCancellationGuard {
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityScanResult, std::io::Error> {
|
||||
async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::Error> {
|
||||
let path = path.to_path_buf();
|
||||
let limits = ScanLimits::from_env();
|
||||
let budget = outer_scan_budget(&limits);
|
||||
|
||||
// The blocking thread cannot be killed; on ceiling expiry the caller (and
|
||||
@@ -756,13 +734,6 @@ async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityS
|
||||
}
|
||||
|
||||
fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -> Result<CapacityScanResult, std::io::Error> {
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::TimedOut,
|
||||
"capacity scan cancelled before starting",
|
||||
));
|
||||
}
|
||||
|
||||
let ScanLimits {
|
||||
max_files_threshold,
|
||||
base_timeout,
|
||||
@@ -771,28 +742,13 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
|
||||
sample_rate: effective_sample_rate,
|
||||
enable_dynamic_timeout,
|
||||
follow_symlinks,
|
||||
..
|
||||
} = *limits;
|
||||
{
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(mount_usage) = &limits.mount_usage {
|
||||
let start_time = Instant::now();
|
||||
let used_bytes = mount_usage.used_bytes(path);
|
||||
if cancelled.load(Ordering::Relaxed) {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::TimedOut,
|
||||
"capacity scan cancelled while reading mount usage",
|
||||
));
|
||||
}
|
||||
if let Some(used_bytes) = used_bytes {
|
||||
record_capacity_scan_mode("mount_usage");
|
||||
return Ok(CapacityScanResult {
|
||||
used_bytes,
|
||||
is_estimated: true,
|
||||
scan_duration: start_time.elapsed(),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
if !path.exists() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
format!("Directory not found: {:?}", path),
|
||||
));
|
||||
}
|
||||
|
||||
// Resolve the scan root before walking. A drive_path that is itself a
|
||||
@@ -805,13 +761,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
|
||||
.map_err(|err| std::io::Error::new(err.kind(), format!("failed to resolve scan root {path:?}: {err}")))?;
|
||||
let path = resolved_root.as_path();
|
||||
|
||||
// Opt-in scans that rejected a mount must not count its whole filesystem on timeout.
|
||||
#[cfg(target_os = "linux")]
|
||||
let fallback_mount_path = limits.mount_usage.is_none().then_some(path);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let fallback_mount_path = Some(path);
|
||||
let start_time = Instant::now();
|
||||
|
||||
let mut exact_prefix_bytes = 0u64;
|
||||
let mut overflow_sampled_bytes = 0u64;
|
||||
let mut file_count = 0usize;
|
||||
@@ -866,7 +816,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
|
||||
Ok(half_elapsed) => half_elapsed,
|
||||
Err(e) => {
|
||||
if let Some(result) = timeout_fallback_estimate(
|
||||
fallback_mount_path,
|
||||
path,
|
||||
"timeout",
|
||||
exact_prefix_bytes,
|
||||
overflow_sampled_bytes,
|
||||
@@ -1039,7 +989,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
|
||||
|
||||
if let Err(e) = progress_monitor.update_and_check_timeout(file_count, avg_size) {
|
||||
if let Some(result) = timeout_fallback_estimate(
|
||||
fallback_mount_path,
|
||||
path,
|
||||
"final_timeout",
|
||||
exact_prefix_bytes,
|
||||
overflow_sampled_bytes,
|
||||
@@ -1270,8 +1220,6 @@ mod tests {
|
||||
sample_rate: 3,
|
||||
enable_dynamic_timeout: false,
|
||||
follow_symlinks: false,
|
||||
#[cfg(target_os = "linux")]
|
||||
mount_usage: None,
|
||||
};
|
||||
|
||||
let result =
|
||||
@@ -1288,7 +1236,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_timeout_fallback_is_marked_for_scheduler_backoff() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("capacity scan tempdir should be created");
|
||||
let result = timeout_fallback_estimate(Some(temp_dir.path()), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
|
||||
let result = timeout_fallback_estimate(temp_dir.path(), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
|
||||
.expect("sampled timeout should produce a fallback estimate");
|
||||
|
||||
assert!(result.timed_out);
|
||||
@@ -1300,7 +1248,7 @@ mod tests {
|
||||
use tempfile::TempDir;
|
||||
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
|
||||
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
|
||||
assert_eq!(size.used_bytes, 0);
|
||||
assert_eq!(size.file_count, 0);
|
||||
}
|
||||
@@ -1317,7 +1265,7 @@ mod tests {
|
||||
file.write_all(b"Hello, World!").unwrap();
|
||||
drop(file);
|
||||
|
||||
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
|
||||
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
|
||||
assert_eq!(size.used_bytes, 13);
|
||||
assert_eq!(size.file_count, 1);
|
||||
}
|
||||
@@ -1336,7 +1284,7 @@ mod tests {
|
||||
file.write_all(b"test").unwrap();
|
||||
}
|
||||
|
||||
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
|
||||
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
|
||||
assert_eq!(size.used_bytes, 40);
|
||||
assert_eq!(size.file_count, 10);
|
||||
}
|
||||
@@ -1361,14 +1309,14 @@ mod tests {
|
||||
f2.write_all(b"content2").unwrap();
|
||||
drop(f2);
|
||||
|
||||
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
|
||||
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
|
||||
assert_eq!(size.used_bytes, 16);
|
||||
assert_eq!(size.file_count, 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_dir_size_async_nonexistent_directory() {
|
||||
let result = get_dir_size_async(Path::new("/nonexistent/path"), ScanLimits::from_env()).await;
|
||||
let result = get_dir_size_async(Path::new("/nonexistent/path")).await;
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
@@ -1476,45 +1424,12 @@ mod tests {
|
||||
assert_eq!(combine_timeout_estimates(None, None, 40), None);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_mount_usage_keeps_directory_scan_on_shared_filesystem() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("create shared-filesystem scan root");
|
||||
std::fs::write(temp_dir.path().join("object"), b"object bytes").expect("write object fixture");
|
||||
let limits = ScanLimits {
|
||||
mount_usage: Some(Arc::new(MountUsageSnapshot::default())),
|
||||
..tight_limits(Duration::from_secs(60))
|
||||
};
|
||||
let scan = scan_dir_blocking(temp_dir.path(), &limits, &AtomicBool::new(false)).expect("scan shared directory");
|
||||
assert_eq!(scan.used_bytes, 12);
|
||||
assert_eq!(scan.file_count, 1);
|
||||
assert!(!scan.is_estimated);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_mount_usage_completes_without_walk_budget() {
|
||||
// Docker and normal Linux hosts mount /dev/shm as a separate tmpfs.
|
||||
let path = Path::new("/dev/shm");
|
||||
let mount_usage = Arc::new(MountUsageSnapshot::default());
|
||||
if mount_usage.used_bytes(path).is_none() {
|
||||
return;
|
||||
}
|
||||
let limits = ScanLimits {
|
||||
mount_usage: Some(mount_usage),
|
||||
..tight_limits(Duration::ZERO)
|
||||
};
|
||||
let temp_dir = tempfile::TempDir::new().expect("create symlink fixture directory");
|
||||
let drive_link = temp_dir.path().join("drive");
|
||||
std::os::unix::fs::symlink(path, &drive_link).expect("link to mount root");
|
||||
for root in [path, drive_link.as_path()] {
|
||||
let scan = scan_dir_blocking(root, &limits, &AtomicBool::new(false)).expect("read usage at a mount root");
|
||||
assert!(scan.is_estimated);
|
||||
assert!(!scan.timed_out);
|
||||
assert!(!scan.metadata_incomplete);
|
||||
assert_eq!(scan.file_count, 0);
|
||||
assert_eq!(scan.metadata_reads, 0);
|
||||
}
|
||||
fn test_mount_point_used_bytes_rejects_shared_filesystem_path() {
|
||||
// A tempdir lives on the same filesystem as its parent, so statvfs
|
||||
// must not be trusted as a per-disk proxy there.
|
||||
let temp_dir = tempfile::TempDir::new().unwrap();
|
||||
assert_eq!(mount_point_used_bytes(temp_dir.path()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1537,8 +1452,6 @@ mod tests {
|
||||
sample_rate: 1,
|
||||
enable_dynamic_timeout: false,
|
||||
follow_symlinks: false,
|
||||
#[cfg(target_os = "linux")]
|
||||
mount_usage: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1938,35 +1851,6 @@ mod tests {
|
||||
assert_eq!(selected.len(), 1);
|
||||
assert_eq!(selected[0].endpoint, "disk-2");
|
||||
assert_eq!(selected[0].drive_path, "/tmp/disk-2");
|
||||
|
||||
let replacement = vec![
|
||||
disks[0].clone(),
|
||||
CapacityDiskRef {
|
||||
endpoint: "disk-3".into(),
|
||||
drive_path: "/tmp/disk-3".into(),
|
||||
},
|
||||
];
|
||||
// Replacing a disk changes membership even when the disk count stays
|
||||
// the same and the only dirty mark belonged to the removed disk.
|
||||
assert_eq!(
|
||||
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
|
||||
ScheduledCapacityRefresh::Scan {
|
||||
disks: replacement.clone(),
|
||||
dirty_subset: false,
|
||||
}
|
||||
);
|
||||
manager
|
||||
.mark_dirty_scope(&CapacityScope {
|
||||
disks: vec![disk_scope_key(&replacement[1])],
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
|
||||
ScheduledCapacityRefresh::Scan {
|
||||
disks: replacement,
|
||||
dirty_subset: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1985,7 +1869,7 @@ mod tests {
|
||||
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
|
||||
|
||||
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("false"))], async {
|
||||
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
|
||||
get_dir_size_async(scan_dir.path()).await
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -2010,7 +1894,7 @@ mod tests {
|
||||
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
|
||||
|
||||
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("true"))], async {
|
||||
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
|
||||
get_dir_size_async(scan_dir.path()).await
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -96,7 +96,4 @@ pub use system_process::{
|
||||
ProcessAttributeError, ProcessAttributes, ProcessStats, ProcessStatusType, collect_process_attributes,
|
||||
collect_process_metrics,
|
||||
};
|
||||
pub use tier::{
|
||||
TierInventoryEntry, TierRequestStats, TierTransitionLast24hEntry, TierUsageSnapshot, collect_tier_request_metrics,
|
||||
collect_tier_usage_metrics,
|
||||
};
|
||||
pub use tier::{TierRequestStats, collect_tier_request_metrics};
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Remote tier request, inventory, and rolling transition metrics collectors.
|
||||
//! Remote tier request metrics collector.
|
||||
|
||||
use crate::metrics::report::PrometheusMetric;
|
||||
use crate::metrics::schema::tier::*;
|
||||
@@ -25,38 +25,6 @@ pub struct TierRequestStats {
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
/// Cluster-wide stored inventory counters for one configured remote tier.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TierInventoryEntry {
|
||||
pub tier: String,
|
||||
pub tier_type: String,
|
||||
pub total_bytes: u64,
|
||||
pub objects_count: u64,
|
||||
pub versions_count: u64,
|
||||
}
|
||||
|
||||
/// Node-local rolling 24-hour transition counters for one configured remote tier.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TierTransitionLast24hEntry {
|
||||
pub tier: String,
|
||||
pub tier_type: String,
|
||||
pub total_bytes: u64,
|
||||
pub objects_count: u64,
|
||||
}
|
||||
|
||||
/// Snapshot of configured remote-tier inventory and rolling 24-hour transition activity.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct TierUsageSnapshot {
|
||||
/// Whether the persisted usage snapshot carries per-tier accounting.
|
||||
///
|
||||
/// When `false` (`not-accounted` or `unavailable`), per-tier inventory
|
||||
/// gauges are omitted so callers never mistake an unaccounted tier for an
|
||||
/// empty tier.
|
||||
pub inventory_accounted: bool,
|
||||
pub inventory: Vec<TierInventoryEntry>,
|
||||
pub transitions_last24h: Vec<TierTransitionLast24hEntry>,
|
||||
}
|
||||
|
||||
/// Split the fixed operation/outcome cells over the success and failure
|
||||
/// counters.
|
||||
///
|
||||
@@ -79,62 +47,6 @@ pub fn collect_tier_request_metrics(stats: &[TierRequestStats]) -> Vec<Prometheu
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Collect configured remote-tier inventory and node-local rolling 24-hour
|
||||
/// transition gauges.
|
||||
///
|
||||
/// Inventory gauges are emitted only when `snapshot.inventory_accounted` is
|
||||
/// `true`; an unaccounted or unavailable usage snapshot emits
|
||||
/// `rustfs_tier_inventory_accounted = 0` and omits per-tier inventory series
|
||||
/// rather than fabricating zeros.
|
||||
pub fn collect_tier_usage_metrics(snapshot: &TierUsageSnapshot) -> Vec<PrometheusMetric> {
|
||||
let inventory_len = if snapshot.inventory_accounted {
|
||||
snapshot.inventory.len() * 3
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut metrics = Vec::with_capacity(1 + inventory_len + snapshot.transitions_last24h.len() * 2);
|
||||
|
||||
metrics.push(PrometheusMetric::from_descriptor(
|
||||
&TIER_INVENTORY_ACCOUNTED_MD,
|
||||
if snapshot.inventory_accounted { 1.0 } else { 0.0 },
|
||||
));
|
||||
|
||||
if snapshot.inventory_accounted {
|
||||
for entry in &snapshot.inventory {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_BYTES_MD, entry.total_bytes as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_OBJECTS_COUNT_MD, entry.objects_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_VERSIONS_COUNT_MD, entry.versions_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for entry in &snapshot.transitions_last24h {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_TRANSITIONS_LAST24H_BYTES_MD, entry.total_bytes as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_TRANSITIONS_LAST24H_OBJECTS_COUNT_MD, entry.objects_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
metrics
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -181,114 +93,4 @@ mod tests {
|
||||
"the failure counter must keep the outcome that produced it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_metrics_emit_all_six_gauges_when_inventory_is_accounted() {
|
||||
let snapshot = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 12,
|
||||
versions_count: 15,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 3,
|
||||
}],
|
||||
};
|
||||
|
||||
let metrics = collect_tier_usage_metrics(&snapshot);
|
||||
assert_eq!(metrics.len(), 6);
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.all(|metric| metric.metric_type == crate::metrics::schema::MetricType::Gauge),
|
||||
"tier usage metrics must be gauges"
|
||||
);
|
||||
|
||||
let accounted = metrics
|
||||
.iter()
|
||||
.find(|metric| metric.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted status gauge must be emitted");
|
||||
assert_eq!(accounted.value, 1.0);
|
||||
assert!(accounted.labels.is_empty(), "accounted gauge is snapshot-level without tier label");
|
||||
|
||||
for (name, expected) in [
|
||||
("rustfs_tier_inventory_bytes", 4096.0),
|
||||
("rustfs_tier_inventory_objects_count", 12.0),
|
||||
("rustfs_tier_inventory_versions_count", 15.0),
|
||||
("rustfs_tier_transitions_last24h_bytes", 1024.0),
|
||||
("rustfs_tier_transitions_last24h_objects_count", 3.0),
|
||||
] {
|
||||
let metric = metrics
|
||||
.iter()
|
||||
.find(|m| m.name == name)
|
||||
.unwrap_or_else(|| panic!("expected metric {name} to be emitted"));
|
||||
assert_eq!(metric.value, expected, "unexpected value for {name}");
|
||||
assert!(
|
||||
metric.labels.iter().any(|(k, v)| *k == TIER_LABEL && v.as_ref() == "COLD"),
|
||||
"{name} must carry tier label"
|
||||
);
|
||||
assert!(
|
||||
metric.labels.iter().any(|(k, v)| *k == TIER_TYPE_LABEL && v.as_ref() == "s3"),
|
||||
"{name} must carry tier_type label"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_metrics_omit_inventory_gauges_when_unaccounted() {
|
||||
let snapshot = TierUsageSnapshot {
|
||||
inventory_accounted: false,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 12,
|
||||
versions_count: 15,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 512,
|
||||
objects_count: 2,
|
||||
}],
|
||||
};
|
||||
|
||||
let metrics = collect_tier_usage_metrics(&snapshot);
|
||||
|
||||
let accounted = metrics
|
||||
.iter()
|
||||
.find(|metric| metric.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted status gauge must be emitted when unaccounted");
|
||||
assert_eq!(accounted.value, 0.0);
|
||||
|
||||
for forbidden in [
|
||||
"rustfs_tier_inventory_bytes",
|
||||
"rustfs_tier_inventory_objects_count",
|
||||
"rustfs_tier_inventory_versions_count",
|
||||
] {
|
||||
assert!(
|
||||
metrics.iter().all(|metric| metric.name != forbidden),
|
||||
"{forbidden} must not be emitted when inventory_accounted is false"
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.any(|metric| metric.name == "rustfs_tier_transitions_last24h_bytes" && metric.value == 512.0),
|
||||
"node-local 24h transition bytes must remain populated when inventory is unaccounted"
|
||||
);
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.any(|metric| metric.name == "rustfs_tier_transitions_last24h_objects_count" && metric.value == 2.0),
|
||||
"node-local 24h transition object count must remain populated when inventory is unaccounted"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,10 +33,9 @@ pub use scheduler::{
|
||||
};
|
||||
pub(crate) use storage_api::metrics::{
|
||||
BucketOperations, BucketOptions, ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore,
|
||||
ObsTierCounter, StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
|
||||
obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity,
|
||||
obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_expiry_state_handle, obs_get_global_bucket_monitor,
|
||||
obs_get_quota_config, obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled,
|
||||
obs_load_compression_total_from_memory, obs_load_data_usage_from_backend, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
obs_transition_state_handle,
|
||||
};
|
||||
|
||||
@@ -78,7 +78,6 @@ use crate::metrics::collectors::{
|
||||
collect_resource_metrics,
|
||||
collect_scanner_runtime_metrics,
|
||||
collect_tier_request_metrics,
|
||||
collect_tier_usage_metrics,
|
||||
};
|
||||
use crate::metrics::config::{
|
||||
DEFAULT_AUDIT_METRICS_INTERVAL, DEFAULT_BUCKET_METRICS_INTERVAL, DEFAULT_BUCKET_REPLICATION_BANDWIDTH_METRICS_INTERVAL,
|
||||
@@ -141,10 +140,10 @@ use crate::metrics::schema::system_process::{PROCESS_EXECUTABLE_NAME_LABEL, PROC
|
||||
use crate::metrics::stats_collector::{
|
||||
ProcessMetricBundle, collect_api_request_stats, collect_bucket_replication_bandwidth_stats,
|
||||
collect_bucket_replication_stats_bundle, collect_bucket_stats, collect_cluster_config_stats,
|
||||
collect_cluster_storage_snapshot, collect_compression_cluster_stats, collect_disk_and_system_drive_runtime_stats,
|
||||
collect_host_network_stats, collect_iam_stats, collect_ilm_runtime_metric_stats, collect_internode_network_stats,
|
||||
collect_on_demand_migration_backfill_stats, collect_on_demand_migration_stats, collect_process_metric_bundle_with,
|
||||
collect_replication_stats, collect_scanner_runtime_metric_stats, collect_supplementary_usage_metric_stats,
|
||||
collect_cluster_storage_snapshot, collect_cluster_usage_metric_stats, collect_compression_cluster_stats,
|
||||
collect_disk_and_system_drive_runtime_stats, collect_host_network_stats, collect_iam_stats, collect_ilm_runtime_metric_stats,
|
||||
collect_internode_network_stats, collect_on_demand_migration_backfill_stats, collect_on_demand_migration_stats,
|
||||
collect_process_metric_bundle_with, collect_replication_stats, collect_scanner_runtime_metric_stats,
|
||||
collect_system_cpu_and_memory_stats_with, collect_tier_request_metric_stats,
|
||||
};
|
||||
use crate::metrics::storage_snapshot::StorageSnapshotMetrics;
|
||||
@@ -1615,7 +1614,6 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
let tombstone_cycles = config.replication_bandwidth_zero_tombstone_cycles;
|
||||
let mut has_seen_bucket_usage_snapshot = false;
|
||||
let mut bucket_usage_snapshot = bucket_metrics_snapshot(cluster_interval);
|
||||
let mut tier_usage_snapshot = bucket_metrics_snapshot(cluster_interval);
|
||||
let mut prev_bucket_usage_keys: HashSet<BucketKey> = HashSet::new();
|
||||
let mut bucket_usage_zero_tombstones: HashMap<BucketKey, u8> = HashMap::new();
|
||||
let mut prev_bucket_usage_object_size_keys: HashSet<BucketRangeKey> = HashSet::new();
|
||||
@@ -1642,8 +1640,7 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
}
|
||||
|
||||
let usage_collection_started = std::time::Instant::now();
|
||||
let (cluster_bucket_usage, tier_usage) = collect_supplementary_usage_metric_stats().await;
|
||||
if let Some((cluster_usage, bucket_usage)) = cluster_bucket_usage {
|
||||
if let Some((cluster_usage, bucket_usage)) = collect_cluster_usage_metric_stats().await {
|
||||
let mut usage_metrics = collect_cluster_usage_metrics(&cluster_usage);
|
||||
usage_metrics.extend(collect_bucket_usage_metrics(&bucket_usage));
|
||||
update_series_zero_tombstones(
|
||||
@@ -1684,11 +1681,6 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_bucket_snapshot", error = %error, "bucket usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
let tier_metrics = tier_usage.as_ref().map(collect_tier_usage_metrics).unwrap_or_default();
|
||||
if let Err(error) = tier_usage_snapshot.replace_collected(tier_metrics, usage_collection_started) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_tier_snapshot", error = %error, "tier usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
if !metrics.is_empty() {
|
||||
report_metrics(&metrics);
|
||||
}
|
||||
|
||||
@@ -135,15 +135,9 @@ pub enum MetricName {
|
||||
TransitionedObjects,
|
||||
TransitionedVersions,
|
||||
|
||||
// Tier metrics
|
||||
//Tier request metrics
|
||||
TierRequestsSuccess,
|
||||
TierRequestsFailure,
|
||||
TierInventoryBytes,
|
||||
TierInventoryObjectsCount,
|
||||
TierInventoryVersionsCount,
|
||||
TierInventoryAccounted,
|
||||
TierTransitionsLast24hBytes,
|
||||
TierTransitionsLast24hObjectsCount,
|
||||
|
||||
// KMS metrics
|
||||
KmsOnline,
|
||||
@@ -566,12 +560,6 @@ impl MetricName {
|
||||
|
||||
Self::TierRequestsSuccess => "requests_success",
|
||||
Self::TierRequestsFailure => "requests_failure",
|
||||
Self::TierInventoryBytes => "inventory_bytes",
|
||||
Self::TierInventoryObjectsCount => "inventory_objects_count",
|
||||
Self::TierInventoryVersionsCount => "inventory_versions_count",
|
||||
Self::TierInventoryAccounted => "inventory_accounted",
|
||||
Self::TierTransitionsLast24hBytes => "transitions_last24h_bytes",
|
||||
Self::TierTransitionsLast24hObjectsCount => "transitions_last24h_objects_count",
|
||||
|
||||
Self::KmsOnline => "online",
|
||||
Self::KmsRequestsSuccess => "request_success",
|
||||
|
||||
@@ -12,23 +12,17 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Remote tier metric descriptors.
|
||||
//! Remote tier request metric descriptors.
|
||||
//!
|
||||
//! Request counters (`rustfs_tier_requests_*`) keep a closed label set fixed by
|
||||
//! the operation and outcome enums so request hot paths never depend on tier
|
||||
//! names, endpoints, or object keys.
|
||||
//!
|
||||
//! Inventory and rolling 24-hour transition gauges are published from periodic
|
||||
//! snapshots and carry configured remote tier identity (`tier`, `tier_type`),
|
||||
//! never endpoints, credentials, or object keys.
|
||||
//! The label set is fixed by the operation and outcome enums the recording
|
||||
//! site uses, so the series count is bounded by construction and cannot grow
|
||||
//! with tier names, endpoints or object keys.
|
||||
|
||||
use crate::{MetricDescriptor, MetricName, new_counter_md, new_gauge_md, subsystems};
|
||||
use crate::{MetricDescriptor, MetricName, new_counter_md, subsystems};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
pub const OPERATION_LABEL: &str = "operation";
|
||||
pub const OUTCOME_LABEL: &str = "outcome";
|
||||
pub const TIER_LABEL: &str = "tier";
|
||||
pub const TIER_TYPE_LABEL: &str = "tier_type";
|
||||
|
||||
pub static TIER_REQUESTS_SUCCESS_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_counter_md(
|
||||
@@ -47,57 +41,3 @@ pub static TIER_REQUESTS_FAILURE_MD: LazyLock<MetricDescriptor> = LazyLock::new(
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_BYTES_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryBytes,
|
||||
"Cluster-wide logical bytes currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_OBJECTS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryObjectsCount,
|
||||
"Cluster-wide object count currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_VERSIONS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryVersionsCount,
|
||||
"Cluster-wide object version count currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_ACCOUNTED_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryAccounted,
|
||||
"Whether the persisted usage snapshot includes per-tier inventory accounting (1 = accounted, 0 = not-accounted or unavailable)",
|
||||
&[],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_TRANSITIONS_LAST24H_BYTES_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierTransitionsLast24hBytes,
|
||||
"Node-local logical bytes committed into a configured remote tier during the rolling 24-hour window",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_TRANSITIONS_LAST24H_OBJECTS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierTransitionsLast24hObjectsCount,
|
||||
"Node-local objects committed into a configured remote tier during the rolling 24-hour window",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -28,16 +28,15 @@ use crate::metrics::collectors::{
|
||||
DriveDetailedStats, DriveRuntimeDetailedStats, ErasureSetStats, HostNetworkStats, IamStats, IlmActionTaskStats,
|
||||
IlmBackpressureStats, IlmQueueTaskStats, IlmRuntimeStats, IlmStats, IlmTaskEventStats, MemoryStats, NetworkStats,
|
||||
OdmBackfillRuntimeStats, OnDemandMigrationBucketStats, ProcessStats, ProcessStatusType, ReplicationMetricsSnapshot,
|
||||
ResourceStats, ScannerRuntimeStats, ScannerStats, TierInventoryEntry, TierRequestStats, TierTransitionLast24hEntry,
|
||||
TierUsageSnapshot,
|
||||
ResourceStats, ScannerRuntimeStats, ScannerStats, TierRequestStats,
|
||||
};
|
||||
use crate::metrics::runtime_sources::{ObsIlmRuntimeSnapshot, bucket_monitor_handle, iam_metrics_snapshot, ilm_runtime_snapshot};
|
||||
use crate::metrics::{
|
||||
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
|
||||
StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_get_quota_config,
|
||||
obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, StorageAdminApi,
|
||||
obs_bucket_replication_stats_snapshot, obs_get_quota_config, obs_get_total_usable_capacity,
|
||||
obs_get_total_usable_capacity_free, obs_load_compression_total_from_memory, obs_load_data_usage_from_backend,
|
||||
obs_on_demand_migration_backfill_snapshot, obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot,
|
||||
obs_resolve_object_store_handle,
|
||||
};
|
||||
use crate::node_identity::current_local_node_identity;
|
||||
use jiff::Timestamp;
|
||||
@@ -77,7 +76,6 @@ struct ObsDataUsageInfo {
|
||||
delete_markers_total_count: u64,
|
||||
objects_total_size: u64,
|
||||
buckets_usage: HashMap<String, ObsBucketUsageInfo>,
|
||||
tier_stats: Option<HashMap<String, ObsTierCounter>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -132,22 +130,6 @@ async fn load_obs_data_usage_from_backend(store: Arc<ObsStore>) -> ObsEcstoreRes
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
tier_stats: data_usage.tier_stats.map(|all_tiers| {
|
||||
all_tiers
|
||||
.tiers
|
||||
.into_iter()
|
||||
.map(|(tier, stats)| {
|
||||
(
|
||||
tier,
|
||||
ObsTierCounter {
|
||||
total_size: stats.total_size,
|
||||
num_objects: stats.num_objects,
|
||||
num_versions: stats.num_versions,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1269,109 +1251,6 @@ pub async fn collect_cluster_usage_metric_stats() -> Option<(ClusterUsageStats,
|
||||
collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await
|
||||
}
|
||||
|
||||
/// Collect cluster/bucket usage and configured remote-tier usage from one
|
||||
/// shared backend data-usage snapshot read.
|
||||
///
|
||||
/// Remote-tier inventory is extracted before the bucket-namespace completeness
|
||||
/// check so OTLP tier metrics match `GET /rustfs/admin/v3/tier-stats`, and a
|
||||
/// backend usage read failure still yields `inventory_accounted = false` plus
|
||||
/// node-local 24-hour transition counters when remote tiers are configured.
|
||||
pub(crate) async fn collect_supplementary_usage_metric_stats()
|
||||
-> (Option<(ClusterUsageStats, Vec<BucketUsageStats>)>, Option<TierUsageSnapshot>) {
|
||||
let configured_tiers = obs_configured_remote_tier_types().await;
|
||||
let store = resolve_obs_object_store_handle();
|
||||
let data_usage = match store.as_ref() {
|
||||
Some(store) => load_obs_data_usage_from_backend(store.clone()).await.ok(),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let tier_usage = if configured_tiers.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let local_daily_stats = obs_local_tier_daily_stats();
|
||||
tier_usage_snapshot_from_parts(
|
||||
&configured_tiers,
|
||||
data_usage.as_ref().and_then(|usage| usage.tier_stats.as_ref()),
|
||||
&local_daily_stats,
|
||||
)
|
||||
};
|
||||
|
||||
let cluster_bucket_usage = match (store, data_usage) {
|
||||
(Some(store), Some(data_usage)) => {
|
||||
let bucket_namespace = store
|
||||
.list_bucket(&BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.map(|buckets| {
|
||||
buckets
|
||||
.into_iter()
|
||||
.filter(|bucket| !bucket.name.starts_with('.'))
|
||||
.map(|bucket| bucket.name)
|
||||
.collect::<HashSet<_>>()
|
||||
});
|
||||
match bucket_namespace {
|
||||
Some(bucket_namespace) => collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await,
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
(cluster_bucket_usage, tier_usage)
|
||||
}
|
||||
|
||||
fn tier_usage_snapshot_from_parts(
|
||||
configured_tiers: &HashMap<String, String>,
|
||||
data_usage_tier_stats: Option<&HashMap<String, ObsTierCounter>>,
|
||||
local_daily_stats: &HashMap<String, ObsTierCounter>,
|
||||
) -> Option<TierUsageSnapshot> {
|
||||
if configured_tiers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut tiers: Vec<(&str, &str)> = configured_tiers
|
||||
.iter()
|
||||
.map(|(name, tier_type)| (name.as_str(), tier_type.as_str()))
|
||||
.collect();
|
||||
tiers.sort_unstable_by(|a, b| a.0.cmp(b.0));
|
||||
|
||||
let inventory_accounted = data_usage_tier_stats.is_some();
|
||||
let mut inventory = Vec::new();
|
||||
let mut transitions_last24h = Vec::with_capacity(tiers.len());
|
||||
|
||||
for (tier, tier_type) in tiers {
|
||||
if let Some(inv_map) = data_usage_tier_stats
|
||||
&& let Some(stats) = inv_map.get(tier)
|
||||
{
|
||||
inventory.push(TierInventoryEntry {
|
||||
tier: tier.to_string(),
|
||||
tier_type: tier_type.to_string(),
|
||||
total_bytes: stats.total_size,
|
||||
objects_count: stats.num_objects,
|
||||
versions_count: stats.num_versions,
|
||||
});
|
||||
}
|
||||
|
||||
let daily = local_daily_stats.get(tier).copied().unwrap_or_default();
|
||||
transitions_last24h.push(TierTransitionLast24hEntry {
|
||||
tier: tier.to_string(),
|
||||
tier_type: tier_type.to_string(),
|
||||
total_bytes: daily.total_size,
|
||||
objects_count: daily.num_objects,
|
||||
});
|
||||
}
|
||||
|
||||
Some(TierUsageSnapshot {
|
||||
inventory_accounted,
|
||||
inventory,
|
||||
transitions_last24h,
|
||||
})
|
||||
}
|
||||
|
||||
async fn collect_cluster_usage_metric_stats_from_data_usage(
|
||||
data_usage: ObsDataUsageInfo,
|
||||
bucket_namespace: &HashSet<String>,
|
||||
@@ -2067,136 +1946,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_returns_none_when_no_remote_tiers_configured() {
|
||||
let configured = HashMap::new();
|
||||
let data_usage_tiers = HashMap::from([(
|
||||
"STANDARD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 4096,
|
||||
num_objects: 2,
|
||||
num_versions: 2,
|
||||
},
|
||||
)]);
|
||||
let daily = HashMap::new();
|
||||
|
||||
assert!(tier_usage_snapshot_from_parts(&configured, Some(&data_usage_tiers), &daily).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_excludes_local_classes_unconfigured_tiers_and_unscanned_zeros() {
|
||||
let configured = HashMap::from([
|
||||
("COLD".to_string(), "rustfs".to_string()),
|
||||
("ARCHIVE".to_string(), "s3".to_string()),
|
||||
]);
|
||||
let data_usage_tiers = HashMap::from([
|
||||
(
|
||||
"STANDARD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 99_999,
|
||||
num_objects: 99,
|
||||
num_versions: 120,
|
||||
},
|
||||
),
|
||||
(
|
||||
"REMOVED_TIER".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 8_192,
|
||||
num_objects: 4,
|
||||
num_versions: 4,
|
||||
},
|
||||
),
|
||||
(
|
||||
"ARCHIVE".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 2048,
|
||||
num_objects: 5,
|
||||
num_versions: 7,
|
||||
},
|
||||
),
|
||||
]);
|
||||
let daily = HashMap::from([
|
||||
(
|
||||
"ARCHIVE".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 512,
|
||||
num_objects: 1,
|
||||
num_versions: 1,
|
||||
},
|
||||
),
|
||||
(
|
||||
"REMOVED_TIER".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 128,
|
||||
num_objects: 1,
|
||||
num_versions: 1,
|
||||
},
|
||||
),
|
||||
]);
|
||||
|
||||
let snapshot = tier_usage_snapshot_from_parts(&configured, Some(&data_usage_tiers), &daily)
|
||||
.expect("configured remote tiers should yield a tier usage snapshot");
|
||||
|
||||
assert!(snapshot.inventory_accounted);
|
||||
assert_eq!(
|
||||
snapshot.inventory,
|
||||
vec![TierInventoryEntry {
|
||||
tier: "ARCHIVE".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 2048,
|
||||
objects_count: 5,
|
||||
versions_count: 7,
|
||||
}],
|
||||
"only accounted configured remote tiers must appear in inventory; local classes, removed tiers, and unscanned tiers must not"
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.transitions_last24h,
|
||||
vec![
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 512,
|
||||
objects_count: 1,
|
||||
},
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "rustfs".to_string(),
|
||||
total_bytes: 0,
|
||||
objects_count: 0,
|
||||
},
|
||||
],
|
||||
"all configured remote tiers should report deterministic sorted node-local 24h transitions"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_preserves_local_transitions_when_inventory_is_not_accounted() {
|
||||
let configured = HashMap::from([("COLD".to_string(), "s3".to_string())]);
|
||||
let daily = HashMap::from([(
|
||||
"COLD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 1024,
|
||||
num_objects: 2,
|
||||
num_versions: 3,
|
||||
},
|
||||
)]);
|
||||
|
||||
let snapshot = tier_usage_snapshot_from_parts(&configured, None, &daily)
|
||||
.expect("configured remote tier should still emit snapshot when usage is unaccounted");
|
||||
|
||||
assert!(!snapshot.inventory_accounted);
|
||||
assert!(snapshot.inventory.is_empty());
|
||||
assert_eq!(
|
||||
snapshot.transitions_last24h,
|
||||
vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 2,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cluster_config_stats_accept_homogeneous_backend_parities() {
|
||||
let stats = cluster_config_stats_from_backend_parities(Some(1), Some(2))
|
||||
|
||||
@@ -16,7 +16,6 @@ use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) use rustfs_ecstore::api::bucket::bandwidth::monitor::Monitor as ObsBucketBandwidthMonitor;
|
||||
use rustfs_ecstore::api::bucket::lifecycle::tier_last_day_stats::LastDayTierStats as ObsLastDayTierStats;
|
||||
pub(crate) use rustfs_ecstore::api::bucket::metadata_sys::get_quota_config as obs_get_quota_config;
|
||||
use rustfs_ecstore::api::bucket::replication::{
|
||||
BucketReplicationStats as SourceBucketReplicationStats, DurableMrfBucketBacklog, DurableMrfTargetBacklog,
|
||||
@@ -33,8 +32,7 @@ pub(crate) use rustfs_ecstore::api::data_usage::load_compression_total_from_memo
|
||||
pub(crate) use rustfs_ecstore::api::error::Result as ObsEcstoreResult;
|
||||
pub(crate) use rustfs_ecstore::api::runtime::{
|
||||
bucket_monitor as obs_get_global_bucket_monitor, expiry_state_handle as obs_expiry_state_handle,
|
||||
global_tier_config_mgr as obs_global_tier_config_mgr, object_store_handle as obs_resolve_object_store_handle,
|
||||
transition_state_handle as obs_transition_state_handle,
|
||||
object_store_handle as obs_resolve_object_store_handle, transition_state_handle as obs_transition_state_handle,
|
||||
};
|
||||
pub(crate) use rustfs_ecstore::api::storage::ECStore as ObsStore;
|
||||
use rustfs_storage_api as storage_contracts;
|
||||
@@ -536,54 +534,6 @@ pub(crate) async fn obs_replication_site_stats_snapshot(current_data_transfer_ra
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal counter tuple bridged from `ecstore` tier snapshots.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(crate) struct ObsTierCounter {
|
||||
pub(crate) total_size: u64,
|
||||
pub(crate) num_objects: u64,
|
||||
pub(crate) num_versions: u64,
|
||||
}
|
||||
|
||||
/// Snapshot configured remote tiers (`name -> lowercase tier_type`) without
|
||||
/// holding the tier config read lock across downstream work.
|
||||
pub(crate) async fn obs_configured_remote_tier_types() -> HashMap<String, String> {
|
||||
let tier_config_mgr = obs_global_tier_config_mgr();
|
||||
let guard = tier_config_mgr.read().await;
|
||||
guard
|
||||
.list_tiers()
|
||||
.into_iter()
|
||||
.map(|tier| (tier.name, tier.tier_type.as_lowercase()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Snapshot this node's rolling 24-hour tier transition counters, aged forward
|
||||
/// to the current UTC hour so expired bins drop out even when no new
|
||||
/// transitions have committed recently.
|
||||
pub(crate) fn obs_local_tier_daily_stats() -> HashMap<String, ObsTierCounter> {
|
||||
let now_ring = ObsLastDayTierStats::default();
|
||||
age_local_tier_daily_stats(obs_transition_state_handle().get_daily_all_tier_stats(), &now_ring)
|
||||
}
|
||||
|
||||
fn age_local_tier_daily_stats(
|
||||
stats: HashMap<String, ObsLastDayTierStats>,
|
||||
now_ring: &ObsLastDayTierStats,
|
||||
) -> HashMap<String, ObsTierCounter> {
|
||||
stats
|
||||
.into_iter()
|
||||
.map(|(tier, ring)| {
|
||||
let total = ring.merge(now_ring.clone()).total();
|
||||
(
|
||||
tier,
|
||||
ObsTierCounter {
|
||||
total_size: total.total_size,
|
||||
num_objects: total.num_objects,
|
||||
num_versions: total.num_versions,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -824,72 +774,17 @@ mod tests {
|
||||
assert_eq!(snapshot.durable_mrf_backlog_count, 0);
|
||||
assert_eq!(snapshot.durable_mrf_backlog_bytes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn age_local_tier_daily_stats_expires_bins_older_than_24_hours() {
|
||||
use rustfs_ecstore::api::bucket::lifecycle::tier_last_day_stats::TierDailyStatsWire;
|
||||
|
||||
let now_unix = 1_700_100_000_i64;
|
||||
let empty_bins = ObsLastDayTierStats::default().to_wire().bins;
|
||||
let now_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: empty_bins.clone(),
|
||||
updated_at_unix_secs: now_unix,
|
||||
})
|
||||
.expect("current reference ring should decode");
|
||||
|
||||
let mut stale_bins = empty_bins.clone();
|
||||
stale_bins[0].total_size = 4096;
|
||||
stale_bins[0].num_versions = 3;
|
||||
stale_bins[0].num_objects = 2;
|
||||
let stale_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: stale_bins,
|
||||
updated_at_unix_secs: now_unix - 25 * 3600,
|
||||
})
|
||||
.expect("stale ring should decode");
|
||||
|
||||
let fresh_updated = now_unix - 2 * 3600;
|
||||
let fresh_hour = usize::try_from((fresh_updated / 3600).rem_euclid(24)).expect("hour fits in usize");
|
||||
let mut fresh_bins = empty_bins;
|
||||
fresh_bins[fresh_hour].total_size = 2048;
|
||||
fresh_bins[fresh_hour].num_versions = 2;
|
||||
fresh_bins[fresh_hour].num_objects = 1;
|
||||
let fresh_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: fresh_bins,
|
||||
updated_at_unix_secs: fresh_updated,
|
||||
})
|
||||
.expect("fresh ring should decode");
|
||||
|
||||
let aged = age_local_tier_daily_stats(
|
||||
HashMap::from([("STALE".to_string(), stale_ring), ("FRESH".to_string(), fresh_ring)]),
|
||||
&now_ring,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
aged.get("STALE"),
|
||||
Some(&ObsTierCounter::default()),
|
||||
"bins older than 24h must age to zero"
|
||||
);
|
||||
assert_eq!(
|
||||
aged.get("FRESH"),
|
||||
Some(&ObsTierCounter {
|
||||
total_size: 2048,
|
||||
num_objects: 1,
|
||||
num_versions: 2,
|
||||
}),
|
||||
"recent bins still inside the 24h window must be preserved"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod metrics {
|
||||
pub(crate) use super::storage_contracts::{BucketOperations, BucketOptions, StorageAdminApi};
|
||||
|
||||
pub(crate) use super::{
|
||||
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
|
||||
obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_expiry_state_handle,
|
||||
obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity, obs_get_total_usable_capacity_free,
|
||||
obs_is_disk_compression_enabled, obs_load_compression_total_from_memory, obs_load_data_usage_from_backend,
|
||||
obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot, obs_on_demand_migration_snapshot,
|
||||
obs_replication_site_stats_snapshot, obs_resolve_object_store_handle, obs_transition_state_handle,
|
||||
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore,
|
||||
obs_bucket_replication_stats_snapshot, obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_quota_config,
|
||||
obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled,
|
||||
obs_load_compression_total_from_memory, obs_load_data_usage_from_backend, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
obs_transition_state_handle,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -471,187 +471,6 @@ mod tests {
|
||||
provider.shutdown().expect("shut down bucket usage test provider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_sdk_exports_tier_inventory_and_transitions_without_fabricating_zeros() {
|
||||
use crate::metrics::collectors::{
|
||||
TierInventoryEntry, TierTransitionLast24hEntry, TierUsageSnapshot, collect_tier_usage_metrics,
|
||||
};
|
||||
|
||||
let (provider, exporter, mut snapshot) = setup_unscoped();
|
||||
|
||||
let extract_tier_points = |points: &[ExportedPoint], metric_name: &str| {
|
||||
let mut entries = points
|
||||
.iter()
|
||||
.filter(|point| point.name == metric_name)
|
||||
.map(|point| {
|
||||
let tier = point
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|attr| attr.key.as_str() == "tier")
|
||||
.expect("tier metric must carry tier attribute")
|
||||
.value
|
||||
.to_string();
|
||||
let tier_type = point
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|attr| attr.key.as_str() == "tier_type")
|
||||
.expect("tier metric must carry tier_type attribute")
|
||||
.value
|
||||
.to_string();
|
||||
(tier, tier_type, point.value)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
entries
|
||||
};
|
||||
|
||||
// 1. Accounted snapshot with two configured remote tiers.
|
||||
let initial = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![
|
||||
TierInventoryEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 8192,
|
||||
objects_count: 4,
|
||||
versions_count: 6,
|
||||
},
|
||||
TierInventoryEntry {
|
||||
tier: "COLD".into(),
|
||||
tier_type: "rustfs".into(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 2,
|
||||
versions_count: 3,
|
||||
},
|
||||
],
|
||||
transitions_last24h: vec![
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 2048,
|
||||
objects_count: 1,
|
||||
},
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "COLD".into(),
|
||||
tier_type: "rustfs".into(),
|
||||
total_bytes: 0,
|
||||
objects_count: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&initial))
|
||||
.expect("publish initial tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
points
|
||||
.iter()
|
||||
.find(|point| point.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted gauge must be exported")
|
||||
.value,
|
||||
1.0
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_bytes"),
|
||||
vec![
|
||||
("ARCHIVE".into(), "s3".into(), 8192.0),
|
||||
("COLD".into(), "rustfs".into(), 4096.0),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_objects_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 4.0), ("COLD".into(), "rustfs".into(), 2.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_versions_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 6.0), ("COLD".into(), "rustfs".into(), 3.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 2048.0), ("COLD".into(), "rustfs".into(), 0.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_objects_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1.0), ("COLD".into(), "rustfs".into(), 0.0),]
|
||||
);
|
||||
|
||||
// 2. Removing COLD and decreasing ARCHIVE inventory stops exporting COLD immediately.
|
||||
let decreased = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 1,
|
||||
versions_count: 1,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 1,
|
||||
}],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&decreased))
|
||||
.expect("publish decreased tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1024.0)]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1024.0)]
|
||||
);
|
||||
|
||||
// 3. Becoming unaccounted flips accounted to 0 and withdraws inventory gauges without emitting zeros.
|
||||
let unaccounted = TierUsageSnapshot {
|
||||
inventory_accounted: false,
|
||||
inventory: Vec::new(),
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 512,
|
||||
objects_count: 1,
|
||||
}],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&unaccounted))
|
||||
.expect("publish unaccounted tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
points
|
||||
.iter()
|
||||
.find(|point| point.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted gauge must stay exported with value 0")
|
||||
.value,
|
||||
0.0
|
||||
);
|
||||
for metric_name in [
|
||||
"rustfs_tier_inventory_bytes",
|
||||
"rustfs_tier_inventory_objects_count",
|
||||
"rustfs_tier_inventory_versions_count",
|
||||
] {
|
||||
assert!(
|
||||
extract_tier_points(&points, metric_name).is_empty(),
|
||||
"{metric_name} must be withdrawn when inventory is unaccounted"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 512.0)]
|
||||
);
|
||||
|
||||
// 4. Removing the last configured tier withdraws all tier gauges cleanly.
|
||||
snapshot
|
||||
.replace(Vec::new())
|
||||
.expect("clear tier snapshot when no remote tiers remain");
|
||||
assert!(flush(&provider, &exporter).is_empty());
|
||||
|
||||
provider.shutdown().expect("shut down tier usage test provider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_or_stalled_collection_cannot_refresh_last_success_or_export_old_points() {
|
||||
let (provider, exporter, mut snapshot) = setup();
|
||||
|
||||
@@ -1025,7 +1025,6 @@ pub struct Metrics {
|
||||
current_scan_cycle_replication_checks_start: AtomicU64,
|
||||
current_scan_cycle_usage_saves_start: AtomicU64,
|
||||
scanner_set_scan_concurrency_limit: AtomicU64,
|
||||
last_scan_cycle_set_scan_concurrency_limit: AtomicU64,
|
||||
scanner_set_scans_queued: AtomicU64,
|
||||
scanner_set_scans_active: AtomicU64,
|
||||
scanner_disk_bucket_scan_states: Mutex<HashMap<ScannerDiskBucketScanKey, ScannerDiskBucketScanState>>,
|
||||
@@ -1561,8 +1560,6 @@ pub struct ScannerMetricsReport {
|
||||
#[serde(default)]
|
||||
pub current_set_scan_concurrency_limit: u64,
|
||||
#[serde(default)]
|
||||
pub last_cycle_set_scan_concurrency_limit: u64,
|
||||
#[serde(default)]
|
||||
pub current_set_scans_queued: u64,
|
||||
#[serde(default)]
|
||||
pub current_set_scans_active: u64,
|
||||
@@ -2249,7 +2246,6 @@ impl Metrics {
|
||||
current_scan_cycle_replication_checks_start: AtomicU64::new(0),
|
||||
current_scan_cycle_usage_saves_start: AtomicU64::new(0),
|
||||
scanner_set_scan_concurrency_limit: AtomicU64::new(0),
|
||||
last_scan_cycle_set_scan_concurrency_limit: AtomicU64::new(0),
|
||||
scanner_set_scans_queued: AtomicU64::new(0),
|
||||
scanner_set_scans_active: AtomicU64::new(0),
|
||||
scanner_disk_bucket_scan_states: Mutex::new(HashMap::new()),
|
||||
@@ -3043,10 +3039,6 @@ impl Metrics {
|
||||
if let Some(concurrency_limit) = concurrency_limit {
|
||||
self.scanner_set_scan_concurrency_limit
|
||||
.store(concurrency_limit as u64, Ordering::Relaxed);
|
||||
if concurrency_limit > 0 {
|
||||
self.last_scan_cycle_set_scan_concurrency_limit
|
||||
.store(concurrency_limit as u64, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
if let Some(queued) = queued {
|
||||
self.scanner_set_scans_queued.store(queued as u64, Ordering::Relaxed);
|
||||
@@ -3946,7 +3938,6 @@ impl Metrics {
|
||||
m.leader_lock_last_update_unix_secs = self.scanner_leader_lock_last_update_unix_secs.load(Ordering::Relaxed);
|
||||
m.last_cycle_end_unix_secs = self.last_scan_cycle_end_unix_secs.load(Ordering::Relaxed);
|
||||
m.current_set_scan_concurrency_limit = self.scanner_set_scan_concurrency_limit.load(Ordering::Relaxed);
|
||||
m.last_cycle_set_scan_concurrency_limit = self.last_scan_cycle_set_scan_concurrency_limit.load(Ordering::Relaxed);
|
||||
m.current_set_scans_queued = self.scanner_set_scans_queued.load(Ordering::Relaxed);
|
||||
m.current_set_scans_active = self.scanner_set_scans_active.load(Ordering::Relaxed);
|
||||
let disk_bucket_scan_states = self.scanner_disk_bucket_scan_state_snapshots();
|
||||
@@ -4492,7 +4483,6 @@ mod tests {
|
||||
let report = metrics.report().await;
|
||||
|
||||
assert_eq!(report.current_set_scan_concurrency_limit, 3);
|
||||
assert_eq!(report.last_cycle_set_scan_concurrency_limit, 3);
|
||||
assert_eq!(report.current_set_scans_queued, 5);
|
||||
assert_eq!(report.current_set_scans_active, 2);
|
||||
assert_eq!(report.current_disk_scan_concurrency_limit, 6);
|
||||
@@ -4503,7 +4493,6 @@ mod tests {
|
||||
let report = metrics.report().await;
|
||||
|
||||
assert_eq!(report.current_set_scan_concurrency_limit, 0);
|
||||
assert_eq!(report.last_cycle_set_scan_concurrency_limit, 3);
|
||||
assert_eq!(report.current_set_scans_queued, 0);
|
||||
assert_eq!(report.current_set_scans_active, 0);
|
||||
assert_eq!(report.current_disk_scan_concurrency_limit, 0);
|
||||
|
||||
@@ -86,10 +86,6 @@ pub(crate) enum DataUsageCacheRevision {
|
||||
}
|
||||
|
||||
impl DataUsageCacheRevision {
|
||||
fn from_etag(etag: Option<String>) -> Option<Self> {
|
||||
etag.filter(|etag| !etag.is_empty()).map(Self::Etag)
|
||||
}
|
||||
|
||||
pub(crate) fn preconditions(&self) -> HTTPPreconditions {
|
||||
match self {
|
||||
Self::Missing => HTTPPreconditions {
|
||||
@@ -187,7 +183,11 @@ pub(crate) async fn read_config_revision<S: ScannerObjectIO>(store: Arc<S>, path
|
||||
read,
|
||||
);
|
||||
match read.await {
|
||||
Ok(reader) => DataUsageCacheRevision::from_etag(reader.object_info.etag)
|
||||
Ok(reader) => reader
|
||||
.object_info
|
||||
.etag
|
||||
.filter(|etag| !etag.is_empty())
|
||||
.map(DataUsageCacheRevision::Etag)
|
||||
.ok_or_else(|| StorageError::other(format!("scanner config object {path} has no ETag"))),
|
||||
Err(
|
||||
Error::ConfigNotFound
|
||||
@@ -628,19 +628,6 @@ pub(crate) struct DataUsageDurableProgress {
|
||||
active_source: Option<String>,
|
||||
}
|
||||
|
||||
fn directory_progress_for<'a, T>(
|
||||
progress: &'a [T],
|
||||
parent: &'a str,
|
||||
path: impl Fn(&T) -> &str + 'a,
|
||||
) -> impl Iterator<Item = &'a T> {
|
||||
let start = if progress.len() > 1 {
|
||||
progress.partition_point(|entry| path(entry) < parent)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
progress[start..].iter().take_while(move |entry| path(entry) == parent)
|
||||
}
|
||||
|
||||
impl DataUsageDurableProgress {
|
||||
fn source_frontier(&self, source: Option<&str>) -> Option<&str> {
|
||||
if source == self.active_source.as_deref() {
|
||||
@@ -651,20 +638,12 @@ impl DataUsageDurableProgress {
|
||||
}
|
||||
|
||||
fn covers_on(&self, source: Option<&str>, path: &str) -> bool {
|
||||
if self
|
||||
.source_frontier(source)
|
||||
self.source_frontier(source)
|
||||
.is_some_and(|frontier| scan_frontier_covers_path(path, frontier))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let covers = |done: &crate::scanner_folder::DirectoryProgress| {
|
||||
Some(done.physical.endpoint.as_str()) == source && done.covers(path)
|
||||
};
|
||||
if self.compacted.len() <= 1 {
|
||||
return self.compacted.iter().any(covers);
|
||||
}
|
||||
path.match_indices('/')
|
||||
.any(|(separator, _)| directory_progress_for(&self.compacted, &path[..separator], |entry| &entry.parent).any(covers))
|
||||
|| self
|
||||
.compacted
|
||||
.iter()
|
||||
.any(|done| Some(done.physical.endpoint.as_str()) == source && done.covers(path))
|
||||
}
|
||||
|
||||
pub(crate) fn advanced_from(&self, previous: &Self) -> bool {
|
||||
@@ -700,10 +679,10 @@ impl DataUsageDurableProgress {
|
||||
// Legacy raw-name pages are local to their writer. The physical
|
||||
// root position must still exist for that writer across rotation.
|
||||
if !previous.raw.is_empty()
|
||||
&& !directory_progress_for(&previous.listings, &self.bucket, |entry| &entry.parent).any(|before| {
|
||||
Some(before.physical.endpoint.as_str()) == old
|
||||
&& directory_progress_for(&self.listings, &before.parent, |entry| &entry.parent)
|
||||
.any(|after| after.extends(before))
|
||||
&& !previous.listings.iter().any(|before| {
|
||||
before.parent == self.bucket
|
||||
&& Some(before.physical.endpoint.as_str()) == old
|
||||
&& self.listings.iter().any(|after| after.extends(before))
|
||||
})
|
||||
{
|
||||
return false;
|
||||
@@ -716,36 +695,32 @@ impl DataUsageDurableProgress {
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
advanced = advanced
|
||||
|| self.raw.iter().any(|(parent, after)| {
|
||||
after.committed_entries() > previous.raw.get(parent).map_or(0, |before| before.committed_entries())
|
||||
});
|
||||
advanced |= self.raw.iter().any(|(parent, after)| {
|
||||
after.committed_entries() > previous.raw.get(parent).map_or(0, |before| before.committed_entries())
|
||||
});
|
||||
}
|
||||
for before in &previous.listings {
|
||||
if !directory_progress_for(&self.listings, &before.parent, |entry| &entry.parent).any(|after| after.extends(before))
|
||||
if !self.listings.iter().any(|after| after.extends(before))
|
||||
&& !self.covers_on(Some(&before.physical.endpoint), &before.parent)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for before in &previous.compacted {
|
||||
if !directory_progress_for(&self.compacted, &before.parent, |entry| &entry.parent).any(|after| after.extends(before))
|
||||
if !self.compacted.iter().any(|after| after.extends(before))
|
||||
&& !self.covers_on(Some(&before.physical.endpoint), &before.parent)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
advanced |= self.listings.iter().any(|after| {
|
||||
Some(after.physical.endpoint.as_str()) == active && !previous.listings.iter().any(|before| before.extends(after))
|
||||
});
|
||||
advanced |= self.compacted.iter().any(|after| {
|
||||
Some(after.physical.endpoint.as_str()) == active && !previous.compacted.iter().any(|before| before.extends(after))
|
||||
});
|
||||
|
||||
advanced
|
||||
|| self.listings.iter().any(|after| {
|
||||
Some(after.physical.endpoint.as_str()) == active
|
||||
&& !directory_progress_for(&previous.listings, &after.parent, |entry| &entry.parent)
|
||||
.any(|before| before.extends(after))
|
||||
})
|
||||
|| self.compacted.iter().any(|after| {
|
||||
Some(after.physical.endpoint.as_str()) == active
|
||||
&& !directory_progress_for(&previous.compacted, &after.parent, |entry| &entry.parent)
|
||||
.any(|before| before.extends(after))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1386,18 +1361,6 @@ impl DataUsageCache {
|
||||
}
|
||||
|
||||
pub(crate) fn durable_scan_progress(&self) -> DataUsageDurableProgress {
|
||||
let mut listings = Vec::new();
|
||||
let mut compacted = Vec::new();
|
||||
for directory in &self.info.scan_directory_work {
|
||||
let (listing, aggregate) = directory.scheduling_progress(&self.info);
|
||||
listings.extend(listing);
|
||||
compacted.extend(aggregate);
|
||||
}
|
||||
// Cache readers can restore receipts in a different order from the producer.
|
||||
if self.info.scan_directory_work.len() > 1 {
|
||||
listings.sort_unstable_by(|left, right| left.parent.cmp(&right.parent));
|
||||
compacted.sort_unstable_by(|left, right| left.parent.cmp(&right.parent));
|
||||
}
|
||||
DataUsageDurableProgress {
|
||||
bucket: self.info.name.clone(),
|
||||
source: self.info.source,
|
||||
@@ -1411,8 +1374,18 @@ impl DataUsageCache {
|
||||
.filter_map(|(source, tree)| tree.frontier(&self.info).map(|last| (source.clone(), last.to_owned())))
|
||||
.collect(),
|
||||
active_source: self.info.scan_directory_source.clone(),
|
||||
listings,
|
||||
compacted,
|
||||
listings: self
|
||||
.info
|
||||
.scan_directory_work
|
||||
.iter()
|
||||
.filter_map(|d| d.read_progress(&self.info))
|
||||
.collect(),
|
||||
compacted: self
|
||||
.info
|
||||
.scan_directory_work
|
||||
.iter()
|
||||
.filter_map(|d| d.progress(&self.info))
|
||||
.collect(),
|
||||
raw: self
|
||||
.info
|
||||
.scan_raw_enumeration_page_index
|
||||
@@ -1493,17 +1466,15 @@ impl DataUsageCache {
|
||||
// authorizing a new leader to skip namespace coverage.
|
||||
// Cycle deadlines advance both counters, so a validated frontier from
|
||||
// an earlier cycle must remain eligible for adoption.
|
||||
let checking_handoff = self.info.leader_epoch < leader_epoch && self.info.scan_identity == Some(identity);
|
||||
let handoff_digest = if checking_handoff {
|
||||
self.validated_scan_frontier_receipt().map(|(_, digest)| digest)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let cross_epoch_checkpoint = checking_handoff
|
||||
&& (handoff_digest.is_some()
|
||||
let cross_epoch_checkpoint = self.info.leader_epoch < leader_epoch
|
||||
&& self.info.scan_identity == Some(identity)
|
||||
&& (self.validated_scan_frontier().is_some()
|
||||
|| self.validated_raw_enumeration_cursor().is_some()
|
||||
|| self.validated_raw_enumeration_page_index().is_some()
|
||||
|| self.info.scan_directory_work.iter().any(|d| d.is_bound_to(&self.info)));
|
||||
let handoff_frontier = cross_epoch_checkpoint
|
||||
.then(|| self.validated_scan_frontier().map(clone_cache_value))
|
||||
.flatten();
|
||||
let reusable = identity.is_valid()
|
||||
&& name != DATA_USAGE_ROOT
|
||||
&& self.info.name == name
|
||||
@@ -1589,13 +1560,9 @@ impl DataUsageCache {
|
||||
self.info.scan_directory_work = directory_work.into_iter().filter(|d| d.is_bound_to(&self.info)).collect();
|
||||
let cursor_is_valid = !self.has_scan_position()
|
||||
|| !self.info.scan_directory_work.is_empty()
|
||||
|| self.validated_scan_frontier().is_some()
|
||||
|| self.info.scan_raw_enumeration_cursor.is_some()
|
||||
|| self.info.scan_raw_enumeration_page_index.is_some()
|
||||
|| if checking_handoff {
|
||||
handoff_digest.is_some()
|
||||
} else {
|
||||
self.validated_scan_frontier().is_some()
|
||||
};
|
||||
|| self.info.scan_raw_enumeration_page_index.is_some();
|
||||
if !cursor_is_valid {
|
||||
self.info.scan_progress = None;
|
||||
}
|
||||
@@ -1607,12 +1574,13 @@ impl DataUsageCache {
|
||||
self.info.tier_registry_generation = Some(identity.tier_registry_generation);
|
||||
self.info.scan_identity = Some(identity);
|
||||
self.info.snapshot_complete = false;
|
||||
if reusable
|
||||
&& let Some(digest) = handoff_digest
|
||||
if let Some(frontier) = handoff_frontier
|
||||
&& let Ok(digest) = self.coverage_prefix_digest(&frontier)
|
||||
&& let Some(receipt) = self.info.scan_coverage_receipt.as_mut()
|
||||
{
|
||||
// Reuse the digest computed during handoff validation. Only the
|
||||
// leader epoch and fields outside the digest have changed here.
|
||||
// Migrate a legacy epoch-bound receipt while the old epoch is
|
||||
// still available for validation. New receipts deliberately do
|
||||
// not bind to the process-local leader epoch.
|
||||
receipt.digest = digest;
|
||||
}
|
||||
// A sweep without a durable position restarts from the first entry,
|
||||
@@ -1751,34 +1719,24 @@ impl DataUsageCache {
|
||||
}
|
||||
|
||||
pub(crate) fn validated_scan_frontier(&self) -> Option<&str> {
|
||||
self.validated_scan_frontier_receipt().map(|(frontier, _)| frontier)
|
||||
}
|
||||
|
||||
/// Verify the saved frontier and return the digest to retain at handoff.
|
||||
fn validated_scan_frontier_receipt(&self) -> Option<(&str, [u8; 32])> {
|
||||
let receipt = self.info.scan_coverage_receipt.as_ref()?;
|
||||
let checkpoint = self.info.scan_checkpoint.as_ref()?;
|
||||
let through = receipt.through.as_str();
|
||||
if self.info.scan_progress.is_none()
|
||||
|| self.info.scan_identity.is_none_or(|identity| !identity.is_valid())
|
||||
|| self.info.source.is_none()
|
||||
|| through.len() > 16 * 1024
|
||||
|| checkpoint.version != DATA_USAGE_SCAN_CHECKPOINT_VERSION
|
||||
|| checkpoint.resume_after != through
|
||||
|| self.info.scan_resume_after.as_deref() != Some(through)
|
||||
|| through
|
||||
(self.info.scan_progress.is_some()
|
||||
&& self.info.scan_identity.is_some_and(|identity| identity.is_valid())
|
||||
&& self.info.source.is_some()
|
||||
&& receipt.through.len() <= 16 * 1024
|
||||
&& checkpoint.version == DATA_USAGE_SCAN_CHECKPOINT_VERSION
|
||||
&& checkpoint.resume_after == receipt.through
|
||||
&& self.info.scan_resume_after.as_deref() == Some(receipt.through.as_str())
|
||||
&& receipt
|
||||
.through
|
||||
.strip_prefix(&self.info.name)
|
||||
.is_none_or(|suffix| !suffix.starts_with('/'))
|
||||
|| self.find(through).is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let current = self.coverage_prefix_digest(through).ok();
|
||||
// If a legacy proof validates but cannot be migrated, retain its bytes.
|
||||
(current == Some(receipt.digest)
|
||||
|| self.v2_coverage_prefix_digest(through).ok() == Some(receipt.digest)
|
||||
|| self.legacy_coverage_prefix_digest(through).ok() == Some(receipt.digest))
|
||||
.then_some((through, current.unwrap_or(receipt.digest)))
|
||||
.is_some_and(|suffix| suffix.starts_with('/'))
|
||||
&& self.find(&receipt.through).is_some()
|
||||
&& (self.coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)
|
||||
|| self.v2_coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)
|
||||
|| self.legacy_coverage_prefix_digest(&receipt.through).ok() == Some(receipt.digest)))
|
||||
.then_some(receipt.through.as_str())
|
||||
}
|
||||
|
||||
pub(crate) fn validated_raw_enumeration_cursor(&self) -> Option<&DataUsageRawEnumerationCursor> {
|
||||
|
||||
@@ -18,26 +18,8 @@ mod scan_load;
|
||||
use super::*;
|
||||
use bytes::Bytes;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Compare the stored body exactly without allocating a second copy of the cache.
|
||||
pub(super) async fn cache_body_matches(reader: &mut (impl AsyncRead + Unpin), mut expected: &[u8]) -> std::io::Result<bool> {
|
||||
let mut buffer = vec![0; expected.len().clamp(1, 16 * 1024)];
|
||||
loop {
|
||||
// When the expected body ends, read at most one extra byte to verify EOF.
|
||||
let limit = buffer.len().min(expected.len().saturating_add(1));
|
||||
let read = reader.read(&mut buffer[..limit]).await?;
|
||||
if read == 0 {
|
||||
return Ok(expected.is_empty());
|
||||
}
|
||||
let Some(remaining) = expected.strip_prefix(&buffer[..read]) else {
|
||||
return Ok(false);
|
||||
};
|
||||
expected = remaining;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CachePublicationAdmissionUnavailable;
|
||||
|
||||
@@ -113,21 +95,6 @@ impl DataUsageCacheLoadAttempt {
|
||||
}
|
||||
}
|
||||
|
||||
impl DataUsageCacheRevisions {
|
||||
pub(crate) async fn refresh_unknown_backup<S: ScannerObjectIO>(&mut self, store: Arc<S>, name: &str) {
|
||||
if self.backup.is_none() {
|
||||
self.backup = DataUsageCache::backup_revision(store, name).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn matches_current_for_resume<S: ScannerObjectIO>(&self, store: Arc<S>, name: &str) -> StorageResult<bool> {
|
||||
let main = DataUsageCache::main_revision(store.clone(), name).await?;
|
||||
// A baseline decoded from backup always has its revision. An unknown
|
||||
// backup cannot invalidate the walk or supply a new CAS token here.
|
||||
Ok(self.main == main && (self.backup.is_none() || self.backup == DataUsageCache::backup_revision(store, name).await))
|
||||
}
|
||||
}
|
||||
|
||||
// Data usage paths (computed at runtime)
|
||||
|
||||
impl DataUsageCache {
|
||||
@@ -198,15 +165,12 @@ impl DataUsageCache {
|
||||
}
|
||||
}
|
||||
|
||||
async fn main_revision<S: ScannerObjectIO>(store: Arc<S>, name: &str) -> StorageResult<DataUsageCacheRevision> {
|
||||
let main_path = path_join_buf(&[BUCKET_META_PREFIX, name]);
|
||||
read_config_revision(store, &main_path).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn read_revisions<S: ScannerObjectIO>(store: Arc<S>, name: &str) -> StorageResult<DataUsageCacheRevisions> {
|
||||
let main = Self::main_revision(store.clone(), name).await?;
|
||||
let backup = Self::backup_revision(store, name).await;
|
||||
let main_path = path_join_buf(&[BUCKET_META_PREFIX, name]);
|
||||
let backup_name = format!("{name}.bkp");
|
||||
let backup_path = path_join_buf(&[BUCKET_META_PREFIX, &backup_name]);
|
||||
let main = read_config_revision(store.clone(), &main_path).await?;
|
||||
let backup = Some(read_config_revision(store, &backup_path).await?);
|
||||
Ok(DataUsageCacheRevisions {
|
||||
main,
|
||||
backup,
|
||||
@@ -581,15 +545,15 @@ impl DataUsageCache {
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn retry_save_op<F, Fut, T>(
|
||||
pub(super) async fn retry_save_op<F, Fut>(
|
||||
path_type: &'static str,
|
||||
timeout_duration: Duration,
|
||||
max_retries: u32,
|
||||
mut save_op: F,
|
||||
) -> StorageResult<T>
|
||||
) -> StorageResult<()>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: Future<Output = StorageResult<T>>,
|
||||
Fut: Future<Output = StorageResult<()>>,
|
||||
{
|
||||
let mut last_err: Option<StorageError> = None;
|
||||
|
||||
@@ -599,9 +563,9 @@ impl DataUsageCache {
|
||||
let duration = attempt_start.elapsed();
|
||||
|
||||
match timeout_res {
|
||||
Ok(Ok(value)) => {
|
||||
Ok(Ok(())) => {
|
||||
Self::record_save_attempt(path_type, "success", duration);
|
||||
return Ok(value);
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => {
|
||||
Self::record_save_attempt(path_type, "timeout", duration);
|
||||
@@ -635,7 +599,7 @@ impl DataUsageCache {
|
||||
max_retries: u32,
|
||||
revision: Option<DataUsageCacheRevision>,
|
||||
expected_epoch: Option<u64>,
|
||||
) -> StorageResult<Option<DataUsageCacheRevision>> {
|
||||
) -> StorageResult<()> {
|
||||
Self::ensure_cache_save_metrics_registered();
|
||||
let path_type = Self::cache_path_type(path);
|
||||
let path = path.to_string();
|
||||
@@ -666,7 +630,7 @@ impl DataUsageCache {
|
||||
counter!(METRIC_CACHE_SAVE_PAYLOAD_BYTES_TOTAL, "cache" => path_type)
|
||||
.increment(u64::try_from(buf_clone.len()).unwrap_or(u64::MAX));
|
||||
if let Some(revision) = revision {
|
||||
let committed = crate::save_config_shared_with_preconditions_and_lease_fence_and_scope(
|
||||
crate::save_config_shared_with_preconditions_and_lease_fence_and_scope(
|
||||
store_clone,
|
||||
&path_clone,
|
||||
buf_clone,
|
||||
@@ -676,19 +640,17 @@ impl DataUsageCache {
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
Ok(DataUsageCacheRevision::from_etag(committed.etag))
|
||||
} else {
|
||||
save_config(store_clone, &path_clone, buf_clone.to_vec()).await?;
|
||||
Ok(None)
|
||||
}
|
||||
Ok::<(), StorageError>(())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
histogram!("rustfs_scanner_cache_persist_attempt_seconds", "path_type" => path_type, "retry_result" => if save_result.is_ok() { "success" } else { "error" })
|
||||
.record(persist_started.elapsed().as_secs_f64());
|
||||
let save_err = match save_result {
|
||||
Ok(revision) => return Ok(revision),
|
||||
Err(error) => error,
|
||||
let Err(save_err) = save_result else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// An epoch-specific admission failure is authoritative: reconciling
|
||||
@@ -713,17 +675,15 @@ impl DataUsageCache {
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let matches = cache_body_matches(&mut reader, buf).await?;
|
||||
Ok::<_, StorageError>((matches, DataUsageCacheRevision::from_etag(reader.object_info.etag)))
|
||||
Ok::<bool, StorageError>(reader.read_all().await?.as_slice() == buf.as_ref())
|
||||
})
|
||||
.await;
|
||||
match reconcile {
|
||||
Ok(Ok((true, revision))) => {
|
||||
Self::record_save_attempt(path_type, "reconciled", Duration::ZERO);
|
||||
return Ok(revision);
|
||||
}
|
||||
Ok(Ok((false, _))) => break,
|
||||
_ => {}
|
||||
if matches!(reconcile, Ok(Ok(true))) {
|
||||
Self::record_save_attempt(path_type, "reconciled", Duration::ZERO);
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(reconcile, Ok(Ok(false))) {
|
||||
break;
|
||||
}
|
||||
if attempt < max_retries {
|
||||
sleep(Duration::from_millis(50_u64 * (u64::from(attempt) + 1))).await;
|
||||
@@ -734,7 +694,7 @@ impl DataUsageCache {
|
||||
}
|
||||
|
||||
pub async fn save<S: ScannerObjectIO + ScannerConfigObjectDelete>(&self, store: Arc<S>, name: &str) -> StorageResult<()> {
|
||||
self.save_inner(store, name, None, None).await.map(drop)
|
||||
self.save_inner(store, name, None, None).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -744,14 +704,12 @@ impl DataUsageCache {
|
||||
name: &str,
|
||||
revisions: &DataUsageCacheRevisions,
|
||||
) -> StorageResult<()> {
|
||||
self.save_inner(store, name, Some(revisions), None).await.map(drop)
|
||||
self.save_inner(store, name, Some(revisions), None).await
|
||||
}
|
||||
|
||||
/// All epoch-fenced cache writes use background disk admission. Incremental
|
||||
/// checkpoints pass their scan token; finalization uses a fresh token so a
|
||||
/// spent scan budget can still persist progress within the save timeout.
|
||||
/// A successful save without a confirmed primary ETag cannot supply a new
|
||||
/// baseline for another write from the same walk.
|
||||
pub(crate) async fn save_with_revisions_for_epoch<S: ScannerObjectIO + ScannerConfigObjectDelete>(
|
||||
&self,
|
||||
store: Arc<S>,
|
||||
@@ -759,7 +717,7 @@ impl DataUsageCache {
|
||||
revisions: &DataUsageCacheRevisions,
|
||||
expected_epoch: u64,
|
||||
cancellation: CancellationToken,
|
||||
) -> StorageResult<Option<DataUsageCacheRevisions>> {
|
||||
) -> StorageResult<()> {
|
||||
crate::storage_api::ecstore_with_background_disk_io(
|
||||
cancellation,
|
||||
self.save_inner(store, name, Some(revisions), Some(expected_epoch)),
|
||||
@@ -773,7 +731,7 @@ impl DataUsageCache {
|
||||
name: &str,
|
||||
revisions: Option<&DataUsageCacheRevisions>,
|
||||
expected_epoch: Option<u64>,
|
||||
) -> StorageResult<Option<DataUsageCacheRevisions>> {
|
||||
) -> StorageResult<()> {
|
||||
let serialize_started = Instant::now();
|
||||
let paged = matches!((revisions, expected_epoch), (Some(_), Some(_))) && pages::eligible(self, name);
|
||||
let encoded = if paged { Some(pages::encode(self)?) } else { None };
|
||||
@@ -823,7 +781,7 @@ impl DataUsageCache {
|
||||
.ok()
|
||||
.flatten();
|
||||
let primary_save_started = Instant::now();
|
||||
let main = Self::save_path_with_retry(
|
||||
Self::save_path_with_retry(
|
||||
store.clone(),
|
||||
&path,
|
||||
&primary_buf,
|
||||
@@ -840,13 +798,8 @@ impl DataUsageCache {
|
||||
let backup_path = path_join_buf(&[BUCKET_META_PREFIX, &backup_name]);
|
||||
let backup_timeout_duration = Self::backup_cache_save_timeout(timeout_duration, primary_save_started.elapsed());
|
||||
let backup_revision = revisions.and_then(|revisions| revisions.backup.clone());
|
||||
let mut committed = main.map(|main| DataUsageCacheRevisions {
|
||||
main,
|
||||
backup: None,
|
||||
damaged_pages: DamagedPages::default(),
|
||||
});
|
||||
if revisions.is_some() && backup_revision.is_none() {
|
||||
return Ok(committed);
|
||||
return Ok(());
|
||||
}
|
||||
let save_backup = async {
|
||||
let (backup_buf, retired) = match (&encoded, &backup_revision, expected_epoch) {
|
||||
@@ -864,7 +817,7 @@ impl DataUsageCache {
|
||||
}
|
||||
_ => (inline, [None, None]),
|
||||
};
|
||||
let backup = Self::save_path_with_retry(
|
||||
Self::save_path_with_retry(
|
||||
store.clone(),
|
||||
&backup_path,
|
||||
&backup_buf,
|
||||
@@ -875,36 +828,29 @@ impl DataUsageCache {
|
||||
)
|
||||
.await?;
|
||||
pages::reclaim_retired(store, &backup_name, retired, expected_epoch).await;
|
||||
Ok::<_, StorageError>(backup)
|
||||
Ok::<_, StorageError>(())
|
||||
};
|
||||
let backup_result = match timeout(backup_timeout_duration, save_backup).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err(StorageError::other("scanner cache backup save timed out")),
|
||||
};
|
||||
match backup_result {
|
||||
Ok(backup) => {
|
||||
if let Some(committed) = &mut committed {
|
||||
committed.backup = backup;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(
|
||||
target: "rustfs::scanner::data_usage",
|
||||
event = EVENT_SCANNER_CACHE_SAVE_STATE,
|
||||
component = LOG_COMPONENT_SCANNER,
|
||||
subsystem = LOG_SUBSYSTEM_CACHE,
|
||||
cache_name = %name,
|
||||
backup_path = %backup_path,
|
||||
state = "backup_save_failed",
|
||||
error = %e,
|
||||
"Scanner cache backup save failed"
|
||||
);
|
||||
if is_cache_publication_admission_unavailable(&e) || is_cache_publication_epoch_changed(&e) {
|
||||
return Err(e);
|
||||
}
|
||||
if let Err(e) = backup_result {
|
||||
warn!(
|
||||
target: "rustfs::scanner::data_usage",
|
||||
event = EVENT_SCANNER_CACHE_SAVE_STATE,
|
||||
component = LOG_COMPONENT_SCANNER,
|
||||
subsystem = LOG_SUBSYSTEM_CACHE,
|
||||
cache_name = %name,
|
||||
backup_path = %backup_path,
|
||||
state = "backup_save_failed",
|
||||
error = %e,
|
||||
"Scanner cache backup save failed"
|
||||
);
|
||||
if is_cache_publication_admission_unavailable(&e) || is_cache_publication_epoch_changed(&e) {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
Ok(committed)
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,8 +66,12 @@ async fn backup_revision<S: ScannerObjectIO>(
|
||||
Err(StorageError::FileNotFound | StorageError::ObjectNotFound(..)) => return Ok(Some(DataUsageCacheRevision::Missing)),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if usize::try_from(reader.object_info.size).ok() == Some(expected.len()) && cache_body_matches(&mut reader, expected).await? {
|
||||
return Ok(None);
|
||||
if usize::try_from(reader.object_info.size).ok() == Some(expected.len()) {
|
||||
let mut bytes = Vec::with_capacity(expected.len());
|
||||
(&mut reader).take(PAGE_MAX as u64 + 1).read_to_end(&mut bytes).await?;
|
||||
if bytes == expected.as_ref() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let etag = reader
|
||||
.object_info
|
||||
|
||||
@@ -226,50 +226,6 @@ impl AsyncRead for PrefixThenErrorReader {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cache_body_comparison_requires_exact_bytes_and_verified_eof() {
|
||||
use super::persistence::cache_body_matches;
|
||||
|
||||
let payload = vec![b'x'; 128 * 1024];
|
||||
for (actual, expected, matches) in [
|
||||
(payload.as_slice(), payload.as_slice(), true),
|
||||
(&payload[..payload.len() - 1], payload.as_slice(), false),
|
||||
(payload.as_slice(), &payload[..payload.len() - 1], false),
|
||||
(b"".as_slice(), b"".as_slice(), true),
|
||||
(b"x".as_slice(), b"".as_slice(), false),
|
||||
] {
|
||||
assert_eq!(
|
||||
cache_body_matches(&mut Cursor::new(actual), expected)
|
||||
.await
|
||||
.expect("compare cache body"),
|
||||
matches,
|
||||
"stored length {}, expected length {}",
|
||||
actual.len(),
|
||||
expected.len()
|
||||
);
|
||||
}
|
||||
|
||||
let mut reader = PrefixThenErrorReader {
|
||||
prefix: Cursor::new(vec![b'y']),
|
||||
failed: false,
|
||||
};
|
||||
assert!(
|
||||
!cache_body_matches(&mut reader, &payload)
|
||||
.await
|
||||
.expect("an already divergent prefix needs no further reads")
|
||||
);
|
||||
assert!(!reader.failed, "the comparison must stop before polling the unread suffix");
|
||||
|
||||
let mut reader = PrefixThenErrorReader {
|
||||
prefix: Cursor::new(payload.clone()),
|
||||
failed: false,
|
||||
};
|
||||
assert!(
|
||||
cache_body_matches(&mut reader, &payload).await.is_err(),
|
||||
"matching bytes cannot establish equality until EOF succeeds"
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CacheReadStore {
|
||||
main: CacheReadBody,
|
||||
@@ -2402,7 +2358,7 @@ fn data_usage_cache_prepare_for_scan_fences_leader_epochs() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
|
||||
fn prepare_bucket_checkpoint_migrates_legacy_epoch_bound_receipt() {
|
||||
let identity = valid_scan_identity();
|
||||
let source = DataUsageCacheSource::new(1, 2);
|
||||
let mut cache = DataUsageCache {
|
||||
@@ -2436,9 +2392,7 @@ fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let current_digest = cache.coverage_prefix_digest("bucket/a").expect("current receipt digest");
|
||||
for saved_digest in [
|
||||
current_digest,
|
||||
for legacy_digest in [
|
||||
cache
|
||||
.legacy_coverage_prefix_digest("bucket/a")
|
||||
.expect("epoch-bound receipt digest"),
|
||||
@@ -2447,7 +2401,7 @@ fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
|
||||
let mut cache = cache.clone();
|
||||
cache.info.scan_coverage_receipt = Some(DataUsageScanCoverageReceipt {
|
||||
through: "bucket/a".to_string(),
|
||||
digest: saved_digest,
|
||||
digest: legacy_digest,
|
||||
});
|
||||
assert_eq!(cache.validated_scan_frontier(), Some("bucket/a"));
|
||||
assert_eq!(
|
||||
@@ -2456,8 +2410,8 @@ fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
|
||||
);
|
||||
assert_eq!(cache.info.leader_epoch, 2);
|
||||
assert_eq!(cache.validated_scan_frontier(), Some("bucket/a"));
|
||||
let digest = cache.info.scan_coverage_receipt.as_ref().expect("retained receipt").digest;
|
||||
assert_eq!(digest, current_digest);
|
||||
let digest = cache.info.scan_coverage_receipt.as_ref().expect("migrated receipt").digest;
|
||||
assert_ne!(digest, legacy_digest);
|
||||
assert_ne!(digest, cache.v2_coverage_prefix_digest("bucket/a").expect("old reader v2 digest"));
|
||||
assert_ne!(
|
||||
digest,
|
||||
@@ -2467,11 +2421,6 @@ fn prepare_bucket_checkpoint_preserves_current_and_migrates_legacy_frontiers() {
|
||||
);
|
||||
cache.cache.get_mut("bucket/a").expect("covered entry").failed_objects = 1;
|
||||
assert!(cache.validated_scan_frontier().is_none(), "tampered health debt invalidates coverage");
|
||||
assert_eq!(
|
||||
cache.prepare_bucket_checkpoint("bucket", 10, 3, source, TEST_PLAN_DIGEST, identity),
|
||||
DataUsageCachePrepareOutcome::Reset
|
||||
);
|
||||
assert!(cache.validated_scan_frontier().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3155,7 +3104,7 @@ async fn test_retry_save_op_does_not_retry_namespace_lock_errors() {
|
||||
let attempts = attempts_clone.clone();
|
||||
async move {
|
||||
attempts.fetch_add(1, Ordering::SeqCst);
|
||||
Err::<(), _>(StorageError::NamespaceLockQuorumUnavailable {
|
||||
Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "write",
|
||||
bucket: RUSTFS_META_BUCKET.to_string(),
|
||||
object: "buckets/.usage-cache.bin".to_string(),
|
||||
|
||||
@@ -1160,8 +1160,7 @@ async fn scan_and_persist_local_bucket_with_store(
|
||||
usage_watch.as_deref(),
|
||||
checkpoint_plan_digest.unwrap_or(scan_plan_digest),
|
||||
);
|
||||
let scan_position_before =
|
||||
(supports_durable_progress && checkpoint_plan_digest.is_some()).then(|| cache.durable_scan_progress());
|
||||
let scan_position_before = cache.durable_scan_progress();
|
||||
let resumed_sweep = cache.has_scan_position();
|
||||
|
||||
let set_disks = scanner_set_disk_inventory(set.as_ref()).await;
|
||||
@@ -1428,9 +1427,7 @@ async fn scan_and_persist_local_bucket_with_store(
|
||||
checkpoint_plan_digest,
|
||||
leader_epoch,
|
||||
next_cycle,
|
||||
advanced: scan_position_before
|
||||
.as_ref()
|
||||
.is_some_and(|before| cache.durable_scan_progress().advanced_from(before)),
|
||||
advanced: supports_durable_progress && cache.durable_scan_progress().advanced_from(&scan_position_before),
|
||||
resource_deferred: cache.info.scan_resource_deferred,
|
||||
observation: supports_complete_observation
|
||||
.then(|| cache.completed_bucket_observation().cloned().map(Box::new))
|
||||
@@ -1844,19 +1841,16 @@ where
|
||||
}
|
||||
RemoteScannerFrameResult::DurableProgress(receipt) => {
|
||||
let actual = receipt.identity.tier_registry_generation;
|
||||
let expected_identity = crate::DataUsageScanIdentity {
|
||||
tier_registry_generation: expected.tier_registry_generation,
|
||||
..receipt.identity
|
||||
};
|
||||
if !(expected.supports_durable_progress || expected.supports_complete_observation)
|
||||
|| (!expected.supports_durable_progress && receipt.advanced)
|
||||
|| (!expected.supports_complete_observation && receipt.observation.is_some())
|
||||
|| frame.phase != RemoteScannerPhase::Persisting
|
||||
|| receipt.source != expected.source
|
||||
|| expected.checkpoint_identity.is_none_or(|identity| {
|
||||
// The worker fences persistence with its own process-local epoch.
|
||||
crate::DataUsageScanIdentity {
|
||||
publication_epoch: identity.publication_epoch,
|
||||
tier_registry_generation: expected.tier_registry_generation,
|
||||
..receipt.identity
|
||||
} != identity
|
||||
})
|
||||
|| Some(expected_identity) != expected.checkpoint_identity
|
||||
|| receipt.scan_plan_digest != expected.scan_plan_digest
|
||||
|| receipt.checkpoint_plan_digest != expected.checkpoint_plan_digest
|
||||
|| receipt.leader_epoch != expected.leader_epoch
|
||||
|
||||
@@ -43,20 +43,13 @@ fn durable_receipt() -> RemoteScannerDurableProgress {
|
||||
|
||||
#[tokio::test]
|
||||
async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
|
||||
let leader_publication_epoch = 3;
|
||||
assert_ne!(progress_identity().publication_epoch, leader_publication_epoch);
|
||||
for case in [
|
||||
"valid",
|
||||
"progress_only",
|
||||
"generation",
|
||||
"after_preflight",
|
||||
"legacy",
|
||||
"source",
|
||||
"identity",
|
||||
"layout",
|
||||
"mode",
|
||||
"missing_identity",
|
||||
"observation_epoch",
|
||||
"epoch",
|
||||
"plan",
|
||||
"future_observation",
|
||||
@@ -68,13 +61,16 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
|
||||
let writer_auth = FrameAuthenticator::for_test(request_id);
|
||||
let reader_auth = FrameAuthenticator::for_test(if case == "mac" { Uuid::new_v4() } else { request_id });
|
||||
let mut receipt = durable_receipt();
|
||||
if case != "valid" {
|
||||
receipt.identity.tier_registry_generation = 1;
|
||||
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
|
||||
}
|
||||
match case {
|
||||
"generation" | "after_preflight" => receipt.identity.tier_registry_generation = 1,
|
||||
"progress_only" => receipt.observation = None,
|
||||
"source" => receipt.source = DataUsageCacheSource::new(99, 99),
|
||||
"identity" => receipt.identity.bucket_incarnation = Uuid::from_u128(99),
|
||||
"layout" => receipt.identity.set_layout = DataUsageScanPlanDigest([99; 32]),
|
||||
"mode" => receipt.identity.scan_mode = HealScanMode::Deep,
|
||||
"identity" => {
|
||||
receipt.identity.bucket_incarnation = Uuid::from_u128(99);
|
||||
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
|
||||
}
|
||||
"epoch" => receipt.leader_epoch += 1,
|
||||
"plan" => receipt.checkpoint_plan_digest = DataUsageScanPlanDigest([99; 32]),
|
||||
"future_observation" => receipt.observation.as_mut().expect("fixture observation").completed_cycle += 1,
|
||||
@@ -85,12 +81,6 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(observation) = receipt.observation.as_mut() {
|
||||
observation.identity = receipt.identity;
|
||||
if case == "observation_epoch" {
|
||||
observation.identity.publication_epoch += 1;
|
||||
}
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
write_frame(
|
||||
&mut bytes,
|
||||
@@ -123,16 +113,13 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
|
||||
tier_registry_generation: 0,
|
||||
supports_durable_progress: case != "legacy",
|
||||
supports_complete_observation: case != "legacy",
|
||||
checkpoint_identity: (case != "missing_identity").then(|| crate::DataUsageScanIdentity {
|
||||
publication_epoch: leader_publication_epoch,
|
||||
..progress_identity()
|
||||
}),
|
||||
checkpoint_identity: Some(progress_identity()),
|
||||
},
|
||||
reader_auth,
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
)
|
||||
.await;
|
||||
if matches!(case, "valid" | "progress_only") {
|
||||
if case == "valid" {
|
||||
let RemoteScannerOutcome::DurableProgress {
|
||||
advanced, observation, ..
|
||||
} = result.expect("validated progress")
|
||||
@@ -140,13 +127,7 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
|
||||
panic!("progress cannot become Complete")
|
||||
};
|
||||
assert!(advanced);
|
||||
if case == "valid" {
|
||||
let observation = observation.expect("preserved companion");
|
||||
assert_eq!(observation.identity, progress_identity());
|
||||
assert_eq!(observation.entry.objects, 5);
|
||||
} else {
|
||||
assert!(observation.is_none());
|
||||
}
|
||||
assert_eq!(observation.expect("preserved companion").entry.objects, 5);
|
||||
} else if case == "generation" {
|
||||
assert!(matches!(
|
||||
result,
|
||||
@@ -156,20 +137,6 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
|
||||
assert!(result.is_err(), "invalid progress case {case}");
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"usage_assertion: {}",
|
||||
serde_json::json!({
|
||||
"case_id": "USAGE-23", "assertion_id": "USAGE-23-A01", "status": "PASS",
|
||||
"evidence": {
|
||||
"worker_publication_epoch": progress_identity().publication_epoch,
|
||||
"leader_publication_epoch": leader_publication_epoch,
|
||||
"outcome": "durable_progress",
|
||||
"companion_identity_preserved": true,
|
||||
"mismatched_companion_rejected": true,
|
||||
}
|
||||
}),
|
||||
);
|
||||
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-23", "status": "PASS"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -3257,7 +3257,6 @@ where
|
||||
let mut superseded_backoff = ScannerRetryBackoff::default();
|
||||
let mut deferred_backoff = ScannerRetryBackoff::default();
|
||||
let mut scope_fallback_backoff = ScannerRetryBackoff::default();
|
||||
let mut pending_maintenance_backoff = ScannerRetryBackoff::default();
|
||||
let scope_fallback_slot = Arc::new(ScannerScopeFallbackSlot::default());
|
||||
let initial_runtime_config = resolve_scanner_runtime_config();
|
||||
if clean_idle_topology_supported && maintenance_generation_seen.is_none() {
|
||||
@@ -3690,11 +3689,8 @@ where
|
||||
let superseded_retry_interval = scanner_superseded_retry_interval(superseded_backoff, &runtime_config);
|
||||
let deferred_retry_interval = deferred_backoff.retry_interval(runtime_config.cycle_interval);
|
||||
let scope_fallback_retry_interval = scanner_scope_fallback_retry_interval(scope_fallback_backoff, &runtime_config);
|
||||
let pending_maintenance_retry_interval =
|
||||
scanner_pending_maintenance_retry_interval(pending_maintenance_backoff, &runtime_config);
|
||||
let mut convergence_retry_interval = superseded_retry_interval
|
||||
.or(scope_fallback_retry_interval)
|
||||
.or(pending_maintenance_retry_interval)
|
||||
.or(deferred_retry_interval);
|
||||
if let Some(retry_interval) = convergence_retry_interval {
|
||||
wait_plan.effective_interval = retry_interval;
|
||||
@@ -3957,7 +3953,6 @@ where
|
||||
) && dirty_usage_buckets_pending()
|
||||
});
|
||||
scope_fallback_backoff.record_retryable_cycle(scope_fallback.is_some());
|
||||
pending_maintenance_backoff.record_retryable_cycle(outcome == ScannerCycleOutcome::CompletedWithPendingMaintenance);
|
||||
dirty_usage_generation_seen = dirty_generation_before_cycle;
|
||||
if guard.is_lock_lost() {
|
||||
record_scanner_leader_lock_lost("Scanner leader lock lost during a scanner cycle").await;
|
||||
|
||||
@@ -225,21 +225,6 @@ pub(super) fn scanner_scope_fallback_retry_interval(
|
||||
Some(retry_interval)
|
||||
}
|
||||
|
||||
/// Prompt convergence pacing when a completed cycle still left remote dirty
|
||||
/// usage or maintenance work pending acknowledgement. Retries start at 1s and
|
||||
/// back off exponentially up to the configured cycle interval so peer dirty
|
||||
/// buckets clear quickly after bursts or restarts without spinning indefinitely.
|
||||
pub(super) fn scanner_pending_maintenance_retry_interval(
|
||||
backoff: ScannerRetryBackoff,
|
||||
runtime_config: &ScannerRuntimeConfig,
|
||||
) -> Option<Duration> {
|
||||
let exponent = backoff.consecutive_cycles.checked_sub(1)?.min(31);
|
||||
let multiplier = 1u32.checked_shl(exponent).unwrap_or(u32::MAX);
|
||||
let cycle_interval = runtime_config.cycle_interval.max(Duration::from_secs(1));
|
||||
let retry_interval = Duration::from_secs(1).saturating_mul(multiplier).min(cycle_interval);
|
||||
Some(retry_interval)
|
||||
}
|
||||
|
||||
const SCANNER_PUBLICATION_PROOF_RETRY_MAX_INTERVAL: Duration = Duration::from_secs(30);
|
||||
|
||||
pub(crate) fn scanner_publication_proof_retry_delay(consecutive_failures: u32) -> Duration {
|
||||
|
||||
@@ -9351,25 +9351,6 @@ fn superseded_retry_caps_at_the_default_cycle_and_resets_after_convergence() {
|
||||
assert_eq!(scanner_superseded_retry_interval(backoff, &config), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_maintenance_retry_converges_promptly_and_caps_at_cycle_interval() {
|
||||
let config = ScannerRuntimeConfig {
|
||||
cycle_interval: Duration::from_secs(60),
|
||||
..Default::default()
|
||||
};
|
||||
let mut backoff = ScannerRetryBackoff::default();
|
||||
assert_eq!(scanner_pending_maintenance_retry_interval(backoff, &config), None);
|
||||
for expected in [1, 2, 4, 8, 16, 32, 60, 60] {
|
||||
backoff.record_retryable_cycle(true);
|
||||
assert_eq!(
|
||||
scanner_pending_maintenance_retry_interval(backoff, &config),
|
||||
Some(Duration::from_secs(expected))
|
||||
);
|
||||
}
|
||||
backoff.record_retryable_cycle(false);
|
||||
assert_eq!(scanner_pending_maintenance_retry_interval(backoff, &config), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn superseded_retry_caps_fast_cycles_without_changing_the_generic_retry_cap() {
|
||||
let mut backoff = ScannerRetryBackoff::default();
|
||||
|
||||
@@ -1693,14 +1693,16 @@ impl FolderScanner {
|
||||
snapshot.seal_scan_frontier(self.coverage_frontier.as_deref()).ok()?;
|
||||
// A resumed readdir can run before covered subtrees are copied. Keep
|
||||
// its durable receipt until this snapshot can represent that coverage.
|
||||
if snapshot.info.scan_coverage_receipt.is_none()
|
||||
&& self.coverage_frontier.as_deref().is_some_and(|frontier| {
|
||||
!snapshot
|
||||
.info
|
||||
.scan_directory_work
|
||||
.iter()
|
||||
.any(|directory| directory.covers_bound_path(&snapshot.info, frontier))
|
||||
})
|
||||
let compacted_work = snapshot
|
||||
.info
|
||||
.scan_directory_work
|
||||
.iter()
|
||||
.filter_map(|directory| directory.progress(&snapshot.info));
|
||||
if self
|
||||
.coverage_frontier
|
||||
.as_deref()
|
||||
.is_some_and(|frontier| !compacted_work.clone().any(|proof| proof.covers(frontier)))
|
||||
&& snapshot.info.scan_coverage_receipt.is_none()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -206,17 +206,13 @@ impl DirectoryProgress {
|
||||
self.same_source(previous) && self.through >= previous.through
|
||||
}
|
||||
pub(crate) fn covers(&self, path: &str) -> bool {
|
||||
compacted_child_covers(&self.parent, &self.through, path)
|
||||
path.strip_prefix(&self.parent)
|
||||
.and_then(|tail| tail.strip_prefix('/'))
|
||||
.and_then(|tail| tail.split('/').next())
|
||||
.is_some_and(|child| child <= self.through.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
fn compacted_child_covers(parent: &str, through: &str, path: &str) -> bool {
|
||||
path.strip_prefix(parent)
|
||||
.and_then(|tail| tail.strip_prefix('/'))
|
||||
.and_then(|tail| tail.split('/').next())
|
||||
.is_some_and(|child| child <= through)
|
||||
}
|
||||
|
||||
impl DirectoryCheckpoint {
|
||||
/// Deserialize each replica's independent receipt, then intern equal
|
||||
/// verified immutable name pages across the bucket's active directories.
|
||||
@@ -244,7 +240,7 @@ impl DirectoryCheckpoint {
|
||||
}
|
||||
hash.finalize().into()
|
||||
}
|
||||
fn checksum(&self, manifest: [u8; 32]) -> Option<[u8; 32]> {
|
||||
fn checksum(&self) -> Option<[u8; 32]> {
|
||||
// Nested usage distributions can contain maps. Canonicalize those
|
||||
// map keys before hashing so restart hash randomization is irrelevant.
|
||||
let mut aggregate = serde_json::to_value(&self.aggregate).ok()?;
|
||||
@@ -259,7 +255,7 @@ impl DirectoryCheckpoint {
|
||||
self.sealed,
|
||||
&self.part,
|
||||
self.metadata,
|
||||
manifest,
|
||||
self.manifest(),
|
||||
aggregate,
|
||||
&self.endpoint,
|
||||
))
|
||||
@@ -267,10 +263,7 @@ impl DirectoryCheckpoint {
|
||||
Some(Sha256::digest(header).into())
|
||||
}
|
||||
pub(crate) fn is_bound_to(&self, info: &DataUsageCacheInfo) -> bool {
|
||||
self.bound_manifest(info).is_some()
|
||||
}
|
||||
fn bound_manifest(&self, info: &DataUsageCacheInfo) -> Option<[u8; 32]> {
|
||||
let matches_scope = self.version == 1
|
||||
self.version == 1
|
||||
&& self.scope.bucket == info.name
|
||||
&& self.scope.identity.is_valid()
|
||||
&& Some(self.scope.identity) == info.scan_identity
|
||||
@@ -283,51 +276,28 @@ impl DirectoryCheckpoint {
|
||||
.parent
|
||||
.strip_prefix(&info.name)
|
||||
.and_then(|p| p.strip_prefix('/'))
|
||||
.is_some_and(|tail| tail.split('/').all(super::valid_component)));
|
||||
if matches_scope { self.validated_manifest() } else { None }
|
||||
.is_some_and(|tail| tail.split('/').all(super::valid_component)))
|
||||
&& self.valid_payload()
|
||||
}
|
||||
pub(crate) fn scheduling_progress(
|
||||
&self,
|
||||
info: &DataUsageCacheInfo,
|
||||
) -> (Option<DirectoryReadProgress>, Option<DirectoryProgress>) {
|
||||
let Some(physical) = self.physical.as_ref() else {
|
||||
return (None, None);
|
||||
};
|
||||
if self.entries_read == 0 && self.aggregate.is_none() {
|
||||
return (None, None);
|
||||
}
|
||||
let Some(manifest) = self.bound_manifest(info) else {
|
||||
return (None, None);
|
||||
};
|
||||
let listing = (self.entries_read > 0).then(|| DirectoryReadProgress {
|
||||
parent: self.parent.clone(),
|
||||
physical: physical.clone(),
|
||||
position: (self.entries_read, self.sealed),
|
||||
});
|
||||
let compacted = self
|
||||
.aggregate
|
||||
.as_ref()
|
||||
.map(|done| self.compacted_progress(physical, manifest, &done.through));
|
||||
(listing, compacted)
|
||||
}
|
||||
fn compacted_progress(&self, physical: &Physical, manifest: [u8; 32], through: &str) -> DirectoryProgress {
|
||||
DirectoryProgress {
|
||||
parent: self.parent.clone(),
|
||||
physical: physical.clone(),
|
||||
manifest,
|
||||
through: through.to_owned(),
|
||||
}
|
||||
pub(crate) fn read_progress(&self, info: &DataUsageCacheInfo) -> Option<DirectoryReadProgress> {
|
||||
let physical = self.physical.as_ref()?;
|
||||
(self.is_bound_to(info) && (self.sealed || self.anchor.is_some()) && self.entries_read > 0).then(|| {
|
||||
DirectoryReadProgress {
|
||||
parent: self.parent.clone(),
|
||||
physical: physical.clone(),
|
||||
position: (self.entries_read, self.sealed),
|
||||
}
|
||||
})
|
||||
}
|
||||
pub(crate) fn progress(&self, info: &DataUsageCacheInfo) -> Option<DirectoryProgress> {
|
||||
let done = self.aggregate.as_ref()?;
|
||||
let physical = self.physical.as_ref()?;
|
||||
let manifest = self.bound_manifest(info)?;
|
||||
Some(self.compacted_progress(physical, manifest, &done.through))
|
||||
}
|
||||
pub(crate) fn covers_bound_path(&self, info: &DataUsageCacheInfo, path: &str) -> bool {
|
||||
self.aggregate
|
||||
.as_ref()
|
||||
.is_some_and(|done| compacted_child_covers(&self.parent, &done.through, path) && self.is_bound_to(info))
|
||||
(self.sealed && self.is_bound_to(info)).then(|| DirectoryProgress {
|
||||
parent: self.parent.clone(),
|
||||
physical: physical.clone(),
|
||||
manifest: self.manifest(),
|
||||
through: done.through.clone(),
|
||||
})
|
||||
}
|
||||
/// A display contribution contains only acknowledged compacted children.
|
||||
pub(crate) fn display_usage(&self, info: &DataUsageCacheInfo) -> Option<(DirectoryProgress, &DataUsageEntry, Option<u64>)> {
|
||||
@@ -337,16 +307,12 @@ impl DirectoryCheckpoint {
|
||||
&self.endpoint
|
||||
}
|
||||
fn valid_for(&self, parent: &str, owner: &Scope) -> bool {
|
||||
self.version == 1 && self.parent == parent && self.scope.may_adopt(owner) && self.validated_manifest().is_some()
|
||||
self.version == 1 && self.parent == parent && self.scope.may_adopt(owner) && self.valid_payload()
|
||||
}
|
||||
fn validated_manifest(&self) -> Option<[u8; 32]> {
|
||||
if !(self.physical.as_ref().is_some_and(|source| source.endpoint == self.endpoint)
|
||||
&& (self.sealed || self.anchor.is_some()))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let manifest = self.manifest();
|
||||
(self.checksum(manifest) == Some(self.digest)
|
||||
fn valid_payload(&self) -> bool {
|
||||
self.physical.as_ref().is_some_and(|source| source.endpoint == self.endpoint)
|
||||
&& (self.sealed || self.anchor.is_some())
|
||||
&& self.checksum() == Some(self.digest)
|
||||
&& self.pages.iter().all(NamePage::valid)
|
||||
&& self.part.as_deref().is_none_or(super::super::is_erasure_part_name)
|
||||
&& self.aggregate.as_ref().is_none_or(|done| {
|
||||
@@ -355,8 +321,7 @@ impl DirectoryCheckpoint {
|
||||
&& done.value.children.is_empty()
|
||||
&& done.value.failed_objects == 0
|
||||
&& self.pages.iter().any(|page| page.contains(&done.through))
|
||||
}))
|
||||
.then_some(manifest)
|
||||
})
|
||||
}
|
||||
pub(super) fn restore_allowed(&self, parent: &str, owner: &Scope, physical: &Option<Physical>) -> bool {
|
||||
self.valid_for(parent, owner)
|
||||
@@ -437,7 +402,7 @@ impl Recorder {
|
||||
digest: [0; 32],
|
||||
measured_at: work.measured_at,
|
||||
};
|
||||
checkpoint.checksum(checkpoint.manifest()).map(|digest| {
|
||||
checkpoint.checksum().map(|digest| {
|
||||
checkpoint.digest = digest;
|
||||
checkpoint
|
||||
})
|
||||
|
||||
@@ -71,9 +71,10 @@ struct LegacyCheckpoint {
|
||||
digest: [u8; 32],
|
||||
}
|
||||
|
||||
fn checkpoint_info() -> DataUsageCacheInfo {
|
||||
#[tokio::test]
|
||||
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
|
||||
let plan = crate::DataUsageScanPlanDigest([1; 32]);
|
||||
DataUsageCacheInfo {
|
||||
let info = DataUsageCacheInfo {
|
||||
name: "bucket".into(),
|
||||
source: Some(DataUsageCacheSource::new(0, 0)),
|
||||
scan_identity: Some(DataUsageScanIdentity {
|
||||
@@ -91,12 +92,7 @@ fn checkpoint_info() -> DataUsageCacheInfo {
|
||||
scan_directory_source: Some("disk-a".into()),
|
||||
last_update: Some(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(10)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_compatibility() {
|
||||
let info = checkpoint_info();
|
||||
};
|
||||
let [checkpoint, _] = DirectoryCheckpoint::storage_fixture(&info, 4, [2, 3]).await;
|
||||
assert_eq!(checkpoint.measured_at, Some(10_000));
|
||||
let bytes = rmp_serde::to_vec(&checkpoint).expect("encode additive named checkpoint");
|
||||
@@ -113,69 +109,4 @@ async fn display_progress_measurement_metadata_keeps_version_one_checkpoint_comp
|
||||
recovered.is_bound_to(&info),
|
||||
"diagnostic metadata must not change the version-one coverage checksum"
|
||||
);
|
||||
let (listing, compacted) = recovered.scheduling_progress(&info);
|
||||
assert!(listing.is_some(), "valid receipt proves listing progress");
|
||||
let compacted = compacted.expect("valid receipt proves compacted progress");
|
||||
let (display, value, _) = recovered
|
||||
.display_usage(&info)
|
||||
.expect("same validated receipt provides display usage");
|
||||
assert!(compacted.extends(&display) && display.extends(&compacted));
|
||||
assert_eq!(value.objects, 2);
|
||||
let covered = "bucket/obj-000001/nested";
|
||||
assert!(recovered.covers_bound_path(&info, covered));
|
||||
assert!(!recovered.covers_bound_path(&info, "bucket/obj-000002/nested"));
|
||||
assert!(!recovered.covers_bound_path(&info, "bucket-sibling/obj-000001"));
|
||||
let other_incarnation = DataUsageCacheInfo {
|
||||
scan_identity: info.scan_identity.map(|identity| DataUsageScanIdentity {
|
||||
bucket_incarnation: uuid::Uuid::from_u128(2),
|
||||
..identity
|
||||
}),
|
||||
..info.clone()
|
||||
};
|
||||
assert!(!recovered.covers_bound_path(&other_incarnation, covered));
|
||||
|
||||
let mut damaged = recovered;
|
||||
damaged.digest[0] ^= 1;
|
||||
assert!(matches!(damaged.scheduling_progress(&info), (None, None)));
|
||||
assert!(!damaged.covers_bound_path(&info, covered));
|
||||
assert!(damaged.display_usage(&info).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn durable_progress_checks_unordered_paths_and_each_replica() {
|
||||
let mut cache = crate::DataUsageCache {
|
||||
info: checkpoint_info(),
|
||||
..Default::default()
|
||||
};
|
||||
let [earlier, later] = DirectoryCheckpoint::storage_fixture(&cache.info, 4, [2, 3]).await;
|
||||
let receipt = |parent: &str, endpoint: &str| {
|
||||
let mut receipt = earlier.clone();
|
||||
receipt.parent = parent.to_owned();
|
||||
receipt.endpoint = endpoint.to_owned();
|
||||
receipt.physical.as_mut().expect("fixture source").endpoint = receipt.endpoint.clone();
|
||||
receipt.digest = receipt.checksum(receipt.manifest()).expect("fixture checksum");
|
||||
receipt
|
||||
};
|
||||
let covered = receipt("bucket/obj-000000/child", "disk-a");
|
||||
let uncovered = receipt("bucket/obj-000003/child", "disk-a");
|
||||
let replica = receipt("bucket", "disk-b");
|
||||
cache.info.scan_directory_work = vec![uncovered.clone(), replica.clone(), covered, earlier];
|
||||
let before = cache.durable_scan_progress();
|
||||
|
||||
cache.info.scan_directory_work = vec![uncovered, later, replica];
|
||||
assert!(
|
||||
cache.durable_scan_progress().advanced_from(&before),
|
||||
"the advanced root still covers a removed descendant and retains the other replica"
|
||||
);
|
||||
let unrelated = cache.info.scan_directory_work.remove(0);
|
||||
assert!(
|
||||
!cache.durable_scan_progress().advanced_from(&before),
|
||||
"the root frontier does not cover every sibling directory"
|
||||
);
|
||||
cache.info.scan_directory_work.pop();
|
||||
cache.info.scan_directory_work.push(unrelated);
|
||||
assert!(
|
||||
!cache.durable_scan_progress().advanced_from(&before),
|
||||
"the root on one replica cannot replace the same path on another"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -106,17 +106,14 @@ where
|
||||
context.ctx.clone(),
|
||||
)
|
||||
.await;
|
||||
let next_revisions = match checkpoint_save {
|
||||
Ok(revisions) => revisions,
|
||||
Err(error) => {
|
||||
record_checkpoint_save_failure(cache_name, checkpoint, &error);
|
||||
return if matches!(error, StorageError::PreconditionFailed) {
|
||||
ScannerCheckpointPersistResult::RetryBucket(error)
|
||||
} else {
|
||||
ScannerCheckpointPersistResult::Skipped
|
||||
};
|
||||
}
|
||||
};
|
||||
if let Err(error) = checkpoint_save {
|
||||
record_checkpoint_save_failure(cache_name, checkpoint, &error);
|
||||
return if matches!(error, StorageError::PreconditionFailed) {
|
||||
ScannerCheckpointPersistResult::RetryBucket(error)
|
||||
} else {
|
||||
ScannerCheckpointPersistResult::Skipped
|
||||
};
|
||||
}
|
||||
|
||||
if crate::remote_scanner::validate_remote_scanner_request_fence_with_store(context.cycle, context.leader_epoch, fence_store)
|
||||
.await
|
||||
@@ -128,34 +125,39 @@ where
|
||||
return ScannerCheckpointPersistResult::FenceChanged;
|
||||
}
|
||||
|
||||
let Some(mut next_revisions) = next_revisions else {
|
||||
// The previous token was consumed. A fresh lookup could observe
|
||||
// another writer's checkpoint and give its revision to this walk.
|
||||
let error = StorageError::other("scanner checkpoint commit did not confirm a primary revision");
|
||||
record_checkpoint_save_failure(cache_name, checkpoint, &error);
|
||||
return ScannerCheckpointPersistResult::RetryBucket(error);
|
||||
};
|
||||
crate::storage_api::ecstore_with_background_disk_io(
|
||||
match crate::storage_api::ecstore_with_background_disk_io(
|
||||
context.ctx.clone(),
|
||||
next_revisions.refresh_unknown_backup(store, cache_name),
|
||||
DataUsageCache::read_revisions(store, cache_name),
|
||||
)
|
||||
.await;
|
||||
*revisions = next_revisions;
|
||||
if let Some(source) = checkpoint.info.source {
|
||||
let saved =
|
||||
checkpoint
|
||||
.info
|
||||
.scan_checkpoint
|
||||
.as_ref()
|
||||
.map(|cursor| rustfs_scanner_metrics::metrics::ScannerCheckpointReport {
|
||||
version: cursor.version,
|
||||
resume_after: cursor.resume_after.clone(),
|
||||
reason: cursor.reason.as_str().to_string(),
|
||||
last_event: "saved".to_string(),
|
||||
.await
|
||||
{
|
||||
Ok(next_revisions) => {
|
||||
*revisions = next_revisions;
|
||||
if let Some(source) = checkpoint.info.source {
|
||||
let saved = checkpoint.info.scan_checkpoint.as_ref().map(|cursor| {
|
||||
rustfs_scanner_metrics::metrics::ScannerCheckpointReport {
|
||||
version: cursor.version,
|
||||
resume_after: cursor.resume_after.clone(),
|
||||
reason: cursor.reason.as_str().to_string(),
|
||||
last_event: "saved".to_string(),
|
||||
}
|
||||
});
|
||||
global_metrics().record_scanner_checkpoint_saved(source.pool_index, source.set_index, &checkpoint.info.name, saved);
|
||||
global_metrics().record_scanner_checkpoint_saved(
|
||||
source.pool_index,
|
||||
source.set_index,
|
||||
&checkpoint.info.name,
|
||||
saved,
|
||||
);
|
||||
}
|
||||
ScannerCheckpointPersistResult::Saved
|
||||
}
|
||||
Err(error) => {
|
||||
// A successful PUT consumed the old CAS revision. Reload the bucket
|
||||
// before another write instead of rebasing this scan over a newer writer.
|
||||
record_checkpoint_save_failure(cache_name, checkpoint, &error);
|
||||
ScannerCheckpointPersistResult::RetryBucket(error)
|
||||
}
|
||||
}
|
||||
ScannerCheckpointPersistResult::Saved
|
||||
}
|
||||
|
||||
fn record_checkpoint_save_failure(cache_name: &str, checkpoint: &DataUsageCache, error: &StorageError) {
|
||||
@@ -219,12 +221,12 @@ impl ScannerCacheLockGuards {
|
||||
*self = acquire_scanner_cache_locks(store.as_ref(), cache_name, source)
|
||||
.await
|
||||
.map_err(Error::other)?;
|
||||
let revisions_match = crate::storage_api::ecstore_with_background_disk_io(
|
||||
let current = crate::storage_api::ecstore_with_background_disk_io(
|
||||
cancel.clone(),
|
||||
revisions.matches_current_for_resume(store, cache_name),
|
||||
DataUsageCache::read_revisions(store, cache_name),
|
||||
)
|
||||
.await?;
|
||||
if self.is_lock_lost() || !revisions_match {
|
||||
if self.is_lock_lost() || ¤t != revisions {
|
||||
return Err(Error::other("scanner cache changed while waiting for node admission"));
|
||||
}
|
||||
// If the walk was dropped, send returns ownership and drops the
|
||||
@@ -1557,7 +1559,7 @@ pub(super) async fn persist_scanner_service_ledger(
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => true,
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
log_skipped("service_order_save_failed", &error);
|
||||
false
|
||||
|
||||
@@ -2157,7 +2157,7 @@ impl ScannerIOCache for SetDisks {
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => true,
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
if scanner_bucket_generation_is_retired(
|
||||
&store_clone_clone,
|
||||
@@ -2212,10 +2212,9 @@ impl ScannerIOCache for SetDisks {
|
||||
).await;
|
||||
bucket_observations_clone.lock().await.insert(bucket.name.clone(), observation.clone());
|
||||
}
|
||||
}
|
||||
let advanced = partial_progress_proven && cache.durable_scan_progress().advanced_from(&scan_position_before);
|
||||
if advanced {
|
||||
bucket_budget.record_durable_turn_progress();
|
||||
if partial_progress_proven && cache.durable_scan_progress().advanced_from(&scan_position_before) {
|
||||
bucket_budget.record_durable_turn_progress();
|
||||
}
|
||||
}
|
||||
if local_stop.reason().is_some() {
|
||||
// Recovery is independent of durable forward progress, but
|
||||
@@ -2244,8 +2243,9 @@ impl ScannerIOCache for SetDisks {
|
||||
}
|
||||
// Only saved forward motion earns another turn in this
|
||||
// cycle; otherwise the bucket waits for the next one.
|
||||
if advanced
|
||||
if partial_progress_proven
|
||||
&& bucket_budget.quantum_exhausted()
|
||||
&& cache.durable_scan_progress().advanced_from(&scan_position_before)
|
||||
&& requeue_bucket_work(&bucket_tx_clone, &bucket, &mut work_guard).await
|
||||
{
|
||||
increment_disk_bucket_scans_queued(
|
||||
|
||||
@@ -876,11 +876,7 @@ async fn checkpoint_uses_global_cycle_fence_with_set_scoped_cache_revisions() {
|
||||
struct CheckpointFaultStore {
|
||||
set: Arc<SetDisks>,
|
||||
fail_put: AtomicBool,
|
||||
lose_primary_response: AtomicBool,
|
||||
omit_primary_etag: AtomicBool,
|
||||
backup_unavailable: AtomicBool,
|
||||
reads: std::sync::atomic::AtomicUsize,
|
||||
backup_puts: std::sync::atomic::AtomicUsize,
|
||||
fail_revision_read: AtomicBool,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -901,9 +897,11 @@ impl crate::storage_api::owner::ObjectIO for CheckpointFaultStore {
|
||||
headers: Self::HeaderMap,
|
||||
opts: &Self::ObjectOptions,
|
||||
) -> crate::EcstoreResult<Self::GetObjectReader> {
|
||||
self.reads.fetch_add(1, Ordering::SeqCst);
|
||||
if object.ends_with(".bkp") && self.backup_unavailable.load(Ordering::SeqCst) {
|
||||
return Err(StorageError::InsufficientReadQuorum(bucket.to_string(), object.to_string()));
|
||||
if self.fail_revision_read.swap(false, Ordering::SeqCst) {
|
||||
return Err(StorageError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"injected revision read failure",
|
||||
)));
|
||||
}
|
||||
self.set.get_object_reader(bucket, object, range, headers, opts).await
|
||||
}
|
||||
@@ -921,25 +919,7 @@ impl crate::storage_api::owner::ObjectIO for CheckpointFaultStore {
|
||||
timeout: Duration::from_secs(5),
|
||||
}));
|
||||
}
|
||||
if object.ends_with(".bkp") {
|
||||
self.backup_puts.fetch_add(1, Ordering::SeqCst);
|
||||
if self.backup_unavailable.load(Ordering::SeqCst) {
|
||||
return Err(StorageError::PreconditionFailed);
|
||||
}
|
||||
}
|
||||
let mut committed = self.set.put_object(bucket, object, data, opts).await?;
|
||||
if !object.ends_with(".bkp") {
|
||||
if self.lose_primary_response.swap(false, Ordering::SeqCst) {
|
||||
return Err(StorageError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"injected lost primary PUT response",
|
||||
)));
|
||||
}
|
||||
if self.omit_primary_etag.swap(false, Ordering::SeqCst) {
|
||||
committed.etag = None;
|
||||
}
|
||||
}
|
||||
Ok(committed)
|
||||
self.set.put_object(bucket, object, data, opts).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -961,7 +941,7 @@ impl crate::ScannerConfigObjectDelete for CheckpointFaultStore {
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn checkpoint_advances_only_with_confirmed_commit_revisions() {
|
||||
async fn checkpoint_retries_next_snapshot_after_lock_failure_and_reloads_after_revision_failure() {
|
||||
let (_temp_dir, fence_store) = setup_local_scanner_store(1, 4).await;
|
||||
let cycle = 8457;
|
||||
let leader_epoch = 19;
|
||||
@@ -986,11 +966,7 @@ async fn checkpoint_advances_only_with_confirmed_commit_revisions() {
|
||||
let store = Arc::new(CheckpointFaultStore {
|
||||
set: set.clone(),
|
||||
fail_put: AtomicBool::new(true),
|
||||
lose_primary_response: AtomicBool::new(false),
|
||||
omit_primary_etag: AtomicBool::new(false),
|
||||
backup_unavailable: AtomicBool::new(false),
|
||||
reads: std::sync::atomic::AtomicUsize::new(0),
|
||||
backup_puts: std::sync::atomic::AtomicUsize::new(0),
|
||||
fail_revision_read: AtomicBool::new(false),
|
||||
});
|
||||
let ctx = CancellationToken::new();
|
||||
let context = || ScannerCheckpointPersistContext {
|
||||
@@ -1024,12 +1000,10 @@ async fn checkpoint_advances_only_with_confirmed_commit_revisions() {
|
||||
.as_mut()
|
||||
.expect("checkpoint cursor")
|
||||
.resume_after = "checkpoint-recovery/second".to_string();
|
||||
let reads = store.reads.load(Ordering::SeqCst);
|
||||
assert!(matches!(
|
||||
persist_scanner_checkpoint(store.clone(), fence_store.clone(), context(), cache_name, &checkpoint, &mut revisions).await,
|
||||
ScannerCheckpointPersistResult::Saved
|
||||
));
|
||||
assert_eq!(store.reads.load(Ordering::SeqCst), reads, "successful PUTs supply both revisions");
|
||||
assert_ne!(revisions, initial_revisions);
|
||||
let mut loaded = DataUsageCache::default();
|
||||
loaded.load(set.clone(), cache_name).await.expect("load recovered checkpoint");
|
||||
@@ -1038,75 +1012,6 @@ async fn checkpoint_advances_only_with_confirmed_commit_revisions() {
|
||||
"next snapshot must become durable"
|
||||
);
|
||||
|
||||
let path = path_join_buf(&[crate::BUCKET_META_PREFIX, cache_name]);
|
||||
let backup_path = format!("{path}.bkp");
|
||||
let backup_before = crate::data_usage_define::read_config_revision(set.clone(), &backup_path)
|
||||
.await
|
||||
.expect("read backup before losing quorum");
|
||||
let backup_puts_before = store.backup_puts.load(Ordering::SeqCst);
|
||||
for (cursor, backup_unavailable, expected_puts) in [
|
||||
("degraded", true, backup_puts_before + 1),
|
||||
("quorum-restored", false, backup_puts_before + 1),
|
||||
("backup-updated", false, backup_puts_before + 2),
|
||||
] {
|
||||
checkpoint.info.scan_checkpoint = Some(crate::DataUsageScanCheckpoint::new(
|
||||
format!("checkpoint-recovery/{cursor}"),
|
||||
crate::DataUsageScanCheckpointReason::Objects,
|
||||
));
|
||||
store.backup_unavailable.store(backup_unavailable, Ordering::SeqCst);
|
||||
if cursor == "quorum-restored" {
|
||||
assert!(
|
||||
revisions
|
||||
.matches_current_for_resume(store.clone(), cache_name)
|
||||
.await
|
||||
.expect("revalidate the primary with a now-readable backup"),
|
||||
"backup recovery must allow the same walk to resume after yielding the cache lease"
|
||||
);
|
||||
}
|
||||
let result =
|
||||
persist_scanner_checkpoint(store.clone(), fence_store.clone(), context(), cache_name, &checkpoint, &mut revisions)
|
||||
.await;
|
||||
assert!(matches!(result, ScannerCheckpointPersistResult::Saved), "{cursor}: {result:?}");
|
||||
assert_eq!(
|
||||
store.backup_puts.load(Ordering::SeqCst),
|
||||
expected_puts,
|
||||
"{cursor}: only attempt a backup write with a known revision"
|
||||
);
|
||||
loaded
|
||||
.load(set.clone(), cache_name)
|
||||
.await
|
||||
.expect("load latest durable cursor");
|
||||
assert_eq!(loaded.info.scan_checkpoint, checkpoint.info.scan_checkpoint, "{cursor}");
|
||||
}
|
||||
let backup_after = crate::data_usage_define::read_config_revision(set.clone(), &backup_path)
|
||||
.await
|
||||
.expect("read backup after it becomes writable again");
|
||||
assert_ne!(backup_before, backup_after);
|
||||
|
||||
checkpoint
|
||||
.info
|
||||
.scan_checkpoint
|
||||
.as_mut()
|
||||
.expect("checkpoint cursor")
|
||||
.resume_after = "checkpoint-recovery/lost-response".to_string();
|
||||
let reads = store.reads.load(Ordering::SeqCst);
|
||||
store.lose_primary_response.store(true, Ordering::SeqCst);
|
||||
assert!(matches!(
|
||||
persist_scanner_checkpoint(store.clone(), fence_store.clone(), context(), cache_name, &checkpoint, &mut revisions).await,
|
||||
ScannerCheckpointPersistResult::Saved
|
||||
));
|
||||
assert_eq!(
|
||||
store.reads.load(Ordering::SeqCst),
|
||||
reads + 1,
|
||||
"reconciliation supplies the matching object's ETag"
|
||||
);
|
||||
assert_eq!(
|
||||
revisions,
|
||||
DataUsageCache::read_revisions(set.clone(), cache_name)
|
||||
.await
|
||||
.expect("committed revisions")
|
||||
);
|
||||
|
||||
let saved_revisions = revisions.clone();
|
||||
checkpoint
|
||||
.info
|
||||
@@ -1114,18 +1019,12 @@ async fn checkpoint_advances_only_with_confirmed_commit_revisions() {
|
||||
.as_mut()
|
||||
.expect("checkpoint cursor")
|
||||
.resume_after = "checkpoint-recovery/third".to_string();
|
||||
let reads = store.reads.load(Ordering::SeqCst);
|
||||
store.omit_primary_etag.store(true, Ordering::SeqCst);
|
||||
store.fail_revision_read.store(true, Ordering::SeqCst);
|
||||
assert!(matches!(
|
||||
persist_scanner_checkpoint(store.clone(), fence_store, context(), cache_name, &checkpoint, &mut revisions).await,
|
||||
ScannerCheckpointPersistResult::RetryBucket(_)
|
||||
persist_scanner_checkpoint(store, fence_store, context(), cache_name, &checkpoint, &mut revisions).await,
|
||||
ScannerCheckpointPersistResult::RetryBucket(StorageError::Io(_))
|
||||
));
|
||||
assert_eq!(
|
||||
store.reads.load(Ordering::SeqCst),
|
||||
reads,
|
||||
"do not adopt a primary revision from a later read"
|
||||
);
|
||||
assert_eq!(revisions, saved_revisions, "a missing commit revision must not rebase the writer");
|
||||
assert_eq!(revisions, saved_revisions, "indeterminate revision refresh must not rebase the writer");
|
||||
loaded
|
||||
.load(set.clone(), cache_name)
|
||||
.await
|
||||
|
||||
+23
-109
@@ -13,8 +13,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
use super::{DiskInfo, IOStats, fs_type::get_fs_type};
|
||||
use rustix::fs::{AtFlags, Mode, OFlags, StatFs, StatxAttributes, StatxFlags, fstatfs, open, statfs, statx};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use rustix::fs::statfs;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufRead, Error, ErrorKind, Read};
|
||||
@@ -27,10 +27,27 @@ static BAVAIL_GT_BFREE_WARNING_PATHS: OnceLock<Mutex<BTreeSet<PathBuf>>> = OnceL
|
||||
/// Returns total and free bytes available in a directory, e.g. `/`.
|
||||
pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
|
||||
// Use statfs on Linux to get access to f_type (filesystem magic number)
|
||||
let path = p.as_ref();
|
||||
let stat = statfs(path)?;
|
||||
let (total, free, used) = statfs_space_usage(&stat, path)?;
|
||||
let st = rustix::fs::stat(path)?;
|
||||
let stat = statfs(p.as_ref())?;
|
||||
|
||||
// Linux statfs:
|
||||
// f_bsize: Optimal transfer block size
|
||||
// f_blocks: Total data blocks in file system
|
||||
// f_frsize: Fragment size (since Linux 2.6) - unit for blocks
|
||||
//
|
||||
// If f_frsize is > 0, it is the unit for f_blocks, f_bfree, f_bavail.
|
||||
// Otherwise f_bsize is used.
|
||||
let bsize = if stat.f_frsize > 0 {
|
||||
stat.f_frsize as u64
|
||||
} else {
|
||||
stat.f_bsize as u64
|
||||
};
|
||||
|
||||
let bfree = stat.f_bfree as u64;
|
||||
let bavail = stat.f_bavail as u64;
|
||||
let blocks = stat.f_blocks as u64;
|
||||
let (total, free, used) = calculate_space_usage(blocks, bfree, bavail, bsize, p.as_ref())?;
|
||||
|
||||
let st = rustix::fs::stat(p.as_ref())?;
|
||||
|
||||
Ok(DiskInfo {
|
||||
total,
|
||||
@@ -45,84 +62,6 @@ pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
|
||||
})
|
||||
}
|
||||
|
||||
fn statfs_space_usage(stat: &StatFs, path: &Path) -> io::Result<(u64, u64, u64)> {
|
||||
// Block counts are in fragment-size units when the kernel provides them.
|
||||
let block_size = if stat.f_frsize > 0 { stat.f_frsize } else { stat.f_bsize };
|
||||
calculate_space_usage(stat.f_blocks, stat.f_bfree, stat.f_bavail, block_size as u64, path)
|
||||
}
|
||||
|
||||
/// Snapshot of Linux whole-filesystem mount eligibility for one refresh.
|
||||
///
|
||||
/// The mount table is read lazily when the first candidate mount root is
|
||||
/// probed. The caller is responsible for ensuring exclusive use of the filesystem.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MountUsageSnapshot(OnceLock<Option<HashMap<u64, (u32, u32)>>>);
|
||||
|
||||
impl MountUsageSnapshot {
|
||||
/// Return filesystem-reported used bytes for a directory at an eligible mount root.
|
||||
///
|
||||
/// Direct accounting is supported for XFS, the ext family, and tmpfs.
|
||||
/// Returns `None` when the mount or its filesystem type is ineligible
|
||||
/// or the kernel cannot identify or read the mounted filesystem.
|
||||
pub fn used_bytes(&self, path: &Path) -> Option<u64> {
|
||||
let directory = open(path, OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).ok()?;
|
||||
let stat = statx(&directory, "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID).ok()?;
|
||||
if !StatxFlags::from_bits_retain(stat.stx_mask).contains(StatxFlags::MNT_ID)
|
||||
|| !stat.stx_attributes.contains(StatxAttributes::MOUNT_ROOT)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mounts = self
|
||||
.0
|
||||
.get_or_init(|| {
|
||||
let mountinfo = fs::read("/proc/self/mountinfo").ok()?;
|
||||
eligible_usage_mounts(&String::from_utf8_lossy(&mountinfo))
|
||||
})
|
||||
.as_ref()?;
|
||||
if mounts.get(&stat.stx_mnt_id) != Some(&(stat.stx_dev_major, stat.stx_dev_minor)) {
|
||||
return None;
|
||||
}
|
||||
// Read the same mount that was classified, even if the path was replaced.
|
||||
let stat = fstatfs(directory).ok()?;
|
||||
if !supports_direct_mount_usage(stat.f_type as u64) {
|
||||
return None;
|
||||
}
|
||||
let (_, _, used) = statfs_space_usage(&stat, path).ok()?;
|
||||
Some(used)
|
||||
}
|
||||
}
|
||||
|
||||
fn supports_direct_mount_usage(fs_type: u64) -> bool {
|
||||
// Distinct mount and device IDs do not establish independent block
|
||||
// accounting on filesystems that share a pool across subvolumes.
|
||||
matches!(get_fs_type(fs_type), "XFS" | "EXT4" | "TMPFS")
|
||||
}
|
||||
|
||||
fn eligible_usage_mounts(mountinfo: &str) -> Option<HashMap<u64, (u32, u32)>> {
|
||||
let mut devices = HashMap::new();
|
||||
let mut parents = HashSet::new();
|
||||
for line in mountinfo.lines() {
|
||||
let mut fields = line.split_ascii_whitespace();
|
||||
let id: u64 = fields.next()?.parse().ok()?;
|
||||
let parent: u64 = fields.next()?.parse().ok()?;
|
||||
let (major, minor) = fields.next()?.split_once(':')?;
|
||||
let device = (major.parse().ok()?, minor.parse().ok()?);
|
||||
let root = fields.next()?;
|
||||
parents.insert(parent);
|
||||
// A second view of the same device may alias accounting for the whole filesystem.
|
||||
devices
|
||||
.entry(device)
|
||||
.and_modify(|mount| *mount = None)
|
||||
.or_insert((root == "/").then_some(id));
|
||||
}
|
||||
Some(
|
||||
devices
|
||||
.into_iter()
|
||||
.filter_map(|(device, id)| id.filter(|id| !parents.contains(id)).map(|id| (id, device)))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn calculate_space_usage(blocks: u64, bfree: u64, bavail: u64, bsize: u64, path: &Path) -> std::io::Result<(u64, u64, u64)> {
|
||||
let available = if bfree < bavail {
|
||||
if should_warn_bavail_greater_than_bfree(path) {
|
||||
@@ -511,31 +450,6 @@ mod tests {
|
||||
assert_eq!(mountinfo_path(line), Some("/data/replacement"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mount_usage_requires_a_unique_whole_filesystem_with_no_child_mounts() {
|
||||
let mountinfo = "\
|
||||
1 0 0:1 / / rw - overlay overlay rw\n\
|
||||
2 1 0:2 / /data/whole rw - tmpfs tmpfs rw\n\
|
||||
3 1 0:3 /subdir /data/bind rw - tmpfs tmpfs rw\n\
|
||||
4 1 0:4 / /data/parent rw - tmpfs tmpfs rw\n\
|
||||
5 4 0:5 / /data/parent/child rw - tmpfs tmpfs rw\n\
|
||||
6 1 0:6 / /data/alias1 rw - tmpfs tmpfs rw\n\
|
||||
7 1 0:6 / /data/alias2 rw - tmpfs tmpfs rw";
|
||||
assert_eq!(eligible_usage_mounts(mountinfo), Some(HashMap::from([(2, (0, 2)), (5, (0, 5))])));
|
||||
assert!(eligible_usage_mounts("1 0 no-device /").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mount_usage_uses_only_filesystems_with_independent_block_accounting() {
|
||||
assert!(supports_direct_mount_usage(0x58465342)); // XFS
|
||||
assert!(supports_direct_mount_usage(0xEF53)); // ext family
|
||||
assert!(supports_direct_mount_usage(0x01021994)); // tmpfs
|
||||
assert!(!supports_direct_mount_usage(0x9123683E)); // Btrfs
|
||||
assert!(!supports_direct_mount_usage(0x2FC12FC1)); // ZFS
|
||||
assert!(!supports_direct_mount_usage(0x794C7630)); // OverlayFS
|
||||
assert!(!supports_direct_mount_usage(0x6969)); // NFS
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reject_relative_path_for_cross_device_validation() {
|
||||
let err = ensure_no_sub_mounts("relative/path", &[]).unwrap_err();
|
||||
|
||||
@@ -24,9 +24,7 @@ mod unix;
|
||||
mod windows;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use linux::{
|
||||
MountUsageSnapshot, check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk,
|
||||
};
|
||||
pub use linux::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
|
||||
|
||||
#[cfg(all(unix, not(target_os = "linux")))]
|
||||
pub use unix::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
|
||||
|
||||
+1
-2
@@ -16,8 +16,7 @@ collection:
|
||||
- [Read-only BTF declaration inspection](operations/btf-prototype-inspection.md) — bounded prototypes and scalar member layouts, explicit void handling, and independent native references.
|
||||
|
||||
- [Internode HTTP streaming transport](operations/internode-http-transport.md) — protocol selection, pooled connection isolation, and distributed read validation.
|
||||
- [S3-over-RDMA on NIXL/UCX](operations/nixl-s3-over-rdma.md) — optional `nixl` feature: GET, PUT, UploadPart, and internode shard traffic over NIXL/UCX into client GPU or host memory; build, settings, wire contract, and large-PUT tuning.
|
||||
- [cuObject S3-over-RDMA](operations/cuobject-s3-over-rdma.md) — optional `cuobject` feature: GET, PUT, and UploadPart straight into client GPU/host memory via `x-amz-rdma-token` and GDS `cufile.json`; build, settings, wire contract.
|
||||
- [cuObject S3-over-RDMA GET](operations/cuobject-s3-over-rdma.md) — optional `cuobject` feature: GET straight into client GPU/host memory via `x-amz-rdma-token`; build, settings, wire contract.
|
||||
- [Erasure shard size](operations/erasure-shard-size.md) — `RUSTFS_ERASURE_SHARD_BYTES`: larger, aligned shards for new objects; rules and memory cost.
|
||||
- [Object data cache fill on PUT](operations/object-data-cache-fill-on-put.md) — `RUSTFS_OBJECT_DATA_CACHE_FILL_ON_PUT`: insert plain streaming PUT bodies so the first GET hits.
|
||||
|
||||
|
||||
@@ -21,8 +21,7 @@ This document describes the design and the invariants of RustFS's S3-over-RDMA d
|
||||
|---|---|---|
|
||||
| Client last hop, cuObject | `rustfs/src/app/object/cuobject.rs`, `crates/cuobject`, `crates/cuobject-sys` | The `cuobject` feature enables `x-amz-rdma-token` transfers. `rustfs-cuobject` manages registered buffers and transfers. `rustfs-cuobject-sys` builds the C++ bridge and links the NVIDIA server SDK. |
|
||||
| Client last hop, NIXL | `crates/nixl/src/lib.rs` (`RdmaToken::from_headers`), `crates/nixl/src/remotes.rs`, `crates/nixl/src/mem.rs` | NIXL/UCX transport selected by the `nixl` feature. The client names a registered `dram` or `vram` buffer; the server WRITEs (GET) or READs (PUT) it. |
|
||||
| Passive NIXL client SDK | `crates/nixl/src/client.rs` (`RegisteredClientWindow`, `ClientWindowHttp`) | Optional `client-http` feature on `rustfs-nixl`: exclusively owned passive host windows that sign and verify one-shot S3 RDMA control exchanges and quarantine memory on indeterminate outcomes. |
|
||||
| Shared pipeline | `rustfs/src/app/object/cuobject.rs` | Segment fan-out of large plain GETs, staging chunks, shard arena, completion handling. The same pipeline serves both transports; compressed and encrypted objects bypass segmented zero-copy emit and stream sequentially over RDMA. |
|
||||
| Shared pipeline | `rustfs/src/app/object/cuobject.rs` | Segment fan-out of large GETs, staging chunks, shard arena, completion handling. The same pipeline serves both transports; only the transfer layer differs. |
|
||||
| Device health | `crates/nixl/src/devices.rs` | Startup check that leaves out RDMA devices that are down, slow or flapping. |
|
||||
| Internode, NIXL | `crates/ecstore/src/cluster/rpc/nixl_internode.rs`, `rustfs/src/storage/rpc/nixl_read.rs` | `RUSTFS_INTERNODE_DATA_TRANSPORT=nixl`: signed control request over HTTP, data over NIXL, for shard reads and writes. |
|
||||
| Transport selection | `crates/ecstore/src/cluster/rpc/internode_data_transport.rs` | `tcp-http`, `tcp` or `nixl`. Internode RDMA runs over NIXL. |
|
||||
@@ -34,7 +33,7 @@ This document describes the design and the invariants of RustFS's S3-over-RDMA d
|
||||
## Design decisions
|
||||
|
||||
- **Signed S3 request, RDMA payload.** The client sends a normal signed S3 request whose body is empty. Three headers name its NIXL agent, its agent metadata and one registered buffer. The reply comes back only after the last transfer completed, so the client may use its buffer as soon as the response arrives. Clients sign with `UNSIGNED-PAYLOAD`, because the payload never crosses HTTP.
|
||||
- **NIXL/UCX is the preferred compile-time RDMA backend.** Neither `nixl` nor `cuobject` is enabled in default builds; when both features are compiled together, `nixl` takes precedence. UCX addresses devices by GID, LID and queue-pair numbers carried in the agent metadata, which works on GPU-side InfiniBand rails without IPoIB or a subnet manager and on RoCE without `rdma_cm`. cuObject remains a compile-time alternative for NVIDIA GPUDirect Storage `x-amz-rdma-token` clients.
|
||||
- **NIXL/UCX replaced cuObject as the default.** UCX addresses devices by GID, LID and queue-pair numbers carried in the agent metadata. That works on the GPU-side InfiniBand rails without IPoIB or a subnet manager, and on RoCE without `rdma_cm`. cuObject stays as a compile-time alternative.
|
||||
- **GPU or host memory.** A `vram:<gpu>:<addr>:<len>` buffer works when the client's NIC can reach GPU memory (GPUDirect over dma-buf with the open NVIDIA driver; `nvidia_peermem` is not needed). The server does not need to know which kind it is writing into.
|
||||
- **Ranges are first class.** A ranged GET lands at offset 0 of the named buffer. Clients split large objects into ranged requests spread over servers to raise parallelism.
|
||||
- **Internode traffic on the same rails.** With `nixl` internode transport, every shard read and write between servers also moves over NIXL. The control request stays on the internode HTTP connection and binds the transfer with a signed metadata digest (and a one-time nonce for writes), so a replayed request cannot redirect a transfer.
|
||||
@@ -52,7 +51,7 @@ This document describes the design and the invariants of RustFS's S3-over-RDMA d
|
||||
|
||||
## Clients
|
||||
|
||||
`crates/nixl` (`client-http` feature, `RegisteredClientWindow`) provides the passive host-window primitive consumed by external Rust clients such as `rustfs/cli`, quarantining registered pages until process exit whenever a transfer lacks a verified completion receipt or pre-DMA conditional rejection. Higher-level LLM-serving clients live outside this repository and shaped this data path's requirements:
|
||||
Clients live outside this repository. Two LLM-serving clients were built against this path and shaped its requirements:
|
||||
|
||||
- **Model weight loading into GPU memory.** The loader plans a checkpoint into whole-tensor units, fetches each unit with several ranged NIXL GETs spread over the servers straight into GPU memory, and shares it with the other ranks over NCCL. No checkpoint byte touches disk or host memory, so ranged GETs into `vram` buffers and many concurrent requests per client are the hot path.
|
||||
- **KV-cache offload.** A hierarchical-cache backend writes groups of KV pages (tens of MB each) once per prefill and reads them back from any node. It needs cheap existence checks, PUTs that return only after the bytes are durable enough for the bucket's durability setting, and ETags that do not cost an MD5 per object, hence per-bucket XXH3 ETags and relaxed durability.
|
||||
|
||||
@@ -25,7 +25,17 @@ its degraded fallback until their quota is migrated.
|
||||
|
||||
## Rationale
|
||||
|
||||
The ledger already carries the write-path accounting that the 2026-09-03 decision assumed only the scanner could provide: an exact baseline, per-write reservations settled at commit, and a recount request when a write that fits the limit is denied or an admission crosses 90% of it, subject to the persisted retry throttle and, on a multi-pool store, only while no reservation is pending. On a single-pool store whose ledger still matches the quota, a recount that overlaps other writes publishes its scan plus the net growth admitted since its seed, including reservations already pending at the seed, so it can over-count but not under-count; it clears a pending reconcile request only if no writer saved the ledger during the walk. It publishes nothing if an older node rewrote the ledger meanwhile, because that save drops the recount's seed. A multi-pool store keeps the strict rule that discards any recount another writer overlapped, and that rule is not a fence for pool moves, which publish versions without writing the ledger. With the admission decision made there, keeping scanner usage authoritative buys no enforcement and costs every deployment the proof machinery that makes a distributed background scan safe to feed a quota: leases that reject pending PUT commits, observed-versus-authoritative routing, and a usage floor whose unreadability stops the scanner. Buckets without a configured quota never read usage at all (`check_quota_with_usage_reporting` returns on the zero-I/O path), so the authority protected a narrow case while blocking usage statistics, lifecycle discovery, and heal discovery for everyone.
|
||||
The ledger already carries the write-path accounting that the 2026-09-03
|
||||
decision assumed only the scanner could provide: an exact baseline, per-write
|
||||
reservations settled at commit, and a reconcile step after a denial. With the
|
||||
admission decision made there, keeping scanner usage authoritative buys no
|
||||
enforcement and costs every deployment the proof machinery that makes a
|
||||
distributed background scan safe to feed a quota: leases that reject pending
|
||||
PUT commits, observed-versus-authoritative routing, and a usage floor whose
|
||||
unreadability stops the scanner. Buckets without a configured quota never read
|
||||
usage at all (`check_quota_with_usage_reporting` returns on the zero-I/O path),
|
||||
so the authority protected a narrow case while blocking usage statistics,
|
||||
lifecycle discovery, and heal discovery for everyone.
|
||||
|
||||
## Consequences
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Tier Stats Contract
|
||||
|
||||
**Use this when:** changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request, inventory snapshot, or rolling transition counter.
|
||||
**Source of truth:** `rustfs/src/admin/handlers/tier.rs` (`GetTierInfo`, `tier_stats_body`), `crates/ecstore/src/services/notification_sys.rs` (`ClusterTierDailyStats`), `crates/ecstore/src/bucket/lifecycle/tier_last_day_stats.rs` (`LastDayTierStats`), `crates/ecstore/src/services/tier/warm_backend.rs` (`MeteredWarmBackend`), `crates/obs/src/metrics/schema/tier.rs`, `crates/obs/src/metrics/collectors/tier.rs`, `crates/obs/src/metrics/stats_collector.rs`, `crates/obs/src/metrics/scheduler.rs`.
|
||||
**Use this when:** changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request.
|
||||
**Source of truth:** `rustfs/src/admin/handlers/tier.rs` (`GetTierInfo`, `tier_stats_body`), `crates/ecstore/src/services/notification_sys.rs` (`ClusterTierDailyStats`), `crates/ecstore/src/bucket/lifecycle/tier_last_day_stats.rs` (`LastDayTierStats`), `crates/ecstore/src/services/tier/warm_backend.rs` (`MeteredWarmBackend`), `crates/obs/src/metrics/schema/tier.rs`.
|
||||
|
||||
## Two quantities, never one
|
||||
|
||||
@@ -41,15 +41,3 @@ The label set is closed by two enums in `crates/scanner-metrics/src/metrics.rs`:
|
||||
`timeout` and `cancelled` are recognised from `std::io::ErrorKind`, never from an error message, so a message that mentions an endpoint cannot reach a label. Until the transition client grows bounded deadlines (rustfs/backlog#2204), few failures actually carry `TimedOut`, so most land in `backend_error`; the classification is the seam that work extends, not a claim that timeouts are already distinguishable.
|
||||
|
||||
The outcome classifies the request only. A transition whose remote PUT succeeded and whose local commit then failed is a `success` here: the remote service did perform the request, and recording it as a tier failure would hide a leaked remote object behind an apparent backend outage. Local commit failure is observable through the ILM task-event metrics instead.
|
||||
|
||||
## Tier inventory and transition metrics
|
||||
|
||||
Periodic OTLP gauges in `crates/obs/src/metrics/schema/tier.rs` expose the same two quantities as `GET /rustfs/admin/v3/tier-stats` whenever at least one remote tier is configured:
|
||||
|
||||
- **Cluster-wide stored inventory** — `rustfs_tier_inventory_bytes`, `rustfs_tier_inventory_objects_count`, and `rustfs_tier_inventory_versions_count` carry `tier` and `tier_type` labels for configured remote tiers present in `DataUsageInfo::tier_stats`. Local storage classes (`STANDARD`, `REDUCED_REDUNDANCY`) and unconfigured tiers are excluded so summing cold-tier inventory does not include hot local data.
|
||||
- **Inventory accounting status** — `rustfs_tier_inventory_accounted` (unlabeled, snapshot-wide) reports `1` when the persisted usage snapshot carries `tier_stats` and `0` when it is `not-accounted` or `unavailable`. Whenever status is `0` or a configured tier is absent from `DataUsageInfo::tier_stats`, per-tier inventory gauges are omitted and never fabricated as `0`.
|
||||
- **Node-local rolling 24h activity** — `rustfs_tier_transitions_last24h_bytes` and `rustfs_tier_transitions_last24h_objects_count` carry `tier` and `tier_type` labels and export each node's local `LastDayTierStats` ring aged forward to the current UTC hour (`merge(LastDayTierStats::default())`). Exporting node-local values avoids periodic all-to-all internode RPCs during metric scrapes; Prometheus/OTLP consumers sum across reporting nodes (`sum by (rustfs_cluster_id, tier, tier_type)`).
|
||||
|
||||
Unlike hot-path request counters (`rustfs_tier_requests_*`), these periodic snapshot gauges carry configured remote tier names (`tier`) and lowercase provider types (`tier_type`), matching the bounded cardinality of configured tiers. Endpoints, credentials, and object keys remain strictly forbidden as labels.
|
||||
|
||||
Inventory and transition gauges are published through an unscoped `StorageSnapshotMetrics` instance without zero tombstones: removing a tier or losing inventory accounting withdraws the series immediately rather than emitting synthetic zeros. See [bucket usage metrics](../operations/bucket-usage-metrics.md#remote-tier-inventory-and-transition-metrics) for query examples and the relationship to `rustfs_cluster_usage_buckets_total_bytes`.
|
||||
|
||||
@@ -104,47 +104,6 @@ usage snapshot. A shorter scrape interval cannot repair an incomplete scanner
|
||||
snapshot. The scanner publication and cache path is shared with the Console's
|
||||
usage display.
|
||||
|
||||
## Remote tier inventory and transition metrics
|
||||
|
||||
When at least one remote tier is configured, RustFS exports six OpenTelemetry gauges aligned with `GET /rustfs/admin/v3/tier-stats` (see [tier stats contract](../architecture/tier-stats-contract.md)) from the same cached scanner usage snapshot and local 24-hour transition ring:
|
||||
|
||||
| Metric | Labels | Scope | Admin API mapping (`GET /rustfs/admin/v3/tier-stats`) |
|
||||
|---|---|---|---|
|
||||
| `rustfs_tier_inventory_bytes` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.totalSize` |
|
||||
| `rustfs_tier_inventory_objects_count` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.numObjects` |
|
||||
| `rustfs_tier_inventory_versions_count` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.numVersions` |
|
||||
| `rustfs_tier_inventory_accounted` | *(none)* | Cluster-wide snapshot | `1` when `inventory.status == "accounted"`, else `0` |
|
||||
| `rustfs_tier_transitions_last24h_bytes` | `tier`, `tier_type` | Node-local rolling 24h | Node contribution to `tiers[].transitionsLast24h.totalSize` |
|
||||
| `rustfs_tier_transitions_last24h_objects_count` | `tier`, `tier_type` | Node-local rolling 24h | Node contribution to `tiers[].transitionsLast24h.numObjects` |
|
||||
|
||||
### How bucket usage, local disk capacity, and cold-tier inventory relate
|
||||
|
||||
- **Bucket logical usage** (`rustfs_cluster_usage_buckets_total_bytes`) counts logical bytes across retained versions in the bucket, including versions transitioned to remote tiers (excluding delete markers and erasure-coding overhead).
|
||||
- **Remote tier inventory** (`rustfs_tier_inventory_bytes`) is the subset of logical bytes currently accounted on a configured remote tier. It excludes local storage classes (`STANDARD`, `REDUCED_REDUNDANCY`) and does not reconcile the entire remote bucket's physical billing total outside RustFS accounting.
|
||||
- **Local physical or usable disk capacity** reflects data stored on local cluster drives (including erasure-coding parity and compression) and excludes object payloads already transitioned to remote tiers.
|
||||
|
||||
### Querying remote tier gauges
|
||||
|
||||
Because every node exports the same cluster-wide inventory snapshot, deduplicate reporting nodes instead of summing them, and guard queries with `rustfs_tier_inventory_accounted == 1`:
|
||||
|
||||
```promql
|
||||
max by (rustfs_cluster_id, tier, tier_type) (
|
||||
rustfs_tier_inventory_bytes{rustfs_cluster_id="production-a"}
|
||||
) and on (rustfs_cluster_id) (
|
||||
max by (rustfs_cluster_id) (rustfs_tier_inventory_accounted{rustfs_cluster_id="production-a"}) == 1
|
||||
)
|
||||
```
|
||||
|
||||
Because each node exports only its own committed transitions from the rolling 24-hour ring (aged forward to the current UTC hour), sum across reporting nodes for the cluster total:
|
||||
|
||||
```promql
|
||||
sum by (rustfs_cluster_id, tier, tier_type) (
|
||||
rustfs_tier_transitions_last24h_bytes{rustfs_cluster_id="production-a"}
|
||||
)
|
||||
```
|
||||
|
||||
When `inventory.status` is `not-accounted` or `unavailable`, or when a newly configured tier has not yet appeared in the scanner snapshot, RustFS omits `rustfs_tier_inventory_{bytes,objects_count,versions_count}` rather than publishing `0`. When no remote tiers are configured, none of these six gauges are exported.
|
||||
|
||||
## Regression checks
|
||||
|
||||
The SDK test uses the production bucket collector and an actual OpenTelemetry
|
||||
@@ -155,12 +114,6 @@ usage, and removal from subsequent exports:
|
||||
RUSTUP_TOOLCHAIN=stable cargo test -p rustfs-obs actual_sdk_exports_bucket_size_and_object_count_as_current_gauges --lib
|
||||
```
|
||||
|
||||
The tier SDK regression test verifies accounted remote-tier inventory, decreasing values, tier removal, and withdrawal of inventory gauges when the snapshot becomes unaccounted:
|
||||
|
||||
```bash
|
||||
RUSTUP_TOOLCHAIN=stable cargo test -p rustfs-obs actual_sdk_exports_tier_inventory_and_transitions_without_fabricating_zeros --lib
|
||||
```
|
||||
|
||||
The PromQL fixture checks same-name buckets in separate clusters and multiple
|
||||
reporting nodes. Run it from `.docker/observability/tests`:
|
||||
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
# cuObject S3-over-RDMA (GPUDirect Storage object transport)
|
||||
# cuObject S3-over-RDMA GET (last hop into client memory)
|
||||
|
||||
RustFS can serve `GetObject`, `PutObject`, and `UploadPart` over NVIDIA's GPUDirect Storage (GDS) cuObject protocol: the client (for example the NIXL `OBJ` plugin used by the SGLang `--load-format rdma` loader, or `rc --rdma-backend cuobject`) registers its GPU (`VRAM`) or host buffer with the cuObject client library, puts the resulting RDMA descriptor in the `x-amz-rdma-token` request header, and RustFS moves the object bytes directly to or from that buffer with one-sided RDMA operations. The HTTP message carries no payload body.
|
||||
RustFS can serve `GetObject` over NVIDIA's cuObject protocol: the client
|
||||
(for example the NIXL `OBJ` plugin used by the SGLang `--load-format rdma`
|
||||
loader) registers its GPU or host buffer with the cuObject client library,
|
||||
puts the resulting RDMA token in the `x-amz-rdma-token` request header, and
|
||||
RustFS writes the object bytes straight into that buffer with one-sided RDMA
|
||||
writes. The HTTP response carries no body.
|
||||
|
||||
This is the Phase 1 "last hop" of the S3-over-RDMA plan. It is independent of
|
||||
the internode shard transport selected by `RUSTFS_INTERNODE_DATA_TRANSPORT`;
|
||||
@@ -17,7 +22,9 @@ architecture. A default build does not require the NVIDIA SDK.
|
||||
CUOBJSERVER_ROOT=/usr cargo build --release -p rustfs --features cuobject
|
||||
```
|
||||
|
||||
The binary dynamically links `libcuobjserver.so.2`; keep it on the library path at run time and raise the locked-memory limit (`ulimit -l unlimited` or systemd `LimitMEMLOCK=infinity`) so the server can pin `RUSTFS_CUOBJECT_POOL_BYTES` and any shard arena. Without the feature (or when both `nixl` and `cuobject` features are compiled together, in which case `nixl` takes precedence) every `cuobject` setting below is ignored and `x-amz-rdma-token` is left untouched.
|
||||
The binary dynamically links `libcuobjserver.so.2`; keep it on the library
|
||||
path at run time. Without the feature every setting below is ignored and
|
||||
tokens are left untouched, so the client falls back to a normal HTTP GET.
|
||||
|
||||
## Settings
|
||||
|
||||
@@ -26,13 +33,8 @@ The binary dynamically links `libcuobjserver.so.2`; keep it on the library path
|
||||
| `RUSTFS_CUOBJECT_ENABLE` | `false` | Start the cuObject servers and honour `x-amz-rdma-token`. |
|
||||
| `RUSTFS_CUOBJECT_ADDRS` | local endpoint hosts | Comma-separated RDMA (RoCE/IB) IPs to serve from; one cuObject server per address. |
|
||||
| `RUSTFS_CUOBJECT_PORT` | `18515` | cuObject control port; the client never dials it directly with the DC transport. |
|
||||
| `RUSTFS_CUOBJECT_CHUNK_BYTES` | `16 MiB` | Staging chunk: the object is streamed into registered host memory in chunks of this size and each chunk is moved with one RDMA operation. Max 1 GiB. |
|
||||
| `RUSTFS_CUOBJECT_CHUNK_BYTES` | `16 MiB` | Staging chunk: the object is streamed into registered host memory in chunks of this size and each chunk is written to the client with one RDMA operation. Max 1 GiB. |
|
||||
| `RUSTFS_CUOBJECT_INFLIGHT_WRITES` | `3` | Staging chunks per GET: while one chunk is being RDMA-written the decoder keeps filling the next ones, so the stripe loop never waits for a write. Each costs one chunk of the pool; a busy pool degrades to fewer chunks rather than failing the GET. |
|
||||
| `RUSTFS_CUOBJECT_PUT_READ_AHEAD` | `4` | Staging chunks RDMA-read ahead of the consumer per PUT or UploadPart; each holds one chunk of the pool. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT` | `8` | Concurrent erasure-block-aligned segments one plain GET can split into on the server (`1` disables fan-out). Compressed and encrypted objects stream sequentially over RDMA. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES` | `192 MiB` | Smallest segment size (in bytes, rounded up to whole erasure blocks) eligible for its own segment producer. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT_BUDGET` | `16` | Total extra segment producers shared across concurrent RDMA GETs on the node. |
|
||||
| `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES` | `0` | Registered host memory (in bytes, `0` disables; otherwise at least `RUSTFS_ERASURE_SHARD_BYTES`, default `4 MiB`) for zero-copy erasure shard emission. Registered on the first configured cuObject server; requests routed to additional `RUSTFS_CUOBJECT_ADDRS` fall back to staging chunks. |
|
||||
| `RUSTFS_CUOBJECT_POOL_BYTES` | `1 GiB` | Registered staging pool per server; bounds concurrent RDMA GETs to about `pool / (chunk x inflight)`. |
|
||||
| `RUSTFS_CUOBJECT_NUM_DCIS` | `128` | DC initiators the server library opens. |
|
||||
| `RUSTFS_CUOBJECT_ASYNC_TRANSFERS` | `true` | Complete transfers through the library's asynchronous mode: the write is submitted with a handle and the task waits on the channel's completion descriptor, so no blocking thread is held per transfer. `false` keeps one blocking library call per transfer. |
|
||||
@@ -43,7 +45,9 @@ state=skipped` and serves plain HTTP.
|
||||
|
||||
## Wire contract
|
||||
|
||||
Request: a normal SigV4-signed `GET` with `x-amz-content-sha256: UNSIGNED-PAYLOAD`, an optional `Range` header, and `x-amz-rdma-token: <addr>:<size>:<rkey>:<lid>:<dctn>:<gidpresent>[:<gid>][:<gidpresent2>[:<gid2>]]` (colon-separated hex fields without `0x` prefixes, positive `size`, and a 32-hex-digit GID whenever `gidpresent` is `1`).
|
||||
Request: a normal SigV4-signed `GET` with `x-amz-content-sha256:
|
||||
UNSIGNED-PAYLOAD`, a `Range` header covering the client buffer, and
|
||||
`x-amz-rdma-token: <addr>:<size>:<rkey>:<lid>:<dctn>:<gidpresent>:<gid>`.
|
||||
|
||||
Response: the usual `GetObject` headers (ETag included) with an empty body
|
||||
and `Content-Length: 0`, plus:
|
||||
@@ -87,29 +91,14 @@ keeps its retained bytes independently of the staging pool.
|
||||
|
||||
## Validation
|
||||
|
||||
1. Set `RUSTFS_CUOBJECT_ENABLE=true` and `RUSTFS_CUOBJECT_ADDRS=<roce ip>` on each node and confirm `cuobject_service_state state=started` in the log.
|
||||
2. On the client, write a GDS `cufile.json` naming the client's RDMA IP(s) and GPUDirect peer mode, then export `CUFILE_ENV_PATH_JSON` (and `CUOBJ_ENV_PATH_JSON` for direct `libcuobjclient` consumers such as `rc --rdma-backend cuobject`):
|
||||
|
||||
```json
|
||||
{
|
||||
"execution": {
|
||||
"parallel_io": false
|
||||
},
|
||||
"properties": {
|
||||
"allow_compat_mode": true,
|
||||
"use_pci_p2pdma": true,
|
||||
"rdma_peer_type": "dmabuf",
|
||||
"rdma_dev_addr_list": ["10.0.1.20"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
export CUFILE_ENV_PATH_JSON=/etc/cufile.json
|
||||
export CUOBJ_ENV_PATH_JSON=/etc/cufile.json
|
||||
```
|
||||
|
||||
3. Run the SGLang loader with `--load-format rdma` and `"accelerated": true` in `--model-loader-extra-config` (or `rc --data-transport rdma --rdma-backend cuobject` from `rustfs/cli`); the NIXL `OBJ` backend then advertises `VRAM_SEG` and every tensor arrives in GPU memory without an HTTP body.
|
||||
1. `RUSTFS_CUOBJECT_ENABLE=true RUSTFS_CUOBJECT_ADDRS=<roce ip>` on each node
|
||||
and confirm `cuobject_service_state state=started` in the log.
|
||||
2. On the client, point `CUFILE_ENV_PATH_JSON` at a `cufile.json` whose
|
||||
`rdma_dev_addr_list` names the client's RDMA IP.
|
||||
3. Run the SGLang loader with `--load-format rdma` and
|
||||
`"accelerated": true` in `--model-loader-extra-config`; the NIXL `OBJ`
|
||||
backend then advertises `VRAM_SEG` and every tensor arrives in GPU memory
|
||||
without an HTTP body.
|
||||
|
||||
The generic `x-amz-rdma-token` client lives in NIXL 1.6.0 (git `2ff2509f`,
|
||||
2026-11-02) or newer. The published `nixl-cu13` 1.5.2 wheel ships only the
|
||||
|
||||
@@ -22,7 +22,11 @@ sum(shard grant amounts) <= quota_limit
|
||||
shard.accounted_usage <= sum(shard grant amounts)
|
||||
```
|
||||
|
||||
`accounted_usage` includes committed bytes and pending positive reservation growth. An abort removes pending growth. A commit removes the pending record because its growth is already accounted. Before releasing a commit-started orphan's precharged bytes, recovery revokes and drains the orphan's object publication and then reconciles the shard against its objects.
|
||||
`accounted_usage` includes committed bytes and pending positive reservation
|
||||
growth. An abort removes the pending growth; a commit removes only the pending
|
||||
record because its growth is already accounted. A reservation whose commit
|
||||
marker was persisted is removed only as a precharged reconcile candidate; the
|
||||
shard is then rebuilt from objects belonging to that shard.
|
||||
|
||||
## Locking and fencing
|
||||
|
||||
@@ -33,7 +37,13 @@ caller object/upload -> metadata transaction -> operation lock -> allocator
|
||||
read lock -> shard write lock
|
||||
```
|
||||
|
||||
Credit refill keeps the operation lock, releases the shared allocator and shard locks, then acquires the exclusive allocator lock before reloading the requester shard. The refill may lock donor shards while it holds the exclusive allocator lock. Allocator and shard mutations are fenced before persistence. Allocator and shard paths include the bucket incarnation and quota revision, so a quota change starts a new epoch after an exact bucket bootstrap instead of reusing old grants.
|
||||
Credit refill releases the operation and shard locks before taking the
|
||||
allocator write lock. The allocator write is fenced before persistence. Shard
|
||||
reservation and settlement fence the shard before persistence. The allocator
|
||||
generation and bucket incarnation/revision are checked on every load, so a
|
||||
late writer from an older epoch fails closed. Allocator and shard paths include
|
||||
the bucket incarnation and quota revision, so a quota change starts a new epoch
|
||||
after an exact bucket bootstrap instead of reusing old grants.
|
||||
|
||||
## Crash and replay behavior
|
||||
|
||||
@@ -46,8 +56,6 @@ releasing credit for an object that may already be durable.
|
||||
Repeated commit/abort operations are keyed by the operation ID and expected
|
||||
reservation fields; mismatches fail closed.
|
||||
|
||||
When reclaiming a whole grant, the allocator first clears any bootstrap usage metadata for the affected durable donor shards. The donor records are then saved with less credit and enough remaining credit to cover their full accounted usage. The allocator publishes the returned and newly assigned credit together. Before that publication, restarting readers can re-adopt the donor's old grants. After publication, they adopt only the retained grants. The initial allocator record can describe a populated shard before that shard is materialized. An empty requester receives regular credit only after its shard record is durable. A denied refill leaves the requester unmaterialized if it did not already exist.
|
||||
|
||||
## Mixed-version rollout
|
||||
|
||||
`reservation_protocol: 2` is serialized with `reservation_quota`. A node that
|
||||
@@ -99,9 +107,15 @@ encoding that makes pre-reservation coordinators reject positive growth.
|
||||
|
||||
## Performance boundary
|
||||
|
||||
Normal v2 admission acquires the shared allocator lock and reads the allocator once, then acquires the shard write lock. The same allocator snapshot remains protected until the reservation is saved. When orphan recovery frees enough local credit, the recovered and new reservations are saved together under the shared allocator lock. When a write exhausts its shard credit, the exclusive allocator lock protects the recheck, refill and reservation. If the remaining unissued credit is insufficient, the allocator can reuse whole grants from other shards, scanning at most the quota's 16 shard ledgers. Donor selection uses up to four concurrent read-only shard checks and performs no object listing. A prospective donor is fenced and reread only once a set of candidates can cover the shortfall. An insufficient candidate set leaves donor records untouched. A donor-backed refill issues the exact shortfall and returns excess credit to the common pool. An empty requester at the bootstrap generation also receives only its requested growth. Ordinary refills from unissued credit aim for roughly one sixteenth of the quota, or the shortfall when larger, within the available budget.
|
||||
|
||||
A shard can still hold idle credit inside a partly used grant. The allocator selects whole grants greedily, so it may also miss a combination of smaller grants. When the allocator cannot refill the write, the quota error reports total accounted usage across the shard ledgers, including pending growth. Deletes can leave accounted usage above the live object bytes.
|
||||
Normal v2 requests take a shared allocator read lock and one shard write lock;
|
||||
the bucket-wide allocator write lock is used only to issue a new credit chunk.
|
||||
The per-grant chunk is bounded by roughly one sixteenth of the quota (or the
|
||||
requested growth when larger), so one active shard cannot consume the entire
|
||||
remaining quota through a single speculative grant. It is a conservative upper
|
||||
bound, not a best-effort token bucket.
|
||||
Unused credit is intentionally retained until the quota epoch changes or a
|
||||
future reconciliation operation returns it, trading some capacity utilization
|
||||
for a simple crash-safe upper bound.
|
||||
|
||||
## Quotas saved before the reservation protocols
|
||||
|
||||
|
||||
@@ -81,27 +81,6 @@ Ansible-shaped hook (replace `/path/to/ansible` and the inventory group; the `co
|
||||
|
||||
For the quick A/B rig use the `HOTPATH_AB_*` names.
|
||||
|
||||
### Managed cluster acceptance
|
||||
|
||||
For a dedicated Linux test cluster, add the following flags to the ABBA command with an existing deploy hook and a fresh output directory.
|
||||
|
||||
```bash
|
||||
--cluster-lock-file /path/to/lab/cluster.lock \
|
||||
--restore-hook ./restore-test-cluster.sh \
|
||||
--hook-timeout-secs 180 \
|
||||
--node-ssh-target node-a=bench-node-a \
|
||||
--node-queue-devices node-a=nvme1n1+nvme2n1 \
|
||||
--node-queue-timeout-secs 60 \
|
||||
--workload 'put-32kib|put|32KiB' \
|
||||
--drive-sync 'sync-on|true'
|
||||
```
|
||||
|
||||
Repeat the SSH target and device mapping for every node. Specify the Linux kernel device names of the benchmark volumes. With the queue check enabled, each PUT attempt waits for two consecutive rounds of parallel five-second sampling. Each node must have mean queue depth at most 0.25 and no listed device above 0.75. Queue depth uses the change in weighted I/O milliseconds divided by elapsed monotonic milliseconds. Each attempt records the collected samples in its cell's `node_telemetry/queue_*.tsv`. An unavailable node, invalid counter or timeout fails the attempt before Warp starts. The ABBA drift and regression budgets still apply. [Linux block device counters](https://docs.kernel.org/admin-guide/iostats.html)
|
||||
|
||||
Use the same persistent lock file for cooperating commands on the same controller. An occupied lock makes the runner exit before deployment. Keep the lock file in place so every command locks the same inode. The controller runs the restore hook once after any deployment attempt, including a failed deploy, interrupted workload or failed gate. The hook receives `HOTPATH_ABBA_DATASET_NAMESPACE` and `HOTPATH_ABBA_OUT_DIR`. It owns the site-specific cleanup and must reconcile partially completed remote deployment, restore services and verify readiness before returning. Use bounded, synchronous hooks on the controller. The runner stops the active controller process group before restoration, holds the lock through restoration and records `restore.log` and `restore.status`. Managed runs require `flock` and a `timeout` implementation supporting `--foreground` and `--kill-after`.
|
||||
|
||||
For diagnostic PUT runs using `--service-prometheus-query-url`, add `--require-rename-rank-metrics` after enabling PUT stage metrics and warming that deployment. The service snapshots must include `rustfs_s3_put_object_rename_disk_wait_completion_ms_count` for both `position="quorum_first"` and `position="quorum_tail"`. Each group must advance across the attempt without series resets or changes in membership. Use the existing query or service-name filter to scope snapshots to the benchmark service. These counters describe completion order. Per-request attribution also needs a join with the coordinator's ACK decision.
|
||||
|
||||
## Quick A/B (`run_hotpath_warp_ab.sh`)
|
||||
|
||||
```bash
|
||||
|
||||
@@ -19,15 +19,17 @@ also enabled.
|
||||
|
||||
## Build
|
||||
|
||||
- Enable the Linux `nixl` Cargo feature on the `rustfs` crate (`cargo build --release -p rustfs --features nixl`). Neither `nixl` nor `cuobject` is enabled in default builds; if both features are passed together, `nixl` takes precedence.
|
||||
- `rustfs-nixl` compiles against the workspace `nixl-sys` binding (NIXL `1.5.2` C++ API). Set `NIXL_PREFIX` to an installation prefix containing `include/` and `lib/` (`libnixl.so`, `libnixl_build.so`, `libnixl_common.so`, `libserdes.so`, `libstream.so`, and `lib/plugins/libplugin_UCX.so`, or the multiarch `lib/<triplet>/` layout on Debian/Ubuntu). `bindgen` requires `g++` (C++20) and `libclang` at build time.
|
||||
- Set `NIXL_NO_STUBS_FALLBACK=1` for production builds so missing NIXL headers or libraries fail compilation instead of falling back to `nixl-sys`'s `dlopen` stub.
|
||||
- At run time, include the NIXL library directory on `LD_LIBRARY_PATH`, point `NIXL_PLUGIN_DIR` at the `plugins` directory containing `libplugin_UCX.so`, and raise the locked-memory limit (`ulimit -l unlimited` or systemd `LimitMEMLOCK=infinity`) so UCX can pin `RUSTFS_NIXL_POOL_BYTES` and `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES`.
|
||||
|
||||
```bash
|
||||
NIXL_PREFIX=/opt/nvidia/nvda_nixl NIXL_NO_STUBS_FALLBACK=1 \
|
||||
cargo build --release -p rustfs --features nixl
|
||||
```
|
||||
- Cargo feature `nixl` on the `rustfs` crate (`--features rdma,nixl`); the
|
||||
`rustfs-nixl` crate depends on the `nixl-sys` binding from the NIXL
|
||||
repository at tag `v1.5.2`.
|
||||
- `NIXL_PREFIX` points at a prefix with `include/` (the NIXL C++ headers of
|
||||
that tag) and `lib/` holding `libnixl.so`, `libnixl_build.so`,
|
||||
`libnixl_common.so`, `libserdes.so`, `libstream.so` and
|
||||
`lib/plugins/libplugin_UCX.so`. The `nixl-cu13` wheel ships the libraries
|
||||
(under `site-packages/.nixl_cu13.mesonpy.libs/`); the headers come from the
|
||||
repository. `bindgen` needs `libclang` at build time.
|
||||
- At run time the server needs `LD_LIBRARY_PATH` on that `lib/` and
|
||||
`NIXL_PLUGIN_DIR` on `lib/plugins`.
|
||||
|
||||
## Settings
|
||||
|
||||
@@ -35,7 +37,7 @@ NIXL_PREFIX=/opt/nvidia/nvda_nixl NIXL_NO_STUBS_FALLBACK=1 \
|
||||
|---|---|---|
|
||||
| `RUSTFS_NIXL_ENABLE` | `false` | Serve requests that carry the NIXL headers over NIXL. |
|
||||
| `RUSTFS_NIXL_AGENT_NAME` | `rustfs-<first local endpoint host>` | This node's agent name; must be unique in the cluster. |
|
||||
| `RUSTFS_NIXL_UCX_DEVICES` | all devices | Comma-separated UCX device names (`mlx5_9,mlx5_10`; NIXL adds the port); pin the agent to the rails that reach the clients. With `UCX_MAX_RMA_RAILS=2` in the server's environment, UCX stripes every write across two of these ports and the client must have registered its buffer on both of them, or the native transfer fails (`InternalError`). |
|
||||
| `RUSTFS_NIXL_UCX_DEVICES` | all devices | Comma-separated UCX device names (`mlx5_9,mlx5_10`; NIXL adds the port); pin the agent to the rails that reach the clients. With `UCX_MAX_RMA_RAILS=2` in the server's environment, UCX stripes every write across two of these ports and the client must have registered its buffer on both of them, or the transfer fails and the GET is declined. |
|
||||
| `RUSTFS_NIXL_NUM_WORKERS` | `1` | UCX progress workers of the agent. |
|
||||
| `RUSTFS_NIXL_CHUNK_BYTES` | `16 MiB` | Staging chunk, one transfer descriptor at most. |
|
||||
| `RUSTFS_NIXL_POOL_BYTES` | `1 GiB` | Registered staging memory. |
|
||||
@@ -44,21 +46,14 @@ NIXL_PREFIX=/opt/nvidia/nvda_nixl NIXL_NO_STUBS_FALLBACK=1 \
|
||||
| `RUSTFS_NIXL_DEVICE_CHECK` | `true` | Check the devices at startup and leave out unhealthy ones (see below). |
|
||||
| `RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS` | `16` | Leave out a device whose link dropped this many times more since boot than the quietest device of its link layer; `0` skips this test. |
|
||||
| `RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS` | `3000` | How long the startup check watches the link counters; `0` skips the watch. |
|
||||
| `RUSTFS_INTERNODE_DATA_TRANSPORT` | `tcp-http` | `nixl` moves internode shard reads and writes over NIXL (requires the node's NIXL agent; see below). |
|
||||
| `RUSTFS_INTERNODE_DATA_TRANSPORT` | `tcp-http` | `nixl` moves internode shard reads over NIXL too (see below). |
|
||||
| `RUSTFS_NIXL_INTERNODE_DEPTH` | `4` | Internode chunk requests in flight per remote shard stream. |
|
||||
| `RUSTFS_CUOBJECT_PUT_READ_AHEAD` | `4` | Staging chunks read from the client's buffer ahead of the PUT body's consumer; each holds one chunk of the pool. |
|
||||
|
||||
### Shared pipeline settings
|
||||
|
||||
These variables govern the S3-over-RDMA object pipeline for both `nixl` and `cuobject`:
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `RUSTFS_CUOBJECT_INFLIGHT_WRITES` | `3` | Staging chunks kept in flight per GET so decoding overlaps RDMA writes. |
|
||||
| `RUSTFS_CUOBJECT_PUT_READ_AHEAD` | `4` | Staging chunks read from the client's buffer ahead of the PUT or UploadPart consumer; each holds one chunk of the pool. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT` | `8` | Concurrent erasure-block-aligned segments one plain GET can split into on the server (`1` disables fan-out). Compressed and encrypted objects bypass the segmented sink and stream sequentially over RDMA. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES` | `192 MiB` | Smallest segment size (in bytes, rounded up to whole erasure blocks) eligible for its own segment producer. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT_BUDGET` | `16` | Total extra segment producers shared fairly across concurrent RDMA GETs on the node (`budget / active_gets`, clamped to `1..=fanout`). |
|
||||
| `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES` | `0` | Registered host memory (in bytes, `0` disables; otherwise at least `RUSTFS_ERASURE_SHARD_BYTES`, default `4 MiB`) that the erasure decoder reads shards into so plain data shards are RDMA-written in place without a staging copy. |
|
||||
The pipeline settings `RUSTFS_CUOBJECT_GET_FANOUT`,
|
||||
`RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES`, `RUSTFS_CUOBJECT_GET_FANOUT_BUDGET`,
|
||||
`RUSTFS_CUOBJECT_INFLIGHT_WRITES` and `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES`
|
||||
apply unchanged.
|
||||
|
||||
### Large-object PUT tuning
|
||||
|
||||
@@ -68,7 +63,7 @@ Several settings outside the NIXL variables decide PUT throughput on large hosts
|
||||
- `MIMALLOC_ALLOW_THP=0`: with transparent huge pages in `madvise` mode, the allocator's huge-page requests for the per-stripe buffers send the kernel into direct compaction, which took about a third of the CPU during PUTs.
|
||||
- `MIMALLOC_PURGE_DELAY=-1`: the allocator keeps freed memory for reuse instead of returning it to the kernel. Every PUT allocates and frees tens of megabytes of stripe and staging buffers, and returning them made the kernel fault in and zero fresh pages, shoot down TLBs and compact memory under its zone lock. Keeping them raised a 4-client PUT of 57 MB objects from about 14 to about 18 GB/s on two servers. The process's resident memory then stays at its peak.
|
||||
- `RUSTFS_OBJECT_DATA_CACHE_FILL_ON_PUT=false` for write-heavy buckets such as an LLM KV cache: fill-on-put copies every PUT body that fits the cache entry limit into the object data cache, which cost about 30-40 ms per 57 MB object. Without it, an RDMA PutObject body also stays in the staging chunks it was read into (no copy).
|
||||
- `RUSTFS_OBJECT_ETAG_MD5_OFFLOAD_MIN_BYTES` (default `0`, disabled; set `8388608` for an 8 MiB threshold): when non-zero, bodies at least this large compute their ETag MD5 on a blocking-pool thread while the body streams into the erasure encoder, instead of inline on the request worker. Each offloaded upload holds one blocking-pool thread until its body finishes, so size the threshold against concurrent upload admission. The ETag and Content-MD5 check are unchanged; the PUT fails before commit on a mismatch.
|
||||
- `RUSTFS_OBJECT_ETAG_MD5_OFFLOAD_MIN_BYTES` (default 8 MiB, `0` turns it off): bodies at least this large compute their ETag MD5 on a blocking-pool thread while the body streams into the erasure encoder, instead of inline before it. The ETag and the Content-MD5 check are unchanged; the PUT fails before commit on a mismatch.
|
||||
- `RUSTFS_OBJECT_DIRECT_IO_WRITE_ENABLE=true`: shard files are written with O_DIRECT instead of through the page cache, which otherwise costs a copy into freshly allocated, zeroed cache pages, zone-lock contention and compaction on every write. With four PUT clients on two servers (57 MB objects) it more than doubled the aggregate (7 to 16-21 GB/s) while reads of the just-written objects, now served by the drives, stayed within about 10%. The NIXL internode shard writes finish every file with a writer shutdown, which the direct writer needs to write its trailing sub-alignment bytes.
|
||||
- A per-bucket XXH3 ETag for buckets whose clients never treat the ETag as an MD5, such as an LLM KV cache: objects written to the bucket without Content-MD5 get an XXH3-128 ETag in the same 32-hex-digit form, an order of magnitude cheaper to compute. It halved the single-stream PUT of 57 MB objects (105 to 55 ms) but did not raise the saturated aggregate. Other buckets keep MD5 ETags, so ordinary S3 clients (rclone checksums, SDKs that verify an upload against the returned ETag) are unaffected. See "Per-bucket ETag algorithm" below.
|
||||
|
||||
@@ -102,14 +97,13 @@ Request headers (GET, PUT, UploadPart):
|
||||
|---|---|
|
||||
| `x-rustfs-nixl-agent` | The client's agent name (printable ASCII, up to 128 bytes). |
|
||||
| `x-rustfs-nixl-metadata` | The client's agent metadata (`get_local_md`), base64. Send on each request for reliable reuse across nodes and cache eviction. The server can accept an omitted value while the registration is cached. In-flight requests pin the registration, including timed-out transfers until native completion. The five-minute idle period starts when the last native request finishes. The server checks once a minute and may reclaim idle registrations sooner under cache pressure. |
|
||||
| `x-rustfs-nixl-buffer` | `<dram|vram>:<device>:<address>:<length>` (case-insensitive; `host` and `gpu` are accepted aliases): the registered buffer the object (or requested range) lands in from offset 0, or is read from for a PUT or UploadPart. Address and positive length are decimal or `0x` hex. |
|
||||
| `x-rustfs-nixl-buffer` | `<dram|vram>:<device>:<address>:<length>`: the registered buffer the object (or the requested range) lands in from offset 0, or is read from for a PUT. Address and length are decimal or `0x` hex. |
|
||||
|
||||
Reply headers on a completed RDMA transfer: `x-amz-rdma-reply` (`200` for a full object or upload, `206` for a ranged GET) and `x-amz-rdma-bytes-transferred` (omitted on a 0-byte GET). The HTTP response body is empty (`Content-Length: 0`) and is sent only after the last native transfer completed, so the client may read or reuse its buffer as soon as the response arrives. The server never needs the client to load the server's metadata.
|
||||
|
||||
Zero-length and fallback rules:
|
||||
- Zero-length buffer descriptors (`length = 0`) are rejected as malformed. To issue an RDMA GET of a 0-byte object, advertise at least a 1-byte registered window; the response carries `x-amz-rdma-reply` with `Content-Length: 0` and omits `x-amz-rdma-bytes-transferred`. Upload 0-byte objects with a normal HTTP PUT without RDMA headers.
|
||||
- When the service is disabled or a request carries malformed RDMA headers, `x-amz-rdma-reply` is omitted: a GET falls back to streaming the normal HTTP body, while an empty-body `PutObject` or `UploadPart` is processed as an ordinary 0-byte HTTP write. Clients that probe unknown endpoints or must avoid overwriting an existing key with 0 bytes on a declined request should stage writes through multipart `UploadPart` and call `CompleteMultipartUpload` only after verifying `x-amz-rdma-reply: 200` and `x-amz-rdma-bytes-transferred` on every part (the strategy used by `rc --data-transport auto|rdma`).
|
||||
- A GET whose resolved object or range length exceeds the advertised buffer length fails with `InvalidRange` (HTTP 416); native transfer failures surface as `InternalError` (HTTP 500).
|
||||
Reply headers: `x-amz-rdma-reply` (`200`, `206` for a range, `501` when the
|
||||
transfer could not run), `x-amz-rdma-bytes-transferred`. The HTTP body is
|
||||
empty; the reply is sent after the last transfer completed, so the client may
|
||||
read its buffer as soon as the response arrives. The server never needs the
|
||||
client to load the server's metadata.
|
||||
|
||||
## Device health check
|
||||
|
||||
@@ -209,8 +203,9 @@ across them; GPU clients register only their GPU's rail.
|
||||
reports its transfer complete, and the target verifies every word against
|
||||
its offset.
|
||||
|
||||
## Validation and observability
|
||||
## Validation
|
||||
|
||||
- Check a transport change with a client that fetches an object into a zero-filled GPU (`vram`) or host (`dram`) buffer through this contract and compares it byte-for-byte with a plain HTTP GET of the same object. Verify with a single round: repeated rounds into the same buffer can mask a transfer that completed early. For GPU buffers, GPUDirect RDMA works over kernel `dma-buf` with the open NVIDIA kernel modules (or `nvidia_peermem` on proprietary drivers) without requiring GPUs on the RustFS storage nodes.
|
||||
- From the companion `rustfs/cli` repository (`./scripts/build-rdma.sh --release`), validate end-to-end uploads, downloads, and `auto` fallback with `rc --data-transport rdma --rdma-backend nixl cp <src> <alias>/<bucket>/<key>` (or set `UCX_TLS=tcp,self` with `RUSTFS_NIXL_DEVICE_CHECK=false` for software loopback checks without RDMA hardware).
|
||||
- Structured log events report lifecycle and refusals under `cuobject_service_state` (`started`, `skipped`, `device_check`), `cuobject_get_rejected` (`token_malformed`), and `nixl_internode_read` (`refused`). Stage summaries record `s3_handler/rdma_transfer`, `cuobject_emit/write_zero_copy`, `cuobject_emit/write_staging`, `cuobject_emit/write_bytes`, `rdma_put_body_wait`, and `nixl_write_file_*`.
|
||||
Check a transport change with a client that fetches an object into a
|
||||
zero-filled GPU or host buffer through this contract and compares it with a
|
||||
plain HTTP GET of the same object. Verify with a single round: later rounds
|
||||
rewrite the same bytes and mask a transfer that completed early.
|
||||
|
||||
@@ -77,7 +77,7 @@
|
||||
|
||||
rustfs = rustPlatform.buildRustPackage {
|
||||
pname = "rustfs";
|
||||
version = "1.0.8";
|
||||
version = "1.0.5";
|
||||
|
||||
src = ./.;
|
||||
|
||||
@@ -92,16 +92,9 @@
|
||||
];
|
||||
|
||||
buildInputs = with pkgs; [
|
||||
aws-lc
|
||||
openssl
|
||||
zstd
|
||||
];
|
||||
|
||||
# Gateway crates include files from their workspace's shared generated directory.
|
||||
prePatch = ''
|
||||
ln -s "$cargoDepsCopy"/rustfs-gateway-core-*/generated "$cargoDepsCopy/../generated"
|
||||
'';
|
||||
|
||||
cargoBuildFlags = [
|
||||
"--package"
|
||||
"rustfs"
|
||||
|
||||
Generated
+57
-54
@@ -1968,14 +1968,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "5.1.0"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94c1aa5a9b7626ed65ac0cf5ea9d4f1547af89017fbac20bd4de40022fff516f"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"cpufeatures 0.2.17",
|
||||
"curve25519-dalek-derive",
|
||||
"digest 0.11.3",
|
||||
"digest 0.10.7",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
@@ -2999,23 +2999,23 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "3.0.0"
|
||||
version = "2.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
|
||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
||||
dependencies = [
|
||||
"signature 3.0.0",
|
||||
"signature 2.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "3.0.0"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
|
||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"sha2 0.11.2",
|
||||
"signature 3.0.0",
|
||||
"sha2 0.10.9",
|
||||
"signature 2.2.0",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
@@ -3151,9 +3151,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.3.0"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
@@ -3641,18 +3641,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "hotpath"
|
||||
version = "0.33.1"
|
||||
version = "0.32.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e68c67280a589200540a7da751fc2dff99501655ff59623c0fba299a68abcd8b"
|
||||
checksum = "c512d9810e0836ad7aae1ecc363a727a20e7d56e1d497433150a354f6ddaccee"
|
||||
dependencies = [
|
||||
"hotpath-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hotpath-macros"
|
||||
version = "0.33.1"
|
||||
version = "0.32.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4db3c637c6c3cf7120ab641f12f83aa19dfa015679ac1b29e16b15684c7a3e3"
|
||||
checksum = "b1afbcca1689d57e341a886622a751f0893add180871306b99e8061fbe4361be"
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
@@ -4763,6 +4763,8 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "nkeys"
|
||||
version = "0.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879011babc47a1c7fdf5a935ae3cfe94f34645ca0cac1c7f6424b36fc743d1bf"
|
||||
dependencies = [
|
||||
"data-encoding",
|
||||
"ed25519",
|
||||
@@ -6245,7 +6247,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-checksums"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -6259,7 +6261,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-common"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"metrics",
|
||||
@@ -6273,7 +6275,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-concurrency"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"rustfs-io-core",
|
||||
"serde",
|
||||
@@ -6283,7 +6285,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-config"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"const-str",
|
||||
"serde",
|
||||
@@ -6292,7 +6294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-credentials"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"hmac 0.13.0",
|
||||
@@ -6305,7 +6307,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-crypto"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"argon2",
|
||||
@@ -6323,7 +6325,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-data-usage"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"hotpath",
|
||||
"rmp-serde",
|
||||
@@ -6333,7 +6335,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-ecstore"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-channel",
|
||||
@@ -6453,7 +6455,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-extension-schema"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror",
|
||||
@@ -6461,7 +6463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-filemeta"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"base64-simd",
|
||||
@@ -6559,7 +6561,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-heal-contracts"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"tokio",
|
||||
@@ -6568,7 +6570,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-io-core"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"rustfs-io-metrics",
|
||||
@@ -6579,7 +6581,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-io-metrics"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"metrics",
|
||||
"num_cpus",
|
||||
@@ -6640,7 +6642,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-kms"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"arc-swap",
|
||||
@@ -6678,7 +6680,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-lifecycle"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"hotpath",
|
||||
@@ -6695,7 +6697,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-lock"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"compact_str",
|
||||
@@ -6719,7 +6721,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-madmin"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"http",
|
||||
"humantime",
|
||||
@@ -6735,7 +6737,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-notify"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -6766,7 +6768,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-object-capacity"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"hotpath",
|
||||
@@ -6782,14 +6784,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-object-data-cache"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"sysinfo",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-policy"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64-simd",
|
||||
@@ -6814,7 +6816,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-protos"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"flatbuffers",
|
||||
"hyper-util",
|
||||
@@ -6837,7 +6839,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-replication"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"bytes",
|
||||
@@ -6854,7 +6856,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-rio"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"arc-swap",
|
||||
@@ -6888,7 +6890,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-client"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -6933,14 +6935,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-ops"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"rustfs-s3-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-types"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
@@ -6954,7 +6956,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3select-api"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-compression",
|
||||
@@ -6995,7 +6997,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3select-query"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
@@ -7014,7 +7016,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-scanner-metrics"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"jiff 1.0.3",
|
||||
"metrics",
|
||||
@@ -7026,14 +7028,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-security-governance"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-signer"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -7049,7 +7051,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-sse"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
@@ -7069,7 +7071,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-storage-api"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"hotpath",
|
||||
@@ -7081,7 +7083,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-targets"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-nats",
|
||||
@@ -7130,7 +7132,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-tls-runtime"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"metrics",
|
||||
@@ -7159,7 +7161,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-utils"
|
||||
version = "1.0.8"
|
||||
version = "1.0.5"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"blake2",
|
||||
@@ -7616,6 +7618,7 @@ version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"digest 0.10.7",
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
|
||||
@@ -42,7 +42,6 @@ uuid = { version = "1.29.3", features = ["v4", "serde"] }
|
||||
|
||||
[patch.crates-io]
|
||||
hyper = { path = "../vendor/hyper" }
|
||||
nkeys = { path = "../vendor/nkeys" }
|
||||
|
||||
[profile.dev]
|
||||
debug = "line-tables-only"
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user