Compare commits

..

1 Commits

Author SHA1 Message Date
Kevin e8ac67b867 fix(storage): resolve 3x2, multi-pool, and replication bugs (#3393) 2026-12-02 04:50:18 +08:00
92 changed files with 3341 additions and 3816 deletions
+3 -3
View File
@@ -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"
-78
View File
@@ -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'
-2
View File
@@ -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
Generated
+68 -67
View File
@@ -1264,9 +1264,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.163.0"
version = "1.162.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c"
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -1293,7 +1293,7 @@ dependencies = [
"lru 0.18.5",
"percent-encoding",
"regex-lite",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
"url",
]
@@ -1417,7 +1417,7 @@ dependencies = [
"http 1.5.0",
"p256",
"percent-encoding",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"time",
"tracing",
@@ -1452,7 +1452,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"tracing",
]
@@ -1801,7 +1801,7 @@ checksum = "144e573728da132683b9488acd528274c790e07fc06ff81ee29f9d8f8b1041e0"
dependencies = [
"blowfish",
"pbkdf2 0.13.0",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -2112,9 +2112,9 @@ dependencies = [
[[package]]
name = "brotli-decompressor"
version = "6.4.1"
version = "6.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50986a054f56ca3e15382f3c09abee2bf494c00311b238daae118a06bc1c15f1"
checksum = "664148598c930650998ef56df301329ffe7b4cdb02d49b2a3fca3bcaf2185bcb"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -3961,7 +3961,7 @@ dependencies = [
"num-traits",
"rand 0.9.5",
"regex",
"sha2 0.11.3",
"sha2 0.11.2",
"uuid",
]
@@ -5148,7 +5148,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"suppaftp",
"tempfile",
"time",
@@ -5200,7 +5200,7 @@ dependencies = [
"ed25519",
"rand_core 0.10.1",
"serde",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"subtle",
"zeroize",
@@ -5695,12 +5695,14 @@ dependencies = [
[[package]]
name = "generator"
version = "0.8.13"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66831419d9074e766421508dff218bf79d99616bc5e56e34599d3b433714a4a4"
checksum = "ea6c6a73cd1aa4f4f00c02b109fa55d3a9d6ecc2fc4f53177b74ed6ee23b0c53"
dependencies = [
"cc",
"libc",
"log",
"rustversion",
"windows-core 0.100.0",
"windows-sys 0.61.2",
]
@@ -5849,7 +5851,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror 2.0.21",
"time",
"tokio",
@@ -6012,7 +6014,7 @@ dependencies = [
"serde",
"serde_json",
"serde_with",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror 2.0.21",
"tokio",
"tokio-stream",
@@ -6842,9 +6844,9 @@ checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
[[package]]
name = "io-uring"
version = "0.7.17"
version = "0.7.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123"
checksum = "878c26bc5e45fe089ce2ca25689260c152a87ce1d7de2ca86101efeea6973932"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@@ -8106,7 +8108,7 @@ version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef1d73c59a56771343712b22ea5615092c612c16ba291c0979e3105dfeec4890"
dependencies = [
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -9460,7 +9462,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -9474,7 +9476,7 @@ dependencies = [
"fiat-crypto",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -9488,7 +9490,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -9514,7 +9516,7 @@ dependencies = [
"futures",
"log",
"rand 0.10.4",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror 2.0.21",
"tokio",
"windows",
@@ -9956,7 +9958,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand_core 0.10.1",
"scrypt 0.12.0",
"sha2 0.11.3",
"sha2 0.11.2",
"spki 0.8.1",
]
@@ -10074,7 +10076,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.3",
"sha2 0.11.2",
"stringprep",
]
@@ -11288,7 +11290,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -11402,7 +11404,7 @@ dependencies = [
"scrypt 0.12.0",
"sec1",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"sha3",
"signature 3.0.0",
"spki 0.8.1",
@@ -11492,7 +11494,7 @@ version = "8.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b"
dependencies = [
"sha2 0.11.3",
"sha2 0.11.2",
"walkdir",
]
@@ -11669,7 +11671,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"serial_test",
"sha2 0.11.3",
"sha2 0.11.2",
"shadow-rs",
"snap",
"socket2",
@@ -11733,7 +11735,7 @@ dependencies = [
"md-5",
"pretty_assertions",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"xxhash-rust",
]
@@ -11780,7 +11782,7 @@ dependencies = [
"object 0.41.0",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"symbolic-demangle",
]
@@ -11793,7 +11795,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
]
@@ -11811,7 +11813,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"test-case",
"thiserror 2.0.21",
"time",
@@ -11972,7 +11974,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.3",
"sha2 0.11.2",
"shadow-rs",
"slab",
"smallvec",
@@ -12041,7 +12043,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tempfile",
"thiserror 2.0.21",
"time",
@@ -12074,7 +12076,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-types",
"rustfs-gateway-xml",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tower",
"tracing",
@@ -12126,7 +12128,7 @@ source = "git+https://github.com/rustfs/gateway.git?rev=ac50e9af28fd1cbb2a643e3f
dependencies = [
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -12171,7 +12173,7 @@ dependencies = [
"phf 0.14.0",
"rustfs-gateway-stream",
"rustfs-gateway-types",
"sha2 0.11.3",
"sha2 0.11.2",
"smallvec",
"subtle",
"zeroize",
@@ -12197,7 +12199,7 @@ dependencies = [
"p256",
"rustfs-gateway-http",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"smallvec",
"subtle",
"zeroize",
@@ -12229,7 +12231,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"time",
"twox-hash",
"unicode-normalization",
@@ -12273,7 +12275,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.3",
"sha2 0.11.2",
"temp-env",
"tempfile",
"thiserror 2.0.21",
@@ -12332,7 +12334,7 @@ dependencies = [
"serde_with",
"serial_test",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"temp-env",
"tempfile",
@@ -12388,7 +12390,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"socket2",
"thiserror 2.0.21",
"tracing",
@@ -12412,7 +12414,7 @@ dependencies = [
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-rustls",
"tracing",
@@ -12481,7 +12483,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"subtle",
"temp-env",
"tempfile",
@@ -12558,7 +12560,7 @@ dependencies = [
"regex",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tar",
"tempfile",
"thiserror 2.0.21",
@@ -12839,7 +12841,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"socket2",
"subtle",
"sync_wrapper",
@@ -12939,7 +12941,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"temp-env",
"thiserror 2.0.21",
"tokio",
@@ -12967,7 +12969,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"walkdir",
]
@@ -13005,7 +13007,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"thiserror 2.0.21",
"time",
"tokio",
@@ -13148,7 +13150,7 @@ dependencies = [
"serde",
"serde_json",
"serial_test",
"sha2 0.11.3",
"sha2 0.11.2",
"temp-env",
"tempfile",
"thiserror 2.0.21",
@@ -13222,7 +13224,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"temp-env",
"tempfile",
"tokio",
@@ -13281,7 +13283,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"snap",
"sysinfo",
"tempfile",
@@ -13326,7 +13328,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tempfile",
"thiserror 2.0.21",
"tokio",
@@ -13379,9 +13381,8 @@ dependencies = [
[[package]]
name = "rustfs-uring"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba"
version = "0.3.0"
source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf"
dependencies = [
"io-uring",
"libc",
@@ -13419,7 +13420,7 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"siphasher",
"snap",
"temp-env",
@@ -13443,7 +13444,7 @@ dependencies = [
"rustfs-tokio-tar",
"serde",
"serde_json",
"sha2 0.11.3",
"sha2 0.11.2",
"tar-codec",
"tar-framing",
"thiserror 2.0.21",
@@ -13680,7 +13681,7 @@ dependencies = [
"serde_json",
"serde_urlencoded",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"smallvec",
"std-next",
"subtle",
@@ -13744,7 +13745,7 @@ dependencies = [
"jiff 0.2.46",
"nom 8.0.0",
"serde",
"sha2 0.11.3",
"sha2 0.11.2",
"smallvec",
"std-next",
"subtle",
@@ -13866,7 +13867,7 @@ dependencies = [
"cfg-if",
"pbkdf2 0.13.0",
"salsa20 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
]
[[package]]
@@ -14174,9 +14175,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.3"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -14606,7 +14607,7 @@ dependencies = [
"sec1",
"serde",
"sha1 0.11.0",
"sha2 0.11.3",
"sha2 0.11.2",
"signature 3.0.0",
"ssh-cipher",
"ssh-encoding",
@@ -14852,9 +14853,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.5"
version = "0.40.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
dependencies = [
"libc",
"memchr",
@@ -15243,7 +15244,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.3",
"sha2 0.11.2",
"tokio",
"tokio-postgres",
"tokio-rustls",
+3 -3
View File
@@ -261,7 +261,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,7 +289,7 @@ 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-smithy-async = { version = "1.3.1" }
@@ -381,7 +381,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"
-6
View File
@@ -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;
+2
View File
@@ -871,6 +871,8 @@ pub struct SizeSummary {
/// remove versions that resolved without allocating one key per healthy
/// version on the hot path.
pub reconciliation_scopes: Vec<SizeReconciliationScope>,
/// True when lifecycle evaluation queued deletion for every remaining version of the object.
pub all_versions_queued_for_delete: bool,
}
/// Replication target size summary
+2 -2
View File
@@ -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
+1 -1
View File
@@ -328,7 +328,7 @@ pub mod bucket {
assign_site_replication_rule_priorities, commit_force_delete_intent, complete_force_delete_intent,
delete_replication_state_from_config, delete_replication_version_id, get_global_replication_pool,
get_global_replication_stats, get_proxy_targets, init_background_replication,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule, legacy_role_target_arn,
merge_incoming_replication_config, merge_user_replication_config, persist_force_delete_intent,
read_durable_mrf_backlog, replication_state_to_filemeta, replication_status_to_filemeta, replication_statuses_map,
replication_target_arn_deployment_id, replication_target_arns, resync_start_conflict_id,
+22 -1
View File
@@ -939,7 +939,7 @@ impl BucketTargetSys {
found = true;
break;
}
if existing_target.endpoint == target.endpoint {
if existing_target.endpoint == target.endpoint && existing_target.target_bucket == target.target_bucket {
return Err(BucketTargetError::BucketRemoteAlreadyExists {
bucket: existing_target.target_bucket.clone(),
});
@@ -5591,4 +5591,25 @@ mod tests {
assert_eq!(base.targets.len(), 1);
assert_eq!(base.targets[0].arn, existing.arn);
}
#[test]
fn upsert_target_entry_allows_distinct_target_buckets_on_same_endpoint() {
let bucket = "bkt-bucket-repl";
let mut site_target = repair_target(bucket, "site-repl");
site_target.target_bucket = bucket.to_string();
let mut bucket_repl_target = repair_target(bucket, "bucket-repl");
bucket_repl_target.target_bucket = "bkt-bucket-repl-replica".to_string();
let mut targets = vec![site_target];
BucketTargetSys::upsert_target_entry(&mut targets, &bucket_repl_target, false)
.expect("distinct target bucket on same endpoint should succeed");
assert_eq!(targets.len(), 2);
let mut duplicate_bucket_target = repair_target(bucket, "dup-arn");
duplicate_bucket_target.target_bucket = "bkt-bucket-repl-replica".to_string();
let err = BucketTargetSys::upsert_target_entry(&mut targets, &duplicate_bucket_target, false)
.expect_err("duplicate endpoint + target_bucket should be rejected");
assert!(matches!(err, BucketTargetError::BucketRemoteAlreadyExists { .. }));
}
}
@@ -1378,6 +1378,11 @@ impl ExpiryState {
.await
};
if deleted {
runtime_sources::notify_scanner_dirty_usage_mutation(
&v.obj_info.bucket,
&v.obj_info.name,
runtime_sources::ScannerDirtyUsageMutationSource::TierExpiration,
);
trace.emit(EVENT_LIFECYCLE_DELETE_COMPLETED, "delete_completed", None);
} else {
record_scanner_lifecycle_expiry_delete_failed(&v.src, 1);
@@ -1401,6 +1406,15 @@ impl ExpiryState {
v.bucket_incarnation_id,
)
.await;
if v.versions.len() > failed {
for ver in &v.versions {
runtime_sources::notify_scanner_dirty_usage_mutation(
&v.bucket,
&ver.object_name,
runtime_sources::ScannerDirtyUsageMutationSource::TierExpiration,
);
}
}
if failed == 0 {
trace.emit(EVENT_LIFECYCLE_DELETE_COMPLETED, "delete_completed", None);
} else {
@@ -2247,6 +2261,11 @@ impl TransitionState {
ts.num_objects = 1;
}
transition_state.add_lastday_stats(&task.event.storage_class, ts);
runtime_sources::notify_scanner_dirty_usage_mutation(
&task.obj_info.bucket,
&task.obj_info.name,
runtime_sources::ScannerDirtyUsageMutationSource::TierExpiration,
);
emit_transition_complete_event(obj_info_for_event, incarnation_id);
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -48,7 +48,7 @@ pub use replication_config_boundary::{
REMOTE_TARGET_UNSUPPORTED_FIELDS, REMOTE_TARGET_WRITABLE_FIELDS, REPLICATION_CAPABILITY_CONTRACT_VERSION,
REPLICATION_READ_ONLY_HISTORICAL_FIELDS, REPLICATION_WRITABLE_FIELDS, ReplicationConfigStructureError,
ReplicationConfigurationExt, ReplicationTargetValidationError, assign_site_replication_rule_priorities,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule, legacy_role_target_arn,
merge_incoming_replication_config, merge_user_replication_config, replication_target_arn_deployment_id,
replication_target_arns, should_remove_replication_target, site_replication_rule_deployment_id,
unsupported_replication_config_field, validate_replication_config_structure, validate_replication_config_target_arns,
@@ -18,7 +18,7 @@ pub use rustfs_replication::{
REMOTE_TARGET_UNSUPPORTED_FIELDS, REMOTE_TARGET_WRITABLE_FIELDS, REPLICATION_CAPABILITY_CONTRACT_VERSION,
REPLICATION_READ_ONLY_HISTORICAL_FIELDS, REPLICATION_WRITABLE_FIELDS, ReplicationConfigStructureError,
ReplicationConfigurationExt, ReplicationRuleExt, ReplicationTargetValidationError, assign_site_replication_rule_priorities,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule, legacy_role_target_arn,
merge_incoming_replication_config, merge_user_replication_config, replication_target_arn_deployment_id,
replication_target_arns, should_remove_replication_target, site_replication_rule_deployment_id,
unsupported_replication_config_field, validate_replication_config_structure, validate_replication_config_target_arns,
@@ -25,6 +25,7 @@ use tracing::error;
use super::replication_config_boundary::{
ObjectOpts, ReplicationConfigurationExt as _, ReplicationRuleExt as _, invalid_replication_config_status_field,
legacy_role_target_arn,
};
use super::replication_error_boundary::Result;
use super::replication_filemeta_boundary::{
@@ -143,7 +144,7 @@ fn validate_delete_replication_config(
)));
}
let role = config.role.trim();
let role = legacy_role_target_arn(&config.role).unwrap_or_default();
let mut role_destination = None;
for rule in &config.rules {
if rule.status.as_str() == Status::ENABLED.as_str() {
@@ -1101,4 +1102,29 @@ mod tests {
let stored_marker = config.resync(marker, ReplicateDecision::default(), &HashMap::new()).await;
assert!(!stored_marker.targets.contains_key(arn));
}
#[test]
fn validate_delete_replication_config_accepts_iam_role_with_multiple_destinations() {
let mut bucket_rule = replication_rule();
bucket_rule.destination.bucket = "arn:minio:replication:us-east-1:peer-b:bkt-replica".to_string();
let mut site_rule = replication_rule();
site_rule.id = Some("rustfs-site-replication:peer-b".to_string());
site_rule.priority = Some(2);
site_rule.destination.bucket = "arn:minio:replication:us-east-1:peer-b:bkt-source".to_string();
let config = PersistedReplicationConfiguration {
role: "arn:aws:iam::123456789012:role/rustfs-replication".to_string(),
rules: vec![bucket_rule, site_rule],
};
let versioning = VersioningConfiguration {
status: Some("Enabled".to_string()),
..Default::default()
};
assert!(
validate_delete_replication_config(&versioning, Some(&config)).is_ok(),
"AWS IAM role ARN must not be treated as a legacy single-target destination ARN"
);
}
}
@@ -1677,12 +1677,27 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
/// Queues a replica delete task
pub async fn queue_replica_delete_task(&self, doi: DeletedObjectReplicationInfo) -> ReplicationQueueAdmission {
if !self.in_flight.try_begin_delete(&doi) {
debug!(
event = EVENT_REPLICATION_IN_FLIGHT_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION,
bucket = %doi.bucket,
object = %doi.delete_object.object_name,
version_id = ?doi.delete_object.version_id,
delete_marker_version_id = ?doi.delete_object.delete_marker_version_id,
op_type = ?doi.op_type,
"Replication delete task already in flight; not queued again"
);
return ReplicationQueueAdmission::Skipped;
}
let target_arns = doi.admitted_target_arns();
let ch = self
.worker_queue_channel(&doi.op_type, &doi.bucket, &doi.delete_object.object_name, 0)
.await;
let Some(channel) = ch else {
self.in_flight.finish_delete(&doi);
return ReplicationQueueAdmission::Missed;
};
@@ -1694,6 +1709,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
self.stats.dec_q(&doi.bucket, 0, true, doi.op_type);
self.stats.dec_target_q(&doi.bucket, &target_arns, 0);
self.in_flight.finish_delete(&doi);
let admission = self.queue_mrf_save_admission(doi.to_mrf_entry(), "delete").await;
self.apply_queue_backpressure("delete", false, "Replication delete queue is backpressured")
@@ -2417,16 +2433,28 @@ pub(crate) struct ReplicationInFlight {
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ReplicationInFlightKey {
bucket: String,
object: String,
version_id: Option<uuid::Uuid>,
generation: ReplicationGenerationSnapshot,
enum ReplicationInFlightKey {
Object {
bucket: String,
object: String,
version_id: Option<uuid::Uuid>,
generation: ReplicationGenerationSnapshot,
},
Delete {
bucket: String,
object: String,
version_id: Option<uuid::Uuid>,
delete_marker_version_id: Option<uuid::Uuid>,
delete_marker: bool,
force_delete: bool,
force_delete_id: Option<uuid::Uuid>,
target_arns: Vec<String>,
},
}
impl From<&ReplicateObjectInfo> for ReplicationInFlightKey {
fn from(info: &ReplicateObjectInfo) -> Self {
Self {
Self::Object {
bucket: info.bucket.clone(),
object: info.name.clone(),
version_id: info.version_id,
@@ -2435,6 +2463,25 @@ impl From<&ReplicateObjectInfo> for ReplicationInFlightKey {
}
}
impl ReplicationInFlightKey {
fn from_delete(info: &DeletedObjectReplicationInfo) -> Option<Self> {
let del = &info.delete_object;
if del.version_id.is_none() && del.delete_marker_version_id.is_none() && del.force_delete_id.is_none() {
return None;
}
Some(Self::Delete {
bucket: info.bucket.clone(),
object: del.object_name.clone(),
version_id: del.version_id,
delete_marker_version_id: del.delete_marker_version_id,
delete_marker: del.delete_marker,
force_delete: del.force_delete,
force_delete_id: del.force_delete_id,
target_arns: info.admitted_target_arns(),
})
}
}
impl ReplicationInFlight {
fn lock(&self) -> std::sync::MutexGuard<'_, std::collections::HashSet<ReplicationInFlightKey>> {
self.keys.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
@@ -2449,6 +2496,19 @@ impl ReplicationInFlight {
self.lock().remove(&ReplicationInFlightKey::from(ri));
}
fn try_begin_delete(&self, doi: &DeletedObjectReplicationInfo) -> bool {
let Some(key) = ReplicationInFlightKey::from_delete(doi) else {
return true;
};
self.lock().insert(key)
}
fn finish_delete(&self, doi: &DeletedObjectReplicationInfo) {
if let Some(key) = ReplicationInFlightKey::from_delete(doi) {
self.lock().remove(&key);
}
}
#[cfg(test)]
fn len(&self) -> usize {
self.lock().len()
@@ -2459,21 +2519,30 @@ impl ReplicationInFlight {
/// including when replication panics.
struct ReplicationInFlightGuard {
in_flight: Arc<ReplicationInFlight>,
key: ReplicationInFlightKey,
key: Option<ReplicationInFlightKey>,
}
impl ReplicationInFlightGuard {
fn new(in_flight: Arc<ReplicationInFlight>, ri: &ReplicateObjectInfo) -> Self {
Self {
in_flight,
key: ReplicationInFlightKey::from(ri),
key: Some(ReplicationInFlightKey::from(ri)),
}
}
fn for_delete(in_flight: Arc<ReplicationInFlight>, doi: &DeletedObjectReplicationInfo) -> Self {
Self {
in_flight,
key: ReplicationInFlightKey::from_delete(doi),
}
}
}
impl Drop for ReplicationInFlightGuard {
fn drop(&mut self) {
self.in_flight.lock().remove(&self.key);
if let Some(key) = self.key.take() {
self.in_flight.lock().remove(&key);
}
}
}
@@ -2548,6 +2617,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
let _in_flight = ReplicationInFlightGuard::for_delete(in_flight, del_info.as_ref());
replicate_delete(*del_info, storage).await;
}
}
@@ -4164,6 +4234,38 @@ mod tests {
assert!(in_flight.try_begin(&ri));
}
#[tokio::test]
async fn queue_replica_delete_task_deduplicates_versioned_delete_in_flight() {
let pool = new_test_replication_pool(Arc::new(LoadResyncNodeStore::new("node-a", empty_resync_shared_state()))).await;
let (tx, _rx) = mpsc::channel(4);
pool.workers.write().await.push(tx);
let dm_version = uuid::Uuid::new_v4();
let doi = DeletedObjectReplicationInfo {
bucket: "delete-dedup-bucket".to_string(),
op_type: ReplicationType::Heal,
target_arn: "arn:minio:replication:us-east-1:peer-b:replica".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "prod/dyn-0".to_string(),
delete_marker: true,
delete_marker_version_id: Some(dm_version),
..Default::default()
},
..Default::default()
};
assert_eq!(pool.queue_replica_delete_task(doi.clone()).await, ReplicationQueueAdmission::Queued);
assert_eq!(
pool.queue_replica_delete_task(doi.clone()).await,
ReplicationQueueAdmission::Skipped,
"scanner heal must not enqueue duplicate copies of an already-queued delete marker"
);
assert_eq!(pool.in_flight.len(), 1);
drop(ReplicationInFlightGuard::for_delete(pool.in_flight.clone(), &doi));
assert_eq!(pool.in_flight.len(), 0);
assert_eq!(pool.queue_replica_delete_task(doi).await, ReplicationQueueAdmission::Queued);
}
#[tokio::test]
async fn regular_worker_admission_counts_target_backlog_before_receive() {
let pool = new_test_replication_pool(Arc::new(LoadResyncNodeStore::new("node-a", empty_resync_shared_state()))).await;
@@ -13,7 +13,7 @@
// limitations under the License.
use super::replication_bandwidth_boundary;
use super::replication_config_boundary::{ObjectOpts, ReplicationConfigurationExt as _};
use super::replication_config_boundary::{ObjectOpts, ReplicationConfigurationExt as _, legacy_role_target_arn};
use super::replication_config_store::ReplicationConfigStore;
use super::replication_error_boundary::{Error, Result, is_err_object_not_found, is_err_version_not_found};
use super::replication_event_sink::{EventArgs, send_event, send_local_event};
@@ -2195,14 +2195,14 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
let has_stored_delete_decision = stored_delete_decision.is_some();
if let Some(rc) = rcfg.config.as_ref()
&& !rc.role.is_empty()
&& let Some(role) = legacy_role_target_arn(&rc.role)
{
if oi.version_purge_status_internal.is_none() && !oi.version_purge_status.is_empty() {
oi.version_purge_status_internal = Some(format!("{}={};", rc.role, oi.version_purge_status.as_str()));
oi.version_purge_status_internal = Some(format!("{role}={};", oi.version_purge_status.as_str()));
}
if oi.replication_status_internal.is_none() && !oi.replication_status.is_empty() {
oi.replication_status_internal = Some(format!("{}={};", rc.role, oi.replication_status.as_str()));
oi.replication_status_internal = Some(format!("{role}={};", oi.replication_status.as_str()));
}
let keys_to_update: Vec<_> = user_defined
@@ -2213,7 +2213,7 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
for (k, v) in keys_to_update {
user_defined.remove(&k);
user_defined.insert(target_reset_header(rc.role.as_str()), v);
user_defined.insert(target_reset_header(role), v);
}
}
@@ -2686,7 +2686,25 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
let purge_source = purge_source.clone();
// Spawn task in the join set
join_set.spawn(async move { replicate_delete_to_target(&dobj_clone, tgt_client.clone(), purge_source).await });
let is_site_peer = tgt_client.is_site_replication_peer();
join_set.spawn(async move {
let tgt_info = replicate_delete_to_target(&dobj_clone, tgt_client.clone(), purge_source).await;
let source = if is_site_peer {
rustfs_scanner_metrics::metrics::ScannerWorkSource::SiteReplication
} else {
rustfs_scanner_metrics::metrics::ScannerWorkSource::BucketReplication
};
match tgt_info.replication_status {
ReplicationStatusType::Completed | ReplicationStatusType::CompletedLegacy => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_executed(source, 1);
}
ReplicationStatusType::Failed => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_failed(source, 1);
}
_ => {}
}
tgt_info
});
}
// Collect all results
@@ -4328,12 +4346,28 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
let roi_clone = roi.clone();
let storage_clone = storage.clone();
let is_site_peer = tgt_client.is_site_replication_peer();
join_set.spawn(async move {
if roi.op_type == ReplicationType::Object {
let tgt_info = if roi.op_type == ReplicationType::Object {
roi_clone.replicate_object(storage_clone, tgt_client).await
} else {
roi_clone.replicate_all(storage_clone, tgt_client).await
};
let source = if is_site_peer {
rustfs_scanner_metrics::metrics::ScannerWorkSource::SiteReplication
} else {
rustfs_scanner_metrics::metrics::ScannerWorkSource::BucketReplication
};
match tgt_info.replication_status {
ReplicationStatusType::Completed | ReplicationStatusType::CompletedLegacy => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_executed(source, 1);
}
ReplicationStatusType::Failed => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_failed(source, 1);
}
_ => {}
}
tgt_info
});
}
@@ -283,8 +283,13 @@ impl BucketTarget {
self.target_bucket.is_empty() && self.endpoint.is_empty() && self.arn.is_empty()
}
pub fn url(&self) -> Result<Url> {
let trimmed = self.endpoint.trim();
let host_and_path = trimmed
.strip_prefix("https://")
.or_else(|| trimmed.strip_prefix("http://"))
.unwrap_or(trimmed);
let scheme = if self.secure { "https" } else { "http" };
Url::parse(&format!("{}://{}", scheme, self.endpoint)).map_err(Error::other)
Url::parse(&format!("{}://{}", scheme, host_and_path)).map_err(Error::other)
}
}
@@ -175,7 +175,26 @@ fn endpoint_matches_audience(endpoint: &str, audience: &str) -> bool {
}
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 {
if old_epoch == new_epoch {
return;
}
let owner = audience.to_string();
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
let reclaimed = rustfs_lock::reclaim_all_local_guards_for_owner(&owner).await;
if reclaimed > 0 {
info!(
event = "internode_peer_locks_reclaimed_on_restart",
owner = %owner,
old_boot_epoch = %old_epoch,
new_boot_epoch = %new_epoch,
reclaimed,
"Reclaimed stale local lock guards from restarted peer incarnation"
);
}
});
}
if *STREAM_RESPONSE_AUTH_STRICT {
return;
}
let mut removed_endpoints = Vec::new();
@@ -138,8 +138,17 @@ impl<T: Send + 'static> Drop for InFlightRpc<'_, T> {
const LOCK_RPC_LIVENESS_WINDOW_DEADLINES: u32 = 2;
const LOCK_RPC_REQUEST_BACKOFF_THRESHOLD: u32 = 3;
const LOCK_RPC_REQUEST_BACKOFF_MAX: Duration = Duration::from_secs(30);
const LATE_RELEASE_RETRY_DELAYS: [Duration; 3] = [Duration::from_millis(100), Duration::from_millis(500), Duration::from_secs(1)];
const LATE_RELEASE_IN_FLIGHT_LIMIT: usize = 32;
const LATE_RELEASE_RETRY_DELAYS: [Duration; 8] = [
Duration::from_millis(100),
Duration::from_millis(250),
Duration::from_millis(500),
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(4),
Duration::from_secs(8),
Duration::from_secs(16),
];
const LATE_RELEASE_IN_FLIGHT_LIMIT: usize = 256;
const TIMEOUT_LOG_STATE_MAX: usize = 1024;
const TIMEOUT_LOG_STATE_RETENTION: Duration = Duration::from_secs(600);
@@ -468,6 +477,15 @@ impl RemoteClient {
if let Some(reason) = crate::cluster::rpc::remote_disk::internode_offline_bypass_reason(&self.addr) {
return Err(LockError::internal(reason));
}
self.get_client_for_cleanup().await
}
async fn get_client_for_cleanup(
&self,
) -> Result<NodeServiceClient<InterceptedService<AuthenticatedChannel, TonicInterceptor>>> {
// Unlock and late-release cleanup RPCs intentionally bypass `internode_offline_bypass_reason`
// so that as soon as a partitioned or paused peer becomes reachable again, pending lock
// releases clear immediately instead of waiting for `remote_disk`'s periodic health monitor.
node_service_time_out_client(&self.addr, TonicInterceptor::Signature(gen_tonic_signature_interceptor()))
.await
.map_err(|err| LockError::internal(format!("can not get client, err: {err}")))
@@ -973,7 +991,7 @@ impl RemoteClient {
let unlock_request = Self::create_unlock_request(lock_id);
let request_string = serde_json::to_string(&unlock_request)
.map_err(|e| LockError::internal(format!("Failed to serialize request: {e}")))?;
let mut client = self.get_client().await?;
let mut client = self.get_client_for_cleanup().await?;
let resource_summary = unlock_request.resource.to_string();
let mut req = Request::new(GenerallyLockRequest { args: request_string });
attach_lock_mutation_body_digest(&mut req)?;
@@ -991,7 +1009,7 @@ impl RemoteClient {
async fn request_release_batch(&self, lock_ids: &[LockId]) -> Result<BatchGenerallyLockResponse> {
let unlock_requests = lock_ids.iter().map(Self::create_unlock_request).collect::<Vec<_>>();
let mut client = self.get_client().await?;
let mut client = self.get_client_for_cleanup().await?;
let resource_summary = Self::summarize_resources(&unlock_requests);
let mut req = Request::new(BatchGenerallyLockRequest {
args: unlock_requests
+4 -2
View File
@@ -185,8 +185,10 @@ const DECOMMISSION_CAPACITY_INTENT_CONFLICT_MAX_ATTEMPTS: usize = 12;
// A scanner pause backlog handoff conflict is a transient membership
// transition: the native authority is expected to converge once surviving
// replicas advance their durable commit. Bound the wait so a genuinely
// divergent authority still reaches a terminal, attributable failure.
const DECOMMISSION_SCANNER_BACKLOG_HANDOFF_MAX_ATTEMPTS: usize = 12;
// divergent authority still reaches a terminal, attributable failure, while
// giving multi-second network partitions and post-partition membership commits
// enough budget (~65s at the 1.5s backoff cap) to converge.
const DECOMMISSION_SCANNER_BACKLOG_HANDOFF_MAX_ATTEMPTS: usize = 48;
const DECOMMISSION_SOURCE_CLEANUP_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(100);
/// In-place attempts for a source cleanup quorum failure before the entry is
/// deferred to the end of the round.
+1 -1
View File
@@ -1832,7 +1832,7 @@ impl LocalDiskWrapper {
/// Only suppresses idle monitoring; request paths still validate the format on disk.
pub(crate) async fn can_skip_background_probe(&self) -> bool {
if self.runtime_state() != RuntimeDriveHealthState::Online {
if self.retired.is_cancelled() || self.runtime_state() != RuntimeDriveHealthState::Online {
return false;
}
let observed = self.disk.format_info.read().await.id;
@@ -532,8 +532,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 +549,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 +654,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 +722,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 +1118,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"
-15
View File
@@ -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())
}
@@ -58,6 +58,7 @@ pub use types::{
RebalanceStats, RebalanceStopPropagationRecord,
};
use types::{RebalanceBucketConfigs, RebalanceBucketOutcome, RebalanceDeferKind, RebalanceEntryOutcome};
pub(crate) use worker::is_transient_rebalance_error;
#[cfg(any(test, feature = "test-util"))]
pub async fn test_store_with_persisted_rebalance_meta(
@@ -287,7 +287,7 @@ pub(super) fn resolve_rebalance_bucket_result(
}
}
pub(super) fn is_transient_rebalance_error(err: &Error) -> bool {
pub(crate) fn is_transient_rebalance_error(err: &Error) -> bool {
let err = rebalance_error_source(err);
match err {
Error::SlowDown
+213 -46
View File
@@ -8022,18 +8022,47 @@ impl SetDisks {
// - If no_lock is false, we must have obtained the lock out side of this function
// - If no_lock is true, we should not obtain locks
lookup_opts.no_lock = true;
let lookup = self.get_object_info(bucket, object, &lookup_opts);
#[cfg(feature = "diagnostic-read-version-caller")]
let lookup = crate::cluster::rpc::runtime_sources::with_read_version_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::WritePreconditionRead,
async {
crate::cluster::rpc::runtime_sources::observe_read_version_context_boundary(
rustfs_io_metrics::internode_metrics::ReadVersionContextBoundary::WritePreconditionLookup,
);
lookup.await
},
);
let oi = lookup.await;
let oi = if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|store| {
!store.single_pool()
&& !crate::bucket::utils::is_meta_bucketname(bucket)
&& !opts.data_movement
&& !opts.replication_request
&& !opts.no_lock
&& !opts.skip_decommissioned
&& !opts.skip_rebalancing
}) {
lookup_opts.metadata_cache_safe = false;
lookup_opts.metadata_cache_fence_proof = None;
lookup_opts.suppress_read_repair = true;
let lookup = store.get_latest_object_info_for_conditional_write(bucket, object, &lookup_opts);
#[cfg(feature = "diagnostic-read-version-caller")]
let lookup = crate::cluster::rpc::runtime_sources::with_read_version_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::WritePreconditionRead,
async {
crate::cluster::rpc::runtime_sources::observe_read_version_context_boundary(
rustfs_io_metrics::internode_metrics::ReadVersionContextBoundary::WritePreconditionLookup,
);
lookup.await
},
);
lookup.await.and_then(|(info, _)| {
lookup_opts.precondition_check(&info)?;
Ok(info)
})
} else {
let lookup = self.get_object_info(bucket, object, &lookup_opts);
#[cfg(feature = "diagnostic-read-version-caller")]
let lookup = crate::cluster::rpc::runtime_sources::with_read_version_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::WritePreconditionRead,
async {
crate::cluster::rpc::runtime_sources::observe_read_version_context_boundary(
rustfs_io_metrics::internode_metrics::ReadVersionContextBoundary::WritePreconditionLookup,
);
lookup.await
},
);
lookup.await
};
Self::evaluate_write_precondition(oi, &http_preconditions, bucket, object, opts)
}
}
@@ -12909,36 +12938,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 +12960,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 +13185,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 +13250,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 +13310,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;
+316 -2
View File
@@ -14,9 +14,10 @@
use super::{
Bytes, DATA_MOVEMENT_MULTIPART_PREFIX, DiskError, DiskStore, FileInfo, HashMap, HashSet, OBJECT_OP_IGNORED_ERRS, ObjProps,
OffsetDateTime, SetDisks, Sha256, TRANSITION_COMPLETE, Uuid, debug, disk, error, file_info_is_valid_for_metadata, hex,
reduce_read_quorum_errs, warn,
OffsetDateTime, SLASH_SEPARATOR, SetDisks, Sha256, TRANSITION_COMPLETE, Uuid, debug, disk, error,
file_info_is_valid_for_metadata, hex, reduce_read_quorum_errs, warn,
};
use crate::disk::DiskAPI;
#[cfg(test)]
use crate::disk::DiskOption;
#[cfg(test)]
@@ -27,6 +28,21 @@ use rustfs_filemeta::metadata_keys;
use rustfs_utils::http;
use sha2::Digest;
const MAX_INCOMPLETE_OVERWRITE_ROLLBACK_STEPS: usize = 4;
pub(super) struct IncompleteOverwriteSlotRollback {
pub(super) slot_index: usize,
pub(super) rollback_dir: Uuid,
pub(super) undo_file_info: FileInfo,
}
pub(super) struct IncompleteOverwriteResolution {
pub(super) online_disks: Vec<Option<DiskStore>>,
pub(super) fi: FileInfo,
pub(super) parts_metadata: Vec<FileInfo>,
pub(super) rollbacks: Vec<IncompleteOverwriteSlotRollback>,
}
#[derive(Clone, Copy)]
struct FileInfoIdentityGroup {
key: FileInfoQuorumKey,
@@ -790,6 +806,304 @@ impl SetDisks {
Self::find_file_info_in_quorum(metas, &mod_time, &etag, quorum)
}
pub(super) fn is_null_version_request(version_id: &str) -> bool {
version_id.is_empty() || Uuid::parse_str(version_id).is_ok_and(|id| id.is_nil())
}
/// Quick complete-set check before inspecting per-disk `xl.meta.bkp` files:
/// requires a non-system null-version target, every set member online and
/// answering without transport/corruption errors, and every live identity at
/// the newest modification time strictly below its write quorum.
pub(super) fn may_have_incomplete_null_overwrite(
&self,
bucket: &str,
version_id: &str,
disks: &[Option<DiskStore>],
parts_metadata: &[FileInfo],
errs: &[Option<DiskError>],
) -> bool {
if crate::bucket::utils::is_meta_bucketname(bucket)
|| !Self::is_null_version_request(version_id)
|| disks.len() != self.set_drive_count
|| disks.is_empty()
|| parts_metadata.len() != disks.len()
|| errs.len() != disks.len()
|| disks.iter().any(Option::is_none)
{
return false;
}
if errs.iter().any(|err| {
!matches!(
err,
None | Some(DiskError::FileNotFound | DiskError::FileVersionNotFound | DiskError::VolumeNotFound)
)
}) {
return false;
}
Self::newest_live_generation_below_write_quorum(parts_metadata, errs, self.default_write_quorum()).is_some()
}
fn newest_live_generation_below_write_quorum(
parts_metadata: &[FileInfo],
errs: &[Option<DiskError>],
default_write_quorum: usize,
) -> Option<OffsetDateTime> {
let latest_mod_time = parts_metadata
.iter()
.zip(errs.iter())
.filter(|(fi, err)| err.is_none() && file_info_is_valid_for_metadata(fi))
.filter_map(|(fi, _)| fi.mod_time)
.max()?;
let mut counts: HashMap<FileInfoQuorumKey, (usize, usize)> = HashMap::new();
for (fi, err) in parts_metadata.iter().zip(errs.iter()) {
if err.is_some() || !file_info_is_valid_for_metadata(fi) || fi.mod_time != Some(latest_mod_time) {
continue;
}
let write_quorum = fi.write_quorum(default_write_quorum);
let entry = counts.entry(Self::file_info_quorum_key(fi)).or_insert((0, write_quorum));
entry.0 += 1;
if entry.0 >= entry.1 {
return None;
}
}
(!counts.is_empty()).then_some(latest_mod_time)
}
/// Resolve a split null-version set left behind when an unversioned
/// overwrite failed below write quorum and `undo_write` was indeterminate
/// or failed on a subset of drives. With every drive in the set answering,
/// any newest live generation below write quorum never committed; restoring
/// those drives' preserved `<rollback_dir>/xl.meta.bkp` recovers the prior
/// committed version when the combined set reaches valid read quorum.
#[allow(clippy::too_many_arguments)]
pub(super) async fn discover_incomplete_overwrite_rollbacks(
&self,
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
version_id: &str,
parts_metadata: &[FileInfo],
errs: &[Option<DiskError>],
read_data: bool,
include_part_checksums: bool,
) -> Option<IncompleteOverwriteResolution> {
if !self.may_have_incomplete_null_overwrite(bucket, version_id, disks, parts_metadata, errs) {
return None;
}
let disk_object = rustfs_utils::path::encode_dir_object(object);
let mut candidate_metadata = parts_metadata.to_vec();
let candidate_errs = errs.to_vec();
let mut rolled_back_slots = vec![false; disks.len()];
let mut rollbacks = Vec::new();
let default_write_quorum = self.default_write_quorum();
for _ in 0..MAX_INCOMPLETE_OVERWRITE_ROLLBACK_STEPS {
let Some(latest_mod_time) =
Self::newest_live_generation_below_write_quorum(&candidate_metadata, &candidate_errs, default_write_quorum)
else {
break;
};
let target_slots = (0..disks.len())
.filter(|&slot| {
!rolled_back_slots[slot]
&& candidate_errs[slot].is_none()
&& file_info_is_valid_for_metadata(&candidate_metadata[slot])
&& candidate_metadata[slot].mod_time == Some(latest_mod_time)
})
.collect::<Vec<_>>();
if target_slots.is_empty() {
break;
}
let mut step_rolled_back = false;
for slot_index in target_slots {
let disk = disks.get(slot_index).and_then(Option::as_ref)?;
let live_fi = &candidate_metadata[slot_index];
let loaded = Self::load_overwrite_rollback_backup_on_disk(
disk,
bucket,
object,
&disk_object,
live_fi,
read_data,
include_part_checksums,
)
.await?;
let Some((rollback_dir, bkp_fi)) = loaded else {
continue;
};
let mut undo_file_info = live_fi.clone();
if undo_file_info.data_dir == bkp_fi.data_dir {
undo_file_info.data_dir = None;
}
candidate_metadata[slot_index] = bkp_fi;
rolled_back_slots[slot_index] = true;
rollbacks.push(IncompleteOverwriteSlotRollback {
slot_index,
rollback_dir,
undo_file_info,
});
step_rolled_back = true;
}
if !step_rolled_back {
break;
}
if let Ok((read_quorum, _)) =
Self::object_quorum_from_meta(&candidate_metadata, &candidate_errs, self.default_parity_count)
&& let Ok(read_quorum) = usize::try_from(read_quorum)
&& reduce_read_quorum_errs(&candidate_errs, OBJECT_OP_IGNORED_ERRS, read_quorum).is_none()
&& let Ok((online_disks, fi)) =
Self::select_valid_fileinfo(disks, &candidate_metadata, &candidate_errs, read_quorum)
{
return Some(IncompleteOverwriteResolution {
online_disks,
fi,
parts_metadata: candidate_metadata,
rollbacks,
});
}
}
None
}
async fn load_overwrite_rollback_backup_on_disk(
disk: &DiskStore,
bucket: &str,
object: &str,
disk_object: &str,
live_fi: &FileInfo,
read_data: bool,
include_part_checksums: bool,
) -> Option<Option<(Uuid, FileInfo)>> {
let entries = match disk.list_dir("", bucket, disk_object, -1).await {
Ok(entries) => entries,
Err(
DiskError::FileNotFound | DiskError::FileVersionNotFound | DiskError::PathNotFound | DiskError::VolumeNotFound,
) => return Some(None),
Err(_) => return None,
};
let live_key = Self::file_info_quorum_key(live_fi);
let mut best: Option<(Uuid, FileInfo)> = None;
for entry in entries {
if !entry.ends_with(SLASH_SEPARATOR) {
continue;
}
let Ok(candidate_dir) = Uuid::parse_str(entry.trim_end_matches(SLASH_SEPARATOR)) else {
continue;
};
let sub_path = format!("{disk_object}{SLASH_SEPARATOR}{candidate_dir}");
let sub_entries = match disk.list_dir("", bucket, &sub_path, -1).await {
Ok(sub_entries) => sub_entries,
Err(
DiskError::FileNotFound
| DiskError::FileVersionNotFound
| DiskError::PathNotFound
| DiskError::VolumeNotFound,
) => continue,
Err(_) => return None,
};
if !sub_entries.iter().any(|name| name == crate::disk::STORAGE_FORMAT_FILE_BACKUP) {
continue;
}
if sub_entries.iter().any(|name| {
let trimmed = name.trim_end_matches(SLASH_SEPARATOR);
matches!(
trimmed,
"delete-prepared"
| "delete-target"
| "delete-commit-finished"
| crate::disk::local::DELETE_QUORUM_COMMITTED_FILE
| "xl.meta.delete-marker.rollback"
)
}) {
continue;
}
let bkp_path = format!("{sub_path}{SLASH_SEPARATOR}{}", crate::disk::STORAGE_FORMAT_FILE_BACKUP);
let bkp_bytes = match disk.read_all(bucket, &bkp_path).await {
Ok(bytes) => bytes,
Err(
DiskError::FileNotFound
| DiskError::FileVersionNotFound
| DiskError::PathNotFound
| DiskError::VolumeNotFound,
) => continue,
Err(_) => return None,
};
let Ok(bkp_meta) = rustfs_filemeta::FileMeta::load(&bkp_bytes) else {
continue;
};
let expected_dir = bkp_meta
.find_unshared_data_dir_for_version(Some(Uuid::nil()))
.unwrap_or_else(|| crate::disk::local::inline_metadata_rollback_dir(Uuid::nil(), &bkp_meta));
if expected_dir != candidate_dir {
continue;
}
let Ok(mut bkp_fi) = rustfs_filemeta::get_file_info(
&bkp_bytes,
bucket,
object,
"",
rustfs_filemeta::FileInfoOpts {
data: read_data,
include_free_versions: false,
include_part_checksums,
},
) else {
continue;
};
if bkp_fi.validate_for_metadata_read().is_err() {
continue;
}
if read_data
&& (bkp_fi.data.as_ref().is_some_and(|d| !d.is_empty()) || bkp_fi.size == 0)
&& !bkp_fi.inline_data()
&& (bkp_fi.size == 0 || bkp_fi.version_id.is_none_or(|v| v.is_nil()))
{
bkp_fi.set_inline_data();
}
if !file_info_is_valid_for_metadata(&bkp_fi)
|| bkp_fi.mod_time > live_fi.mod_time
|| Self::file_info_quorum_key(&bkp_fi) == live_key
{
continue;
}
if !bkp_fi.deleted && !bkp_fi.is_remote() && !bkp_fi.inline_data() && bkp_fi.size > 0 {
match disk.check_parts(bucket, object, &bkp_fi).await {
Ok(resp)
if !resp.results.is_empty() && resp.results.iter().all(|res| *res == crate::disk::CHECK_PART_SUCCESS) => {
}
Ok(_)
| Err(
DiskError::FileNotFound
| DiskError::FileVersionNotFound
| DiskError::PathNotFound
| DiskError::VolumeNotFound,
) => continue,
Err(_) => return None,
}
}
if best.as_ref().is_none_or(|(_, prev)| bkp_fi.mod_time > prev.mod_time) {
best = Some((candidate_dir, bkp_fi));
}
}
Some(best)
}
pub(crate) fn hydrate_selected_fileinfo_part_checksums(fi: &mut FileInfo) -> disk::error::Result<()> {
fi.hydrate_shard_integrity().map_err(DiskError::from)?;
fi.hydrate_data_movement_part_checksums().map_err(DiskError::from)?;
+119 -5
View File
@@ -391,6 +391,33 @@ struct ObjectLockDiagGuard {
mode: &'static str,
acquired_at: Instant,
_attempt: ObjectLockAttempt,
_local_writer_gate: Option<tokio::sync::OwnedMutexGuard<()>>,
}
type PutCommitKeyGateKey = (String, String, String);
type PutCommitKeyGateMap = HashMap<PutCommitKeyGateKey, std::sync::Weak<tokio::sync::Mutex<()>>>;
static LOCAL_PUT_COMMIT_KEY_GATES: std::sync::LazyLock<std::sync::Mutex<PutCommitKeyGateMap>> =
std::sync::LazyLock::new(|| std::sync::Mutex::new(HashMap::new()));
fn local_put_commit_key_gate(namespace: &str, bucket: &str, object: &str) -> Arc<tokio::sync::Mutex<()>> {
let key = (
namespace.to_string(),
bucket.to_string(),
rustfs_utils::path::object_name_disk_identity(object).into_owned(),
);
let mut gates = LOCAL_PUT_COMMIT_KEY_GATES
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(existing) = gates.get(&key).and_then(std::sync::Weak::upgrade) {
return existing;
}
if gates.len() > 4096 {
gates.retain(|_, weak| weak.strong_count() > 0);
}
let created = Arc::new(tokio::sync::Mutex::new(()));
gates.insert(key, Arc::downgrade(&created));
created
}
impl ObjectLockDiagGuard {
@@ -413,6 +440,7 @@ impl ObjectLockDiagGuard {
mode,
acquired_at: Instant::now(),
_attempt: ObjectLockAttempt::default(),
_local_writer_gate: None,
}
}
@@ -421,6 +449,11 @@ impl ObjectLockDiagGuard {
self
}
fn with_local_writer_gate(mut self, gate: Option<tokio::sync::OwnedMutexGuard<()>>) -> Self {
self._local_writer_gate = gate;
self
}
/// Whether the underlying namespace lock's heartbeat has observed a
/// refresh-quorum loss (backlog#899 Phase 2). Callers fence their commit
/// point on this so a stale lock holder does not race a double-write.
@@ -5569,7 +5602,13 @@ impl SetDisks {
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let acquire_start = Instant::now();
let timeout = get_lock_acquire_timeout();
let mut timeout = get_lock_acquire_timeout();
if op == "get_object_info"
&& self.ctx.is_dist_erasure().await
&& rustfs_utils::get_env_opt_str(rustfs_config::ENV_OBJECT_LOCK_ACQUIRE_TIMEOUT).is_none()
{
timeout = timeout.max(Duration::from_secs(8));
}
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "read", timeout);
let result = ns_lock.get_read_lock(timeout).await;
if let Err(error) = &result {
@@ -5591,14 +5630,88 @@ impl SetDisks {
.with_attempt(attempt))
}
async fn acquire_dist_put_commit_write_lock(
&self,
ns_lock: &NamespaceLockWrapper,
bucket: &str,
object: &str,
acquire_start: Instant,
acquire_timeout: Duration,
) -> std::result::Result<NamespaceLockGuard, rustfs_lock::error::LockError> {
use std::hash::{Hash, Hasher};
const SPLIT_VOTE_BUDGETS_MS: [u64; 3] = [120, 240, 480];
let mut hasher = std::collections::hash_map::DefaultHasher::new();
ns_lock.owner().hash(&mut hasher);
let owner_jitter_ms = (hasher.finish() % 4).saturating_mul(8);
let mut round = 0usize;
loop {
let remaining = acquire_timeout.saturating_sub(acquire_start.elapsed());
if remaining.is_zero() {
return Err(rustfs_lock::LockError::timeout(format!("{bucket}/{object}"), acquire_timeout));
}
let round_budget = SPLIT_VOTE_BUDGETS_MS
.get(round)
.map(|&ms| Duration::from_millis(ms).min(remaining))
.unwrap_or(remaining);
match ns_lock.get_write_lock(round_budget).await {
Ok(guard) => return Ok(guard),
Err(err @ (rustfs_lock::LockError::Timeout { .. } | rustfs_lock::LockError::AlreadyLocked { .. })) => {
let after_elapsed = acquire_start.elapsed();
if after_elapsed >= acquire_timeout {
return Err(err);
}
let left = acquire_timeout.saturating_sub(after_elapsed);
let rand_jitter_ms = (u64::from(rand::random::<u8>()) % 13).saturating_add(4);
let backoff = Duration::from_millis(owner_jitter_ms.saturating_add(rand_jitter_ms)).min(left / 4);
if !backoff.is_zero() {
tokio::time::sleep(backoff).await;
}
round = round.saturating_add(1);
}
Err(err) => return Err(err),
}
}
}
async fn acquire_write_lock_diag(&self, op: &'static str, bucket: &str, object: &str) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let acquire_start = Instant::now();
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
let result = ns_lock.get_write_lock(acquire_timeout).await;
let mut acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let dist_erasure = self.ctx.is_dist_erasure().await;
if op == "put_object_commit"
&& dist_erasure
&& !put_object_commit_lock_timeout_override_enabled(op)
&& rustfs_utils::get_env_opt_str(rustfs_config::ENV_OBJECT_LOCK_ACQUIRE_TIMEOUT).is_none()
{
acquire_timeout = acquire_timeout.max(Duration::from_secs(8));
}
let local_writer_gate = if op == "put_object_commit" && dist_erasure {
let gate = local_put_commit_key_gate(&self.set_lock_namespace, bucket, object);
match tokio::time::timeout(acquire_timeout, gate.lock_owned()).await {
Ok(guard) => Some(guard),
Err(_) => {
let err = rustfs_lock::LockError::timeout(format!("{bucket}/{object}"), acquire_timeout);
record_lock_acquire_failure(op, bucket, object, "write", &err);
record_put_object_commit_lock_admission(op, put_object_commit_lock_acquire_error_outcome(op, &err));
return Err(map_put_object_commit_lock_acquire_error(self, op, bucket, object, err));
}
}
} else {
None
};
let remaining_timeout = acquire_timeout.saturating_sub(acquire_start.elapsed());
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", remaining_timeout);
let result = if op == "put_object_commit" && dist_erasure && !put_object_commit_lock_timeout_override_enabled(op) {
self.acquire_dist_put_commit_write_lock(&ns_lock, bucket, object, acquire_start, acquire_timeout)
.await
} else {
ns_lock.get_write_lock(remaining_timeout).await
};
if let Err(error) = &result {
record_lock_acquire_failure(op, bucket, object, "write", error);
}
@@ -5624,7 +5737,8 @@ impl SetDisks {
owner,
"write",
)
.with_attempt(attempt))
.with_attempt(attempt)
.with_local_writer_gate(local_writer_gate))
}
#[cfg(any(test, feature = "test-util"))]
@@ -917,6 +917,29 @@ impl SetDisks {
self.recover_delete_key(bucket, object, context).await
}
/// Fast-path check used while holding the key's write and transaction locks:
/// returns `true` only when every drive in the set is online and reports zero
/// pending delete recovery transactions for `bucket/object`.
pub(in crate::set_disk) async fn has_no_pending_delete_recovery_transactions(
&self,
bucket: &str,
object: &str,
work_budget: Option<&crate::object_api::DeleteRecoveryWorkBudget>,
) -> bool {
let disks = self.disk_inventory().await;
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
return false;
}
let pages = join_all(disks.iter().flatten().map(|disk| async {
match work_budget {
Some(budget) => discover_bounded(disk, bucket, object, budget).await,
None => discover(disk, bucket, Some(object)).await,
}
}))
.await;
pages.into_iter().all(|page| matches!(page, Ok(ids) if ids.is_empty()))
}
/// Caller retains the exact key's write lock and its lifecycle owner.
pub(in crate::set_disk) async fn recover_delete_key(
&self,
+493 -73
View File
@@ -2306,7 +2306,115 @@ impl SetDisks {
Ok((result, None))
}
Err(err) => Ok((result, Some(err))),
Err(err) => {
if err == DiskError::ErasureReadQuorum
&& !opts.dry_run
&& allow_explicit_version_regen
&& self.may_have_incomplete_null_overwrite(bucket, version_id, &disks, &parts_metadata, &errs)
{
let mut upgraded_write_guard = None;
if read_repair_uses_shared_lock {
drop(_read_repair_read_lock_guard.take());
let guard = Arc::new(
self.acquire_heal_object_lock(
bucket,
object,
version_id,
HealObjectLockKind::Write,
"heal_object_overwrite_rollback",
)
.await?,
);
upgraded_write_guard = Some(guard);
let (fresh_meta, fresh_errs, _) =
Self::read_metadata(&disks, "", bucket, object, version_id, true, true, false)
.await?
.into_legacy();
parts_metadata = fresh_meta;
let active_guard = upgraded_write_guard.as_ref().or(_write_lock_guard.as_ref());
let undo_owner: Arc<dyn Send + Sync> = Arc::new((
namespace_owner.cloned(),
active_guard.cloned(),
bucket_heal_scope.clone(),
self.ctx.begin_namespace_commit_for_bucket(bucket),
));
let _ = self
.try_recover_incomplete_overwrite_meta(
bucket,
object,
version_id,
&parts_metadata,
&fresh_errs,
&disks,
commit_fence,
Some(undo_owner),
)
.await?;
if active_guard.is_some_and(|guard| guard.is_lock_lost()) {
return Err(DiskError::DiskOngoingReq);
}
let retry_opts = HealOpts {
no_lock: true,
read_repair: false,
..*opts
};
return Box::pin(self.heal_object_with_explicit_version_regen(
bucket,
object,
version_id,
ExplicitVersionHeal {
opts: &retry_opts,
allow_regeneration: false,
..run
},
absence,
))
.await;
}
let active_guard = upgraded_write_guard.as_ref().or(_write_lock_guard.as_ref());
let undo_owner: Arc<dyn Send + Sync> = Arc::new((
namespace_owner.cloned(),
active_guard.cloned(),
bucket_heal_scope.clone(),
self.ctx.begin_namespace_commit_for_bucket(bucket),
));
if self
.try_recover_incomplete_overwrite_meta(
bucket,
object,
version_id,
&parts_metadata,
&errs,
&disks,
commit_fence,
Some(undo_owner),
)
.await?
{
if active_guard.is_some_and(|guard| guard.is_lock_lost()) {
return Err(DiskError::DiskOngoingReq);
}
let retry_opts = HealOpts {
no_lock: true,
read_repair: false,
..*opts
};
return Box::pin(self.heal_object_with_explicit_version_regen(
bucket,
object,
version_id,
ExplicitVersionHeal {
opts: &retry_opts,
allow_regeneration: false,
..run
},
absence,
))
.await;
}
}
Ok((result, Some(err)))
}
}
}
Err(err) => {
@@ -2375,6 +2483,75 @@ impl SetDisks {
))
.await;
}
if err == DiskError::ErasureReadQuorum
&& !opts.dry_run
&& allow_explicit_version_regen
&& self.may_have_incomplete_null_overwrite(bucket, version_id, &disks, &parts_metadata, &errs)
{
let mut upgraded_write_guard = None;
let mut active_errs = errs.clone();
if read_repair_uses_shared_lock {
drop(_read_repair_read_lock_guard.take());
let guard = Arc::new(
self.acquire_heal_object_lock(
bucket,
object,
version_id,
HealObjectLockKind::Write,
"heal_object_overwrite_rollback",
)
.await?,
);
upgraded_write_guard = Some(guard);
let (fresh_meta, fresh_errs, _) =
Self::read_metadata(&disks, "", bucket, object, version_id, true, true, false)
.await?
.into_legacy();
parts_metadata = fresh_meta;
active_errs = fresh_errs;
}
let active_guard = upgraded_write_guard.as_ref().or(_write_lock_guard.as_ref());
let undo_owner: Arc<dyn Send + Sync> = Arc::new((
namespace_owner.cloned(),
active_guard.cloned(),
bucket_heal_scope.clone(),
self.ctx.begin_namespace_commit_for_bucket(bucket),
));
let recovered = self
.try_recover_incomplete_overwrite_meta(
bucket,
object,
version_id,
&parts_metadata,
&active_errs,
&disks,
commit_fence,
Some(undo_owner),
)
.await?;
if recovered || upgraded_write_guard.is_some() {
if active_guard.is_some_and(|guard| guard.is_lock_lost()) {
return Err(DiskError::DiskOngoingReq);
}
let retry_opts = HealOpts {
no_lock: true,
read_repair: false,
..*opts
};
return Box::pin(self.heal_object_with_explicit_version_regen(
bucket,
object,
version_id,
ExplicitVersionHeal {
opts: &retry_opts,
allow_regeneration: false,
..run
},
absence,
))
.await;
}
}
if opts.dry_run || preserve_unrepairable || !opts.remove {
return Ok((
@@ -2649,6 +2826,57 @@ impl SetDisks {
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn try_recover_incomplete_overwrite_meta(
&self,
bucket: &str,
object: &str,
version_id: &str,
parts_metadata: &[FileInfo],
errs: &[Option<DiskError>],
disks: &[Option<DiskStore>],
commit_fence: Option<&(dyn Fn() -> bool + Sync)>,
undo_owner: Option<Arc<dyn Send + Sync>>,
) -> disk::error::Result<bool> {
if !self.may_have_incomplete_null_overwrite(bucket, version_id, disks, parts_metadata, errs) {
return Ok(false);
}
let Some(resolution) = self
.discover_incomplete_overwrite_rollbacks(disks, bucket, object, version_id, parts_metadata, errs, false, false)
.await
else {
return Ok(false);
};
if resolution.rollbacks.is_empty() {
return Ok(false);
}
if commit_fence.is_some_and(|check| !check()) {
return Err(DiskError::DiskOngoingReq);
}
for rollback in resolution.rollbacks {
if commit_fence.is_some_and(|check| !check()) {
return Err(DiskError::DiskOngoingReq);
}
let Some(disk) = disks.get(rollback.slot_index).and_then(Option::as_ref) else {
return Err(DiskError::DiskNotFound);
};
disk.undo_write_with_namespace_owner(
bucket,
object,
rollback.undo_file_info,
DeleteOptions {
undo_write: true,
old_data_dir: Some(rollback.rollback_dir),
..Default::default()
},
undo_owner.clone(),
)
.await?;
}
self.invalidate_get_object_metadata_cache(bucket, object).await;
Ok(true)
}
async fn try_regenerate_explicit_version_meta(
&self,
bucket: &str,
@@ -11827,51 +12055,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 +12103,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 +12116,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 +12154,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 +12179,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 +12194,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)
@@ -12572,4 +12791,205 @@ mod shard_identity_tests {
}
}
}
#[tokio::test]
async fn incomplete_null_overwrite_rollback_recovers_read_and_heal_without_resurrecting_committed_write() {
use crate::set_disk::{STORAGE_FORMAT_FILE, StorageError, Uuid};
for (label, v1, v2, v3) in [
("inline", vec![0x11; 138], vec![0x22; 138], vec![0x33; 138]),
(
"non-inline",
vec![0x11; 1024 * 1024 + 137],
vec![0x22; 1024 * 1024 + 137],
vec![0x33; 1024 * 1024 + 137],
),
] {
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
let bucket = format!("incomplete-overwrite-{label}");
let object = "coh-copy-0";
for disk in &disks {
disk.make_volume(&bucket).await.expect("bucket");
}
let opts = ObjectOptions {
no_lock: true,
metadata_cache_safe: false,
..Default::default()
};
// 1. V1 commits across all 6 drives.
set.put_object(&bucket, object, &mut PutObjReader::from_vec(v1.clone()), &opts)
.await
.expect("PUT V1");
let mut v1_metas = Vec::new();
for dir in &dirs {
v1_metas.push(
tokio::fs::read(dir.path().join(&bucket).join(object).join(STORAGE_FORMAT_FILE))
.await
.expect("read V1 xl.meta"),
);
}
// 2. V2 commits across drives 0..4 (write_quorum = 4), while drives 4..6 stay on stale V1.
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
set.put_object(&bucket, object, &mut PutObjReader::from_vec(v2.clone()), &opts)
.await
.expect("PUT V2");
let mut v2_metas = Vec::new();
let mut v2_parts = Vec::new();
for (idx, dir) in dirs.iter().enumerate() {
let obj_dir = dir.path().join(&bucket).join(object);
let bytes = tokio::fs::read(obj_dir.join(STORAGE_FORMAT_FILE))
.await
.expect("read V2 xl.meta");
let fm = rustfs_filemeta::FileMeta::load(&bytes).expect("parse V2 xl.meta");
let old_dir = fm.find_unshared_data_dir_for_version(Some(Uuid::nil()));
let saved_part = if let Some(d) = old_dir {
Some((
d,
tokio::fs::read(obj_dir.join(d.to_string()).join("part.1"))
.await
.expect("read V2 part.1"),
))
} else {
None
};
v2_metas.push((bytes, fm));
v2_parts.push(saved_part);
if idx >= 4 {
tokio::fs::write(obj_dir.join(STORAGE_FORMAT_FILE), &v1_metas[idx])
.await
.expect("keep drives 4..6 on V1");
}
}
// 3. V3 attempts an overwrite, publishes only on drives 2..4 (< write_quorum = 4) with
// preserved `<rollback_dir>/xl.meta.bkp` of V2, while drives 0..2 stay on V2 and
// drives 4..6 stay on V1 (exact 2-2-2 split!).
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
set.put_object(&bucket, object, &mut PutObjReader::from_vec(v3.clone()), &opts)
.await
.expect("stage V3");
set.invalidate_get_object_metadata_cache(&bucket, object).await;
for idx in 0..2 {
let obj_dir = dirs[idx].path().join(&bucket).join(object);
tokio::fs::write(obj_dir.join(STORAGE_FORMAT_FILE), &v2_metas[idx].0)
.await
.expect("restore V2 on drives 0..2");
if let Some((d, part_bytes)) = &v2_parts[idx] {
let d_path = obj_dir.join(d.to_string());
tokio::fs::create_dir_all(&d_path).await.expect("recreate V2 data dir");
tokio::fs::write(d_path.join("part.1"), part_bytes)
.await
.expect("restore V2 part.1 on drives 0..2");
}
}
for idx in 4..6 {
let obj_dir = dirs[idx].path().join(&bucket).join(object);
tokio::fs::write(obj_dir.join(STORAGE_FORMAT_FILE), &v1_metas[idx])
.await
.expect("restore V1 on drives 4..6");
}
let mut backup_paths = Vec::new();
for idx in 2..4 {
let obj_dir = dirs[idx].path().join(&bucket).join(object);
let rollback_dir = v2_metas[idx]
.1
.find_unshared_data_dir_for_version(Some(Uuid::nil()))
.unwrap_or_else(|| crate::disk::local::inline_metadata_rollback_dir(Uuid::nil(), &v2_metas[idx].1));
let r_path = obj_dir.join(rollback_dir.to_string());
tokio::fs::create_dir_all(&r_path).await.expect("create rollback dir");
if let Some((_, part_bytes)) = &v2_parts[idx] {
tokio::fs::write(r_path.join("part.1"), part_bytes)
.await
.expect("preserve V2 part.1 prior to post-quorum cleanup");
}
let bkp_path = r_path.join(crate::disk::STORAGE_FORMAT_FILE_BACKUP);
tokio::fs::write(&bkp_path, &v2_metas[idx].0)
.await
.expect("preserve V2 xl.meta.bkp");
backup_paths.push(bkp_path);
}
// Negative safety gate: if a drive is offline (incomplete set visibility), read must NOT
// roll back V3 because V3 could have committed on the offline drives.
{
let saved = set.disks.write().await[5].take();
let res = set
.get_object_info(
&bucket,
object,
&ObjectOptions {
suppress_read_repair: true,
..opts.clone()
},
)
.await;
set.disks.write().await[5] = saved;
assert!(
matches!(res, Err(StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(..))),
"{label}: offline set must fail closed with read quorum error, got {res:?}"
);
}
// Positive read gate (before heal runs): GET and HEAD serve committed V2 immediately.
let info = set
.get_object_info(
&bucket,
object,
&ObjectOptions {
suppress_read_repair: true,
..opts.clone()
},
)
.await
.expect("HEAD must resolve past uncommitted V3 to V2");
assert_eq!(info.size as usize, v2.len(), "{label}: HEAD size");
let mut reader = set
.get_object_reader(
&bucket,
object,
None,
Default::default(),
&ObjectOptions {
suppress_read_repair: true,
..opts.clone()
},
)
.await
.expect("GET must resolve past uncommitted V3 to V2");
let mut body = Vec::new();
reader.stream.read_to_end(&mut body).await.expect("read V2 body");
assert_eq!(body, v2, "{label}: GET body before heal");
// Positive heal gate: heal rolls back V3 on drives 2..4, repairs drives 4..6 to V2,
// and consumes all preserved `xl.meta.bkp` files.
let (_, heal_err) = set
.heal_object(
&bucket,
object,
"",
&HealOpts {
no_lock: true,
scan_mode: HealScanMode::Normal,
..Default::default()
},
)
.await
.expect("heal split set");
assert!(heal_err.is_none(), "{label}: heal error {heal_err:?}");
for bkp in &backup_paths {
assert!(!bkp.exists(), "{label}: heal must consume rollback backup {bkp:?}");
}
let mut post_reader = set
.get_object_reader(&bucket, object, None, Default::default(), &opts)
.await
.expect("GET after heal");
let mut post_body = Vec::new();
post_reader.stream.read_to_end(&mut post_body).await.expect("post-heal body");
assert_eq!(post_body, v2, "{label}: GET body after heal");
}
}
}
+27 -3
View File
@@ -447,19 +447,21 @@ impl SetDisks {
let mut reconnects = stream::iter(disks.into_iter().enumerate())
.map(|(i, opdisk)| async move {
if let Some(disk) = opdisk {
if !active_monitoring
let local_retired = disk.local_retirement_token().is_some_and(|token| token.is_cancelled());
if !local_retired
&& !active_monitoring
&& disk.get_disk_location().set_idx.is_some()
&& let disk::Disk::Local(local) = disk.as_ref()
&& local.can_skip_background_probe().await
{
return None;
}
if disk.is_online().await && disk.get_disk_location().set_idx.is_some() {
if !local_retired && disk.is_online().await && disk.get_disk_location().set_idx.is_some() {
return None;
}
// A failed remote reconnect must retain its existing recovery monitor.
if disk.is_local() {
if disk.is_local() && !local_retired {
let _ = disk.close().await;
}
}
@@ -1315,6 +1317,28 @@ mod tests {
assert!(Arc::ptr_eq(&registered, renewed_again));
assert!(!current.retirement_token().is_cancelled());
// Simulate a transient drive fault where a failed reconnect attempt
// retired the attached local wrapper before the underlying directory
// became accessible again and runtime health returned to Online.
renewed_again.close().await.expect("retire attached local wrapper");
assert!(current.retirement_token().is_cancelled());
assert!(renewed_again.is_online().await);
set_disks.connect_disks_with_active_monitoring(false).await;
let disks_after_recover = set_disks.get_disks_internal().await;
let recovered = disks_after_recover[0]
.as_ref()
.expect("connect_disks must replace a retired local wrapper once accessible");
assert!(!Arc::ptr_eq(recovered, renewed_again));
let disk::Disk::Local(recovered_local) = recovered.as_ref() else {
panic!("recovered slot must remain local");
};
assert!(!recovered_local.retirement_token().is_cancelled());
recovered_local
.check_scanner_handle()
.expect("recovered local wrapper must be usable by the data scanner");
drop(temp_dirs);
}
+48 -119
View File
@@ -3640,13 +3640,6 @@ impl crate::storage_api_contracts::object::ObjectIO for SetDisks {
let (producer_terminal_tx, producer_terminal_rx) = tokio::sync::oneshot::channel();
let (mut reader, offset, length) =
get_legacy_object_reader_with_context(&self.ctx, rd, producer_terminal_rx, range, &object_info, opts, &h).await?;
if let Some(max_bytes) = caller_sink.as_ref().and_then(crate::object_api::GetObjectSink::max_bytes)
&& u64::try_from(length).is_ok_and(|needed| needed > max_bytes)
{
return Err(StorageError::InvalidRangeSpec(format!(
"rdma token buffer ({max_bytes} bytes) is smaller than the response ({length} bytes)"
)));
}
// Carry the hook probe result so the app layer skips its now-redundant
// lookup on the streaming miss path (ODC-16).
reader.body_source = body_source;
@@ -4011,108 +4004,6 @@ mod sink_segment_plan_tests {
}
}
#[cfg(test)]
mod get_object_sink_bounds_tests {
use super::hermetic_set_disks_support::hermetic_set_disks_isolated;
use super::*;
#[tokio::test]
async fn undersized_get_object_sink_rejects_before_taking_sink_or_writing_bytes() {
#[derive(Clone, Default)]
struct RecordingSink(Arc<std::sync::Mutex<Vec<u8>>>);
impl tokio::io::AsyncWrite for RecordingSink {
fn poll_write(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
buf: &[u8],
) -> std::task::Poll<std::io::Result<usize>> {
self.0.lock().expect("sink buffer lock").extend_from_slice(buf);
std::task::Poll::Ready(Ok(buf.len()))
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
fn poll_shutdown(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<std::io::Result<()>> {
std::task::Poll::Ready(Ok(()))
}
}
let (_dirs, disks, set_disks) = hermetic_set_disks_isolated(4).await;
let bucket = "sink-max-bytes-check";
let object = "large-plain.bin";
for disk in &disks {
disk.make_volume(bucket).await.expect("create fixture bucket");
}
let payload = b"rustfs-rdma-sink-bounds-".repeat(40_000);
let mut upload = PutObjReader::from_vec(payload.clone());
set_disks
.put_object(
bucket,
object,
&mut upload,
&ObjectOptions {
write_completion: crate::object_api::WriteCompletion::TailDrained,
..Default::default()
},
)
.await
.expect("upload fixture object");
let recorded = RecordingSink::default();
let undersized_sink = crate::object_api::GetObjectSink::new(GetObjectSinkWriter::new(Box::new(recorded.clone())))
.with_max_bytes((payload.len() - 1) as u64);
let opts = ObjectOptions {
no_lock: true,
get_object_sink: Some(undersized_sink.clone()),
..Default::default()
};
let error = match set_disks
.get_object_reader(bucket, object, None, HeaderMap::new(), &opts)
.await
{
Err(error) => error,
Ok(_) => panic!("undersized sink must be rejected before opening reader"),
};
assert!(
matches!(error, StorageError::InvalidRangeSpec(_)),
"expected InvalidRangeSpec, got {error:?}"
);
assert!(!undersized_sink.is_taken(), "undersized sink must not be taken");
assert!(recorded.0.lock().expect("sink buffer lock").is_empty(), "no bytes may be written");
let exact_recorded = RecordingSink::default();
let fitting_sink = crate::object_api::GetObjectSink::new(GetObjectSinkWriter::new(Box::new(exact_recorded.clone())))
.with_max_bytes(payload.len() as u64);
let fit_opts = ObjectOptions {
no_lock: true,
get_object_sink: Some(fitting_sink.clone()),
..Default::default()
};
let mut reader = set_disks
.get_object_reader(bucket, object, None, HeaderMap::new(), &fit_opts)
.await
.expect("fitting sink must open reader");
assert!(fitting_sink.is_taken(), "fitting sink must be taken by producer");
let mut pipe_drain = Vec::new();
reader
.stream
.read_to_end(&mut pipe_drain)
.await
.expect("wait for producer completion");
assert!(pipe_drain.is_empty(), "pipe carries only completion when sink is used");
assert_eq!(*exact_recorded.0.lock().expect("sink buffer lock"), payload);
}
}
#[cfg(test)]
mod legacy_producer_stack_tests {
use super::*;
@@ -11166,9 +11057,11 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
// needs below. These reads are pure quorum lookups under the locks
// already held; sequencing one metadata fan-out per key made a
// 1000-key batch pay a full round of drive reads at a time.
const DELETE_OBJECTS_SOURCE_READ_CONCURRENCY: usize = 16;
let mut source_reads: HashMap<usize, (ObjectInfo, FileInfo, Option<Error>)> =
const DELETE_OBJECTS_SOURCE_READ_CONCURRENCY: usize = 64;
let mut source_reads: HashMap<usize, (ObjectInfo, FileInfo, Option<Error>, bool)> =
HashMap::with_capacity(DELETE_OBJECTS_SOURCE_READ_CONCURRENCY);
let recovery_prefetch_allowed =
!is_meta_bucketname(bucket) && !opts.data_movement && !opts.replication_request && opts.http_preconditions.is_none();
let mut vers_map: HashMap<&String, FileInfoVersions> = HashMap::new();
let mut tier_reference_leases: Vec<(usize, String, Option<TierDestinationId>)> = Vec::new();
let mut tier_free_version_receipt_candidates: HashMap<usize, TierFreeVersionReceiptCandidate> = HashMap::new();
@@ -11179,6 +11072,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
for (i, dobj) in objects.iter().enumerate() {
if i.is_multiple_of(DELETE_OBJECTS_SOURCE_READ_CONCURRENCY) {
source_reads.clear();
let recovery_work_budget = opts.delete_recovery_work_budget.as_deref();
let mut pending = Vec::new();
for (i, source) in source_inputs
.iter()
@@ -11195,13 +11089,28 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
if !source.needs_source_read {
continue;
}
let guarded_prefetch =
current_generations.is_some_and(|generations| generations.contains_key(&objects[i].object_name));
let can_check_empty_recovery = recovery_prefetch_allowed
&& !guarded_prefetch
&& transaction_guards
.get(lock_names[i].as_ref())
.is_some_and(|guard| !guard.is_lock_lost());
let object_name = objects[i].object_name.clone();
let check_opts = &source.check_opts;
pending.push(async move {
let (goi, file_info, _write_quorum, gerr) = self
.get_object_info_fileinfo_and_quorum(bucket, &object_name, check_opts)
.await;
(i, (goi, file_info, gerr))
let confirmed_no_recovery = can_check_empty_recovery
&& goi.name.is_empty()
&& gerr
.as_ref()
.is_some_and(|error| is_err_object_not_found(error) || is_err_version_not_found(error))
&& self
.has_no_pending_delete_recovery_transactions(bucket, &object_name, recovery_work_budget)
.await;
(i, (goi, file_info, gerr, confirmed_no_recovery))
});
}
let reads = futures::stream::iter(pending)
@@ -11237,25 +11146,26 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
replicate_delete,
needs_source_read,
} = source;
let (mut goi, mut authoritative_file_info, mut gerr) = if needs_source_read {
let (mut goi, mut authoritative_file_info, mut gerr, confirmed_no_recovery) = if needs_source_read {
match source_reads.remove(&i) {
Some(read) => read,
None => {
let (goi, file_info, _write_quorum, gerr) = self
.get_object_info_fileinfo_and_quorum(bucket, &dobj.object_name, &check_opts)
.await;
(goi, file_info, gerr)
(goi, file_info, gerr, false)
}
}
} else {
(ObjectInfo::default(), FileInfo::default(), None)
(ObjectInfo::default(), FileInfo::default(), None, false)
};
// A quorum-resolved marker returns not-found with a populated name.
// Only missing metadata needs recovery; unrelated legacy residue or
// an offline disk must not block a new marker write at quorum.
if gerr
.as_ref()
.is_some_and(|error| is_err_object_not_found(error) || is_err_version_not_found(error))
if !confirmed_no_recovery
&& gerr
.as_ref()
.is_some_and(|error| is_err_object_not_found(error) || is_err_version_not_found(error))
&& !is_meta_bucketname(bucket)
&& !opts.data_movement
&& !opts.replication_request
@@ -11574,15 +11484,26 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
}
let mut vers = Vec::with_capacity(vers_map.len());
let mut coalesced_delete_marker_aliases: Vec<(usize, usize)> = Vec::new();
for (_, mut fi_vers) in vers_map {
fi_vers.versions.sort_by_key(|a| a.deleted);
fi_vers.versions.retain(|fi| del_errs[fi.idx].is_none());
if let Some(index) = fi_vers.versions.iter().position(|fi| fi.deleted) {
let canonical_idx = fi_vers.versions[index].idx;
for dup in &fi_vers.versions[(index + 1)..] {
if dup.deleted {
del_objects[dup.idx] = del_objects[canonical_idx].clone();
coalesced_delete_marker_aliases.push((dup.idx, canonical_idx));
}
}
fi_vers.versions.truncate(index + 1);
}
vers.push(fi_vers);
if !fi_vers.versions.is_empty() {
vers.push(fi_vers);
}
}
let rollback_dir = Uuid::new_v4();
@@ -11859,6 +11780,9 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
};
group_results.push((true, error));
}
for &(dup_idx, canonical_idx) in &coalesced_delete_marker_aliases {
group_by_object[dup_idx] = group_by_object[canonical_idx];
}
for obj_idx in 0..objects.len() {
let mut has_err = match group_by_object[obj_idx] {
@@ -11986,6 +11910,11 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
}
}
}
for &(dup_idx, canonical_idx) in &coalesced_delete_marker_aliases {
if del_errs[dup_idx].is_none() && del_errs[canonical_idx].is_some() {
del_errs[dup_idx] = del_errs[canonical_idx].clone();
}
}
receipt_summary.log(self.pool_index, self.set_index, None);
}
let mut rollback_futures = Vec::new();
+143 -24
View File
@@ -1113,10 +1113,26 @@ impl SetDisks {
};
let (read_quorum, write_quorum) = match Self::object_quorum_from_meta(&parts_metadata, &errs, self.default_parity_count)
.map_err(|err| dangling_not_found(&err).unwrap_or(err))
.map_err(|err| to_object_err(err.into(), vec![bucket, object, &vid]))
{
Ok(v) => v,
Err(e) => {
Err(raw_err) => {
if raw_err == DiskError::ErasureReadQuorum
&& vid.is_empty()
&& dangling_read != DanglingRead::KeepQuorumError
&& metadata_fanout_complete
&& !crate::bucket::utils::is_meta_bucketname(bucket)
&& let Some(snapshot) =
Box::pin(self.read_latest_past_dangling_versions(bucket, object, opts, read_data, purpose, &disks)).await
{
rustfs_io_metrics::record_get_object_metadata_quorum_result(metadata_metrics_path, "reached");
record_get_stage_duration_if_enabled(
GET_OBJECT_PATH_SET_DISK,
GET_STAGE_METADATA_RESOLVE,
metadata_resolve_stage_start,
);
return Ok(snapshot);
}
let e = to_object_err(raw_err.into(), vec![bucket, object, &vid]);
rustfs_io_metrics::record_get_object_metadata_quorum_result(metadata_metrics_path, metadata_quorum_outcome(&e));
// error!("Self::object_quorum_from_meta: {:?}, bucket: {}, object: {}", &e, bucket, object);
record_get_stage_duration_if_enabled(
@@ -1192,14 +1208,30 @@ impl SetDisks {
&& late_materialization_candidate_is_safe(&fi);
let mut snapshot = if !opts.suppress_read_repair && errs.iter().any(|err| err.is_some()) {
let version_id = resolved_read_repair_version_id(&fi, opts.version_id.as_deref());
submit_read_repair_heal(
&fi.volume,
&fi.name,
version_id.as_deref(),
self.pool_index,
self.set_index,
None,
"metadata_read_error",
let has_metadata_corruption = errs.iter().any(|err| {
matches!(
err,
Some(
DiskError::FileCorrupt
| DiskError::CorruptedFormat
| DiskError::CorruptedBackend
| DiskError::OutdatedXLMeta
)
)
});
submit_read_repair_heal_with_submitter(
ReadRepairHealSubmission {
bucket: &fi.volume,
object: &fi.name,
version_id: version_id.as_deref(),
pool_index: self.pool_index,
set_index: self.set_index,
part_number: None,
reason: "metadata_read_error",
mrf_intent: has_metadata_corruption
.then_some((rustfs_common::mrf_channel::MrfKind::MetadataCorruption, None)),
},
send_read_repair_heal_request,
)
.await;
let mut snapshot = GetObjectFileInfo::owned(fi, parts_metadata, op_online_disks);
@@ -1344,6 +1376,7 @@ impl SetDisks {
let mut best: Option<(Option<time::OffsetDateTime>, GetObjectFileInfo)> = None;
let mut skipped = Vec::new();
let mut recovered_null_overwrite = false;
let mut settled = false;
for (reads, (version_id, newest_mod_time)) in candidates.into_iter().enumerate() {
if best.as_ref().is_some_and(|(selected, _)| newest_mod_time < *selected) {
@@ -1359,7 +1392,7 @@ impl SetDisks {
version_id: Some(version_id.clone()),
..opts.clone()
};
match Box::pin(self.get_object_fileinfo_gated_inner(
let resolved_snapshot = match Box::pin(self.get_object_fileinfo_gated_inner(
bucket,
object,
&exact,
@@ -1370,21 +1403,41 @@ impl SetDisks {
))
.await
{
Ok(snapshot) => {
let selected = snapshot.fi().mod_time;
let replace = match best.as_ref() {
Some((current, previous)) if selected == *current => {
selected_header(&snapshot)?.sorts_before(&selected_header(previous)?)
}
Some((current, _)) => selected > *current,
None => true,
};
if replace {
best = Some((selected, snapshot));
}
Ok(snapshot) => Some((snapshot, true)),
Err(StorageError::VersionNotFound(..)) => {
skipped.push(version_id);
None
}
Err(StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(..))
if version_id == uuid::Uuid::nil().to_string() =>
{
let snapshot = self
.read_null_version_past_incomplete_overwrites(bucket, object, &exact, read_data, disks)
.await?;
recovered_null_overwrite = true;
Some((snapshot, false))
}
Err(StorageError::VersionNotFound(..)) => skipped.push(version_id),
Err(_) => return None,
};
if let Some((snapshot, require_live_header)) = resolved_snapshot {
let selected = snapshot.fi().mod_time;
let replace = match best.as_ref() {
Some((current, previous)) if selected == *current => {
if require_live_header {
selected_header(&snapshot)?.sorts_before(&selected_header(previous)?)
} else {
match (selected_header(&snapshot), selected_header(previous)) {
(Some(left), Some(right)) => left.sorts_before(&right),
_ => false,
}
}
}
Some((current, _)) => selected > *current,
None => true,
};
if replace {
best = Some((selected, snapshot));
}
}
}
// Headers past each drive's first few were not compared; only a walk
@@ -1407,10 +1460,76 @@ impl SetDisks {
)
.await;
}
if recovered_null_overwrite {
submit_read_repair_heal(
bucket,
object,
None,
self.pool_index,
self.set_index,
None,
"incomplete_overwrite_rollback",
)
.await;
}
}
Some(snapshot)
}
async fn read_null_version_past_incomplete_overwrites(
&self,
bucket: &str,
object: &str,
opts: &ObjectOptions,
read_data: bool,
disks: &[Option<DiskStore>],
) -> Option<GetObjectFileInfo> {
let metadata_read = Self::read_metadata_observed(
disks,
"",
bucket,
object,
"",
read_data,
false,
opts.incl_free_versions,
false,
self.default_parity_count,
)
.await
.ok()?;
if !metadata_read.is_complete() {
return None;
}
let (parts_metadata, errs, _) = metadata_read.into_legacy();
let include_part_checksums =
opts.include_part_checksums || opts.part_number.is_some() || opts.data_movement || opts.raw_data_movement_read;
let mut resolution = self
.discover_incomplete_overwrite_rollbacks(
disks,
bucket,
object,
"",
&parts_metadata,
&errs,
read_data,
include_part_checksums,
)
.await?;
if include_part_checksums {
Self::hydrate_selected_fileinfo_part_checksums(&mut resolution.fi).ok()?;
} else {
for metadata in std::iter::once(&mut resolution.fi).chain(resolution.parts_metadata.iter_mut()) {
rustfs_utils::http::remove_str(&mut metadata.metadata, rustfs_utils::http::SUFFIX_PART_CHECKSUMS);
}
}
Some(GetObjectFileInfo::owned(
resolution.fi,
resolution.parts_metadata,
resolution.online_disks,
))
}
#[hotpath::measure(impl_type = "SetDisks")]
pub(super) async fn get_object_info_fileinfo_and_quorum(
&self,
+18
View File
@@ -850,6 +850,24 @@ impl ECStore {
.await
}
/// Return online formatted drive counts for every live `(pool_idx, set_idx)` in the cluster.
pub async fn online_drive_counts_by_set(&self) -> Vec<((u32, u32), usize)> {
let mut counts = Vec::new();
for pool in &self.pools {
let Ok(pool_idx) = u32::try_from(pool.pool_idx) else {
continue;
};
for set in &pool.disk_set {
let Ok(set_idx) = u32::try_from(set.set_index) else {
continue;
};
let (disks, _) = set.get_online_disks_with_healing(false).await;
counts.push(((pool_idx, set_idx), disks.len()));
}
}
counts
}
/// Return every live erasure set selected by an object-heal scope.
pub async fn heal_erasure_set_scopes(&self, opts: &HealOpts) -> Result<Vec<(usize, usize)>> {
let pools = self.get_pools_for_heal_object(opts)?;
+20 -5
View File
@@ -439,14 +439,22 @@ async fn resume_rebalance_after_init(store: Arc<ECStore>, rx: CancellationToken)
match store.start_rebalance().await {
Ok(()) => return,
Err(err) if crate::core::pools::is_pool_activation_fleet_proof_error(&err) => {
Err(err)
if crate::core::pools::is_pool_activation_fleet_proof_error(&err)
|| crate::services::rebalance::is_transient_rebalance_error(&err) =>
{
let reason = if crate::core::pools::is_pool_activation_fleet_proof_error(&err) {
"fleet_capability_proof_unavailable"
} else {
"transient_rebalance_error"
};
warn!(
event = EVENT_ECSTORE_INIT_STATUS,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_STORE_INIT,
stage = "start_rebalance",
state = "retrying",
reason = "fleet_capability_proof_unavailable",
reason = reason,
error = %err,
retry_delay_secs = REBALANCE_RESUME_RETRY_DELAY.as_secs(),
"Retrying deferred rebalance auto-start"
@@ -1085,7 +1093,14 @@ impl ECStore {
"Deferred rebalance auto-start until a live fleet capability proof is available"
);
} else if let Err(err) = self.start_rebalance().await {
if crate::core::pools::is_pool_activation_fleet_proof_error(&err) {
if crate::core::pools::is_pool_activation_fleet_proof_error(&err)
|| crate::services::rebalance::is_transient_rebalance_error(&err)
{
let reason = if crate::core::pools::is_pool_activation_fleet_proof_error(&err) {
"fleet_capability_proof_changed"
} else {
"transient_rebalance_error"
};
rebalance_auto_start_deferred = true;
warn!(
event = EVENT_ECSTORE_INIT_STATUS,
@@ -1093,10 +1108,10 @@ impl ECStore {
subsystem = LOG_SUBSYSTEM_STORE_INIT,
stage = "start_rebalance",
state = "deferred",
reason = "fleet_capability_proof_changed",
reason = reason,
error = %err,
retry_delay_secs = REBALANCE_RESUME_RETRY_DELAY.as_secs(),
"Deferred rebalance auto-start after the fleet capability proof changed"
"Deferred rebalance auto-start after transient startup failure"
);
} else {
return resolve_store_init_stage_result(Err(err), "start_rebalance");
+40 -33
View File
@@ -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,
@@ -6914,25 +6907,39 @@ impl ECStore {
if !has_conditions {
// Keys whose write lock failed are already reported in `del_errs`;
// the phase only runs for the keys this batch actually holds, and
// only its outcomes replace the outer per-key state.
let indices = (0..objects.len()).filter(|idx| del_errs[*idx].is_none()).collect::<Vec<_>>();
let (mut phase_deleted, mut phase_errors, mut phase_accounting) = self
.run_batch_delete_phase(
bucket,
&objects,
&opts,
BatchDeletePhasePlan {
indices: &indices,
pool_generations,
marker_targets: &conditional_marker_targets,
},
)
.await;
for idx in indices {
del_objects[idx] = std::mem::take(&mut phase_deleted[idx]);
del_errs[idx] = phase_errors[idx].take();
accounting[idx] = phase_accounting[idx].take();
// deduplicate identical `(object_name, version_id)` actions so a batch
// with duplicate versionless keys creates one persisted delete marker
// and echoes that exact marker VersionId across all duplicate rows.
let mut unconditional_actions = HashMap::with_capacity(objects.len());
let mut indices = Vec::with_capacity(objects.len());
for (idx, object) in objects.iter().enumerate() {
if del_errs[idx].is_some() {
continue;
}
let representative = *unconditional_actions.entry(batch_delete_action_key(object)).or_insert(idx);
representatives[idx] = representative;
if representative == idx {
indices.push(idx);
}
}
if !indices.is_empty() {
let (mut phase_deleted, mut phase_errors, mut phase_accounting) = self
.run_batch_delete_phase(
bucket,
&objects,
&opts,
BatchDeletePhasePlan {
indices: &indices,
pool_generations,
marker_targets: &conditional_marker_targets,
},
)
.await;
for idx in indices {
del_objects[idx] = std::mem::take(&mut phase_deleted[idx]);
del_errs[idx] = phase_errors[idx].take();
accounting[idx] = phase_accounting[idx].take();
}
}
} else {
let mut conditional_actions = HashMap::with_capacity(objects.len());
@@ -7013,14 +7020,14 @@ impl ECStore {
}
}
if has_conditions {
for (idx, representative) in representatives.into_iter().enumerate() {
if representative != idx {
del_objects[idx] = del_objects[representative].clone();
del_errs[idx] = del_errs[representative].clone();
accounting[idx] = None;
}
for (idx, representative) in representatives.into_iter().enumerate() {
if representative != idx {
del_objects[idx] = del_objects[representative].clone();
del_errs[idx] = del_errs[representative].clone();
accounting[idx] = None;
}
}
if has_conditions {
let mut first_successes = HashMap::with_capacity(objects.len());
for (idx, object) in objects.iter().enumerate() {
if del_errs[idx].is_none() {
+1 -1
View File
@@ -878,7 +878,7 @@ impl ECStore {
/// Observe every pool for a conditional-write preflight. This does not
/// hold the namespace locks needed to prove a condition at publication.
pub(super) async fn get_latest_object_info_for_conditional_write(
pub(crate) async fn get_latest_object_info_for_conditional_write(
&self,
bucket: &str,
object: &str,
+10 -1
View File
@@ -885,7 +885,12 @@ fn retry_budget_for_result(task: &HealTask, result: &Result<()>, retryable_batch
tokio::time::Instant::now().checked_add(delay)?;
return Some((delay, err.to_string()));
}
if task.retry_attempts >= MAX_RECOVERABLE_HEAL_RETRIES {
let max_retries = if err.is_slow_down() {
12
} else {
MAX_RECOVERABLE_HEAL_RETRIES
};
if task.retry_attempts >= max_retries {
return None;
}
// Admin traversals already exhaust their per-object retries. Restarting
@@ -2211,6 +2216,10 @@ impl HealManager {
self.submit_heal_request_with_receipt_and_alias(request, false).await
}
pub(crate) async fn online_drive_counts_by_set(&self) -> Vec<((u32, u32), usize)> {
self.storage.online_drive_counts_by_set().await
}
pub(crate) async fn submit_heal_request_with_receipt_and_alias(
&self,
request: HealRequest,
+16
View File
@@ -2389,6 +2389,7 @@ async fn run_mrf_consumer_with_stop(
flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut batch: Vec<MrfIntent> = Vec::with_capacity(runtime.config.replay_batch);
let mut durable_batch = Vec::with_capacity(runtime.config.replay_batch);
let mut observed_online_drives: HashMap<(u32, u32), usize> = HashMap::new();
loop {
if stop.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
@@ -2505,6 +2506,21 @@ async fn run_mrf_consumer_with_stop(
}
}
_ = flush_tick.tick() => {
if runtime.partial_writes.depth() > 0 {
let mut recovered_scopes = HashSet::new();
for (scope, online_count) in manager.online_drive_counts_by_set().await {
if let Some(previous) = observed_online_drives.insert(scope, online_count)
&& online_count > previous
{
recovered_scopes.insert(scope);
}
}
runtime.partial_writes.wake_recovered_scopes(&recovered_scopes);
} else if !observed_online_drives.is_empty() {
for (scope, online_count) in manager.online_drive_counts_by_set().await {
observed_online_drives.insert(scope, online_count);
}
}
runtime.partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
runtime.discharge_durable_replay_anchors();
match tick_action(
@@ -783,6 +783,35 @@ impl PartialWrites {
Ok((entry.intent.clone(), previous))
}
/// Reset exponential retry backoff for active obligations in `(pool, set)`
/// (plus unscoped obligations) whenever an offline drive returns online.
pub(super) fn wake_recovered_scopes(&mut self, recovered_scopes: &HashSet<(u32, u32)>) -> bool {
if recovered_scopes.is_empty() {
return false;
}
let now = Instant::now();
let mut woke = false;
for (key, entry) in &mut self.entries {
if entry.is_parked() || entry.attempt_in_flight || !entry.persisted {
continue;
}
let scope_matches = entry
.intent
.scope
.is_none_or(|scope| recovered_scopes.contains(&(scope.pool_index, scope.set_index)));
if scope_matches && (entry.next_attempt > now || entry.consecutive_unverified_attempts > 0) {
entry.next_attempt = now;
entry.consecutive_unverified_attempts = 0;
if !entry.retry_queued && self.retry_index.insert(key.clone()) {
self.retry_order.push_back(key.clone());
entry.retry_queued = true;
}
woke = true;
}
}
woke
}
pub(super) fn restore_operator_state(
&mut self,
responsibility_id: Uuid,
+10
View File
@@ -738,6 +738,12 @@ pub trait HealStorageAPI: Send + Sync {
Ok(None)
}
/// Return online formatted drive counts per `(pool_index, set_index)` so
/// MRF backoff timers can wake immediately when an offline drive recovers.
async fn online_drive_counts_by_set(&self) -> Vec<((u32, u32), usize)> {
Vec::new()
}
/// List versions for healing via a per-erasure-set DISK-WALK union enumerator
/// (backlog#920). Unlike `list_objects_for_heal_page` (which reflects only the
/// READ-QUORUM metadata view via `list_object_versions`), this surfaces every
@@ -2189,6 +2195,10 @@ impl HealStorageAPI for ECStoreHealStorage {
.map_err(Error::Storage)
}
async fn online_drive_counts_by_set(&self) -> Vec<((u32, u32), usize)> {
self.live_ecstore().online_drive_counts_by_set().await
}
async fn list_versions_for_heal_page_disk_walk(
&self,
set_disk_id: &str,
+3
View File
@@ -946,6 +946,9 @@ impl HealTask {
}
pub(crate) fn should_log_failure(&self, error: &Error) -> bool {
if error.is_slow_down() && self.source == HealRequestSource::Scanner {
return false;
}
if !matches!(error, Error::Storage(crate::heal::StorageError::DeleteRecoveryLegacyAmbiguous)) {
return true;
}
+123 -273
View File
@@ -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";
@@ -112,6 +108,56 @@ impl GuardRegistryState {
self.next_expiry = next_expiry;
expired
}
fn extract_by_owner(&mut self, owner: &str) -> Vec<LocalGuardEntry> {
if self.entries.is_empty() {
return Vec::new();
}
let mut next_expiry: Option<Instant> = None;
let matching = self
.entries
.extract_if(|_, entry| {
if entry.guard.owner().as_ref().eq_ignore_ascii_case(owner) {
true
} else {
next_expiry = Some(next_expiry.map_or(entry.deadline, |deadline| deadline.min(entry.deadline)));
false
}
})
.map(|(_, entry)| entry)
.collect();
self.next_expiry = next_expiry;
matching
}
}
static LIVE_GUARD_STORAGES: std::sync::LazyLock<parking_lot::Mutex<Vec<std::sync::Weak<Vec<GuardShard>>>>> =
std::sync::LazyLock::new(|| parking_lot::Mutex::new(Vec::new()));
/// Reclaim all active local lock guards owned by `owner` across every live `LocalClient`
/// in this process (used when an internode peer proves a new `boot_epoch` after restart).
pub async fn reclaim_all_local_guards_for_owner(owner: &str) -> usize {
if owner.is_empty() {
return 0;
}
let storages: Vec<GuardStorage> = {
let mut list = LIVE_GUARD_STORAGES.lock();
let mut upgraded = Vec::with_capacity(list.len());
list.retain(|weak| {
if let Some(arc) = weak.upgrade() {
upgraded.push(arc);
true
} else {
false
}
});
upgraded
};
let mut total = 0usize;
for storage in storages {
total = total.saturating_add(LocalClient::reclaim_storage_guards_for_owner(&storage, owner).await);
}
total
}
/// Registry access never reserves the table for a task that has not resumed.
@@ -471,12 +517,17 @@ 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 {
let shard_count = guard_storage.len();
debug_assert!(shard_count.is_power_of_two());
{
let mut list = LIVE_GUARD_STORAGES.lock();
list.retain(|weak| weak.strong_count() > 0);
list.push(Arc::downgrade(&guard_storage));
}
Self {
guard_storage,
shard_mask: shard_count - 1,
@@ -491,6 +542,29 @@ impl LocalClient {
}
}
/// Reclaim all guards held by `owner` on this `LocalClient`.
pub async fn reclaim_guards_for_owner(&self, owner: &str) -> usize {
Self::reclaim_storage_guards_for_owner(&self.guard_storage, owner).await
}
async fn reclaim_storage_guards_for_owner(storage: &GuardStorage, owner: &str) -> usize {
let mut extracted = Vec::new();
for shard in storage.iter() {
let has_owner = shard
.read()
.await
.entries
.values()
.any(|entry| entry.guard.owner().as_ref().eq_ignore_ascii_case(owner));
if !has_owner {
continue;
}
let mut guards = shard.write().await;
extracted.extend(guards.extract_by_owner(owner));
}
Self::release_reclaimed_guards(extracted)
}
fn cache_fence_stamp_for_grant(
&self,
resource: &crate::ObjectKey,
@@ -522,7 +596,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 +639,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 +668,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 +679,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 +1050,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 +1157,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
@@ -1832,263 +1892,53 @@ mod tests {
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);
#[tokio::test]
async fn reclaim_all_local_guards_for_owner_evicts_only_restarted_peer_locks() {
let client = LocalClient::with_manager(Arc::new(GlobalLockManager::new()));
let restarted_owner = format!("restarted-peer-{}:9000", uuid::Uuid::new_v4());
let healthy_owner = format!("healthy-peer-{}:9000", uuid::Uuid::new_v4());
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);
let stale_write_key = crate::ObjectKey::new("bucket", "cross-pool-write");
let stale_write =
LockRequest::new(stale_write_key.clone(), LockType::Exclusive, &restarted_owner).with_ttl(Duration::from_secs(30));
assert!(client.acquire_lock(&stale_write).await.expect("stale write grant").success);
let healthy_write_key = crate::ObjectKey::new("bucket", "healthy-write");
let healthy_write =
LockRequest::new(healthy_write_key.clone(), LockType::Exclusive, &healthy_owner).with_ttl(Duration::from_secs(30));
assert!(
client
.acquire_lock(&read_req)
.acquire_lock(&healthy_write)
.await
.expect("acquire default-ttl shared lock")
.expect("healthy write grant")
.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"
);
let reclaimed = reclaim_all_local_guards_for_owner(&restarted_owner.to_ascii_uppercase()).await;
assert_eq!(reclaimed, 1, "expected exactly the restarted peer's guard to be reclaimed");
// 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"
);
let contender = LockRequest::new(stale_write_key, LockType::Exclusive, &healthy_owner)
.with_acquire_timeout(Duration::from_millis(50));
assert!(
client
.check_status(&read_req.lock_id)
.acquire_lock(&contender)
.await
.expect("check reaped read lock status")
.is_none()
.expect("contender after reclaim")
.success,
"reclaimed cross-pool write lock must immediately admit new writers"
);
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);
}
assert!(client.release(&contender.lock_id).await.expect("release contender"));
#[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);
let blocked_healthy = LockRequest::new(healthy_write_key, LockType::Exclusive, "other-peer:9000")
.with_acquire_timeout(Duration::from_millis(20));
assert!(
client
.acquire_lock(&read_req)
!client
.acquire_lock(&blocked_healthy)
.await
.expect("acquire default-ttl bucket read lock")
.success
.expect("healthy lock check")
.success,
"unrelated peer guards must remain intact"
);
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);
assert!(client.release(&healthy_write.lock_id).await.expect("release healthy write"));
}
}
+4 -1
View File
@@ -38,7 +38,10 @@ pub mod types;
// Re-export main types for easy access
pub use crate::{
// Client interfaces
client::{BatchAcquireOutcome, LockCleanupOutcome, LockClient, local::LocalClient},
client::{
BatchAcquireOutcome, LockCleanupOutcome, LockClient,
local::{LocalClient, reclaim_all_local_guards_for_owner},
},
distributed_lock::DistributedLockGuard,
// Error types
error::{LockError, Result},
+16 -9
View File
@@ -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.
+16 -9
View File
@@ -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` 缓存:
+45 -154
View File
@@ -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, &current).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(&current), || 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());
+52 -168
View File
@@ -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();
+38 -19
View File
@@ -523,9 +523,21 @@ pub fn assign_site_replication_rule_priorities(
}
}
fn is_iam_role_arn(role: &str) -> bool {
let trimmed = role.trim();
trimmed
.strip_prefix("arn:")
.and_then(|rest| rest.split_once(':'))
.is_some_and(|(_, service_and_rest)| service_and_rest.starts_with("iam:"))
}
pub fn legacy_role_target_arn(role: &str) -> Option<&str> {
let trimmed = role.trim();
(!trimmed.is_empty() && !is_iam_role_arn(trimmed)).then_some(trimmed)
}
pub fn replication_target_arns(config: &PersistedReplicationConfiguration) -> HashSet<String> {
let role = config.role.trim();
if !role.is_empty() {
if let Some(role) = legacy_role_target_arn(&config.role) {
return HashSet::from([role.to_string()]);
}
@@ -538,9 +550,8 @@ pub fn validate_replication_config_target_arns<'a>(
) -> std::result::Result<(), ReplicationTargetValidationError> {
let configured_arns = configured_arns.into_iter().collect::<HashSet<_>>();
let role = config.role.trim();
let destination_arns = active_replication_rule_destination_arns(config);
if !role.is_empty() && destination_arns.len() > 1 {
if legacy_role_target_arn(&config.role).is_some() && destination_arns.len() > 1 {
return Err(ReplicationTargetValidationError::RoleWithMultipleDestinations);
}
@@ -690,7 +701,7 @@ fn actionable_rules_refs<'a>(
}
let target_arn = obj.target_arn.trim();
let role_arn = config.role.trim();
let role_arn = legacy_role_target_arn(&config.role);
let mut rules = Vec::with_capacity(config.rules.len());
let mut decoded_tags: Option<HashMap<String, String>> = None;
@@ -699,7 +710,7 @@ fn actionable_rules_refs<'a>(
continue;
}
if !obj.target_arn.is_empty() && rule.destination.bucket.trim() != target_arn && role_arn != target_arn {
if !obj.target_arn.is_empty() && rule.destination.bucket.trim() != target_arn && role_arn != Some(target_arn) {
continue;
}
@@ -739,9 +750,10 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
fn has_existing_object_replication(&self, arn: &str) -> (bool, bool) {
let mut has_arn = false;
let arn = arn.trim();
let role_arn = legacy_role_target_arn(&self.role);
for rule in &self.rules {
if rule.destination.bucket.trim() == arn || self.role.trim() == arn {
if rule.destination.bucket.trim() == arn || role_arn == Some(arn) {
if !has_arn {
has_arn = true;
}
@@ -817,8 +829,7 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
/// Filter target ARNs and return a slice of the distinct values in the config
fn configured_target_arns(&self) -> HashSet<String> {
let role = self.role.trim();
if !role.is_empty() {
if let Some(role) = legacy_role_target_arn(&self.role) {
return HashSet::from([role.to_string()]);
}
self.rules
@@ -830,8 +841,7 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
}
fn filter_target_arns(&self, obj: &ObjectOpts) -> Vec<String> {
let role = self.role.trim();
if !role.is_empty() {
if let Some(role) = legacy_role_target_arn(&self.role) {
return vec![role.to_string()];
}
@@ -852,7 +862,7 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
}
fn filter_force_delete_target_arns(&self, prefix: &str) -> Vec<String> {
let role = self.role.trim();
let role = legacy_role_target_arn(&self.role);
let mut selected = BTreeMap::<String, (&PersistedReplicationRule, bool)>::new();
for rule in &self.rules {
@@ -865,11 +875,7 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
continue;
}
let target = if role.is_empty() {
rule.destination.bucket.trim()
} else {
role
};
let target = role.unwrap_or_else(|| rule.destination.bucket.trim());
if target.is_empty() {
continue;
}
@@ -899,8 +905,7 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
fn filter_target_replication_decisions(&self, obj: &ObjectOpts) -> Vec<(String, bool)> {
let rules = self.filter_actionable_rules(obj);
let role = self.role.trim();
if !role.is_empty() {
if let Some(role) = legacy_role_target_arn(&self.role) {
let mut selected = None;
for rule in &rules {
if selected.is_none_or(|current: &PersistedReplicationRule| rule.priority > current.priority) {
@@ -1430,6 +1435,20 @@ mod tests {
.expect("disabled rules should not require live targets");
}
#[test]
fn validate_replication_config_target_arns_ignores_aws_iam_role_arn() {
let arn_a = "arn:rustfs:replication:us-east-1:target-a:bucket";
let arn_b = "arn:rustfs:replication:us-east-1:target-b:bucket";
let config = PersistedReplicationConfiguration {
role: "arn:aws:iam::123456789012:role/s3-replication".to_string(),
rules: vec![replication_rule("rule-a", arn_a), replication_rule("rule-b", arn_b)],
};
validate_replication_config_target_arns([arn_a, arn_b], &config)
.expect("AWS IAM role ARN should delegate target resolution to rule destination ARNs");
assert_eq!(replication_target_arns(&config), HashSet::from([arn_a.to_string(), arn_b.to_string()]));
}
#[test]
fn should_remove_replication_target_only_matches_replication_target_arns() {
let target_arns = HashSet::from(["arn:rustfs:replication:us-east-1:removed:bucket".to_string()]);
+4 -4
View File
@@ -35,10 +35,10 @@ pub use config::{
REPLICATION_READ_ONLY_HISTORICAL_FIELDS, REPLICATION_WRITABLE_FIELDS, ReplicationConfigStructureError,
ReplicationConfigurationExt, ReplicationTargetValidationError, active_replication_rule_destination_arns,
assign_site_replication_rule_priorities, invalid_replication_config_status_field, is_reconciler_owned_site_replication_rule,
is_site_replication_role, is_site_replication_rule, merge_incoming_replication_config, merge_user_replication_config,
replication_target_arn_deployment_id, replication_target_arns, should_remove_replication_target,
site_replication_rule_deployment_id, unsupported_replication_config_field, validate_replication_config_structure,
validate_replication_config_target_arns,
is_site_replication_role, is_site_replication_rule, legacy_role_target_arn, merge_incoming_replication_config,
merge_user_replication_config, replication_target_arn_deployment_id, replication_target_arns,
should_remove_replication_target, site_replication_rule_deployment_id, unsupported_replication_config_field,
validate_replication_config_structure, validate_replication_config_target_arns,
};
pub use delete::{
DeletedObjectReplicationInfo, delete_marker_purge_mrf_entry, delete_marker_purge_version_id,
+66 -108
View File
@@ -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;
@@ -114,12 +96,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
@@ -203,7 +179,6 @@ impl DataUsageCache {
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;
@@ -581,15 +556,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 +574,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 +610,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 +641,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 +651,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 +686,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 +705,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 +715,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 +728,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 +742,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 +792,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 +809,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 +828,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 +839,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
+6 -57
View File
@@ -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(),
+11
View File
@@ -295,6 +295,17 @@ impl Settlement {
counter!("rustfs_scanner_heal_candidate_terminal_total",
"disposition" => self.disposition, "scope" => self.scope, "scan_mode" => self.mode.as_str())
.increment(self.candidates);
if self.scope != "dry_run" {
let source = match self.mode {
HealScanMode::Deep => rustfs_scanner_metrics::metrics::ScannerWorkSource::Bitrot,
HealScanMode::Unknown | HealScanMode::Normal => rustfs_scanner_metrics::metrics::ScannerWorkSource::Heal,
};
if self.execution == "completed" {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_executed(source, self.candidates);
} else if self.execution == "failed" {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_failed(source, self.candidates);
}
}
if self.first_task_observation {
counter!("rustfs_scanner_heal_task_terminal_observations_total").increment(1);
}
+7 -13
View File
@@ -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]
+32 -2
View File
@@ -1919,11 +1919,41 @@ async fn load_scanner_pause_backlog<S>(storeapi: Arc<S>) -> Result<LoadedScanner
where
S: ScannerStorage,
{
let replicas = read_scanner_pause_backlog_replicas(storeapi).await;
let replicas = read_scanner_pause_backlog_replicas(storeapi.clone()).await;
if replicas.is_empty() {
return Err("scanner pause backlog has no surviving storage replicas".to_string());
}
select_scanner_pause_backlog_replicas(replicas).map_err(|failure| failure.to_string())
let loaded = select_scanner_pause_backlog_replicas(replicas).map_err(|failure| failure.to_string())?;
if !loaded.durable {
// When a newly expanded cluster immediately starts decommissioning the
// source pool before the scanner has repaired membership onto the new
// writable pool(s), all writable sets read as `Missing` while the
// retiring source pool still holds the authoritative native ledger.
// Bootstrapping an independent generation on the new writable pool(s)
// here would create equal-size or competing source/target commit proofs
// that block decommission retirement (`HandoffConflict`). Defer writer
// bootstrap until decommission hands off and retires the source replica.
let writable_ids = loaded.replicas.iter().map(|replica| replica.id).collect::<BTreeSet<_>>();
let mut retiring_sets = Vec::new();
for set in storeapi.all_set_disks() {
let id = ScannerPauseBacklogReplicaId::from_set(&set).map_err(|err| err.to_string())?;
if !writable_ids.contains(&id) {
retiring_sets.push(set);
}
}
if !retiring_sets.is_empty() {
let retiring_replicas = join_all(retiring_sets.into_iter().map(read_scanner_pause_backlog_replica)).await;
if retiring_replicas
.iter()
.any(|replica| !matches!(replica.state, ScannerPauseBacklogReplicaState::Missing))
{
return Err(
"scanner pause backlog handoff from a retiring pool is still pending on surviving writable sets".to_string(),
);
}
}
}
Ok(loaded)
}
async fn read_scanner_pause_backlog_replicas<S>(storeapi: Arc<S>) -> Vec<ScannerPauseBacklogReplica>
+47 -18
View File
@@ -263,10 +263,15 @@ pub fn heal_object_select_prob() -> u32 {
}
fn deep_verify_cooldown() -> Duration {
Duration::from_secs(rustfs_utils::get_env_u64(
ENV_SCANNER_DEEP_VERIFY_COOLDOWN_SECS,
DEFAULT_SCANNER_DEEP_VERIFY_COOLDOWN_SECS,
))
let default_secs = if rustfs_utils::get_env_opt_str(rustfs_config::ENV_SCANNER_BITROT_CYCLE_SECS)
.and_then(|raw| raw.trim().parse::<u64>().ok())
== Some(0)
{
0
} else {
DEFAULT_SCANNER_DEEP_VERIFY_COOLDOWN_SECS
};
Duration::from_secs(rustfs_utils::get_env_u64(ENV_SCANNER_DEEP_VERIFY_COOLDOWN_SECS, default_secs))
}
fn object_is_within_deep_verify_cooldown(mod_time: Option<OffsetDateTime>, now: OffsetDateTime, cooldown: Duration) -> bool {
@@ -372,6 +377,23 @@ fn record_scanner_replication_admission(metrics: &Metrics, roi: &ReplicationHeal
}
}
fn record_scanner_site_replication_admission(
metrics: &Metrics,
roi: &ReplicationHealObject,
admission: ReplicationQueueAdmission,
) {
let work = scanner_replication_work_update(admission);
metrics.record_scanner_source_work(ScannerWorkSource::SiteReplication, work);
if !roi.is_empty_identity() {
let kind = if roi.is_existing_object_repair() {
ScannerReplicationRepairKind::SiteActiveResync
} else {
ScannerReplicationRepairKind::SitePassiveRequeue
};
metrics.record_scanner_replication_repair_work(kind, work);
}
}
fn scanner_heal_source(scan_mode: HealScanMode) -> ScannerWorkSource {
match scan_mode {
HealScanMode::Deep => ScannerWorkSource::Bitrot,
@@ -1693,14 +1715,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;
}
@@ -2622,10 +2646,13 @@ impl FolderScanner {
let work_started = tokio::time::Instant::now();
let heal_enabled = this_hash.mod_alt(
self.old_cache.info.next_cycle as u32 / folder.object_heal_prob_div,
self.heal_object_select / folder.object_heal_prob_div,
) && self.try_should_heal().await?;
let heal_bitrot = self.scan_mode == HealScanMode::Deep;
let selected_for_heal = heal_bitrot
|| this_hash.mod_alt(
self.old_cache.info.next_cycle as u32 / folder.object_heal_prob_div,
self.heal_object_select / folder.object_heal_prob_div,
);
let heal_enabled = selected_for_heal && self.try_should_heal().await?;
let mut item = ScannerItem {
path: file_path,
@@ -2637,7 +2664,7 @@ impl FolderScanner {
replication: active_replication.clone(),
heal_scope: None,
heal_enabled,
heal_bitrot: self.scan_mode == HealScanMode::Deep,
heal_bitrot,
debug: self.data_usage_scanner_debug,
file_type: entry_type,
notification_bucket_incarnation: self.notification_bucket_incarnation,
@@ -2834,7 +2861,9 @@ impl FolderScanner {
self.coverage_gap |= self.old_cache.info.scan_progress.is_some();
}
self.apply_size_reconciliation(&sz);
into.objects += 1;
if !sz.all_versions_queued_for_delete {
into.objects += 1;
}
object_count += 1;
self.budget.record_object_scanned();
self.checkpoint_objects = self.checkpoint_objects.saturating_add(1);
@@ -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"
);
}
@@ -844,6 +844,10 @@ impl ScannerItem {
|| event.action == IlmAction::DelMarkerDeleteAllVersionsAction
{
remaining_versions = 0;
} else if !versioning_config.prefix_enabled(&object_path)
&& event.action == IlmAction::DeleteAction
{
remaining_versions = remaining_versions.saturating_sub(1);
}
} else if matches!(
event.action,
@@ -981,8 +985,9 @@ impl ScannerItem {
if record_scanner_ilm_action_if_queued(global_metrics(), event.action, 1, queued) {
done_ilm(1)();
if !versioning_config.prefix_enabled(&object_path) && event.action == IlmAction::DeleteAction {
remaining_versions -= 1;
remaining_versions = remaining_versions.saturating_sub(1);
size = 0;
account_now = false;
}
}
}
@@ -1076,6 +1081,9 @@ impl ScannerItem {
}
}
}
if !object_infos.is_empty() && remaining_versions == 0 {
size_summary.all_versions_queued_for_delete = true;
}
if !cancellation.is_some_and(CancellationToken::is_cancelled) {
self.alert_excessive_versions(remaining_versions, cumulative_size, notification_bucket_incarnation);
}
@@ -1121,12 +1129,28 @@ impl ScannerItem {
None if !oi.version_purge_status.is_empty() => ReplicationConfig::new(None, None),
None => return,
};
let has_site_targets = replication.has_site_replication_targets();
let has_bucket_targets = replication.has_bucket_replication_targets() || !has_site_targets;
let done_replication = Metrics::time(Metric::CheckReplication);
let done_replication = if has_bucket_targets {
Some(Metrics::time(Metric::CheckReplication))
} else {
None
};
if has_site_targets {
global_metrics().record_scanner_source_checked(ScannerWorkSource::SiteReplication, 1);
}
let replication_result = queue_replication_heal(&oi.bucket, oi.clone(), replication, 0).await;
done_replication();
if let Some(done_replication) = done_replication {
done_replication();
}
let roi = replication_result.object_info;
record_scanner_replication_admission(global_metrics(), &roi, replication_result.admission);
if has_bucket_targets {
record_scanner_replication_admission(global_metrics(), &roi, replication_result.admission);
}
if has_site_targets {
record_scanner_site_replication_admission(global_metrics(), &roi, replication_result.admission);
}
if !Self::should_account_replication_stats(oi) {
return;
}
@@ -1195,6 +1219,7 @@ impl ScannerItem {
let now = OffsetDateTime::now_utc();
let scan_mode = effective_object_heal_scan_mode(self.heal_bitrot, oi.mod_time, now);
global_metrics().record_scanner_source_checked(scanner_heal_source(scan_mode), 1);
if self.heal_bitrot && scan_mode != HealScanMode::Deep {
let cooldown = deep_verify_cooldown();
let age_secs = oi.mod_time.map(|mod_time| {
+38 -36
View File
@@ -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) {
@@ -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
+6 -6
View File
@@ -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(
+14 -57
View File
@@ -876,10 +876,8 @@ 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,
fail_revision_read: AtomicBool,
backup_unavailable: AtomicBool,
reads: std::sync::atomic::AtomicUsize,
backup_puts: std::sync::atomic::AtomicUsize,
}
@@ -901,7 +899,12 @@ 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 self.fail_revision_read.swap(false, Ordering::SeqCst) {
return Err(StorageError::Io(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"injected revision read failure",
)));
}
if object.ends_with(".bkp") && self.backup_unavailable.load(Ordering::SeqCst) {
return Err(StorageError::InsufficientReadQuorum(bucket.to_string(), object.to_string()));
}
@@ -927,19 +930,7 @@ impl crate::storage_api::owner::ObjectIO for CheckpointFaultStore {
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 +952,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,10 +977,8 @@ 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),
fail_revision_read: AtomicBool::new(false),
backup_unavailable: AtomicBool::new(false),
reads: std::sync::atomic::AtomicUsize::new(0),
backup_puts: std::sync::atomic::AtomicUsize::new(0),
});
let ctx = CancellationToken::new();
@@ -1024,12 +1013,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");
@@ -1083,30 +1070,6 @@ async fn checkpoint_advances_only_with_confirmed_commit_revisions() {
.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 +1077,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
+26
View File
@@ -284,6 +284,32 @@ impl ScannerReplicationConfig {
.is_some_and(|config| EcstoreReplicationConfigurationExt::has_active_rules(config, prefix, recursive))
}
pub(crate) fn has_site_replication_targets(&self) -> bool {
self.0
.remotes
.as_ref()
.is_some_and(|remotes| remotes.targets.iter().any(|target| !target.deployment_id.trim().is_empty()))
|| self.0.config.as_ref().is_some_and(|config| {
config.rules.iter().any(|rule| {
!rule.status.eq_ignore_ascii_case("Disabled")
&& rule.id.as_deref().is_some_and(|id| id.starts_with("site-repl-"))
})
})
}
pub(crate) fn has_bucket_replication_targets(&self) -> bool {
self.0
.remotes
.as_ref()
.is_some_and(|remotes| remotes.targets.iter().any(|target| target.deployment_id.trim().is_empty()))
|| self.0.config.as_ref().is_some_and(|config| {
config.rules.iter().any(|rule| {
!rule.status.eq_ignore_ascii_case("Disabled")
&& !rule.id.as_deref().is_some_and(|id| id.starts_with("site-repl-"))
})
})
}
pub(crate) fn into_ecstore(self) -> EcstoreReplicationConfig {
self.0
}
+23 -109
View File
@@ -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();
+1 -3
View File
@@ -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};
@@ -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
-7
View File
@@ -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"
+1 -74
View File
@@ -192,7 +192,7 @@ pub struct LockEntry {
pub since: Option<String>,
/// How long the lock has been held, in seconds.
pub elapsed_secs: u64,
/// Truncated whole seconds remaining until the lock's timeout expires (`0` when under 1s remains or already past).
/// Seconds until the lock's timeout expires (0 if already past).
pub ttl_secs: u64,
}
@@ -1820,77 +1820,4 @@ mod tests {
assert!(client.release(&lock_id).await.expect("local lock release should succeed"));
}
#[tokio::test(start_paused = true)]
async fn collect_top_locks_is_read_only_and_reports_truncated_remaining_ttl() {
use rustfs_lock::{FastObjectLockManager, GlobalLockManager, LocalClient, LockClient, LockRequest, LockStatus};
let manager = Arc::new(GlobalLockManager::Enabled(Arc::new(FastObjectLockManager::new())));
let client = Arc::new(LocalClient::with_manager(manager.clone()));
let resource = ObjectKey::new("diag-bucket", "subsecond-read-lock");
// Half-second offset puts expiry between the t=30s and t=31s 1s reaper ticks.
let request = LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(Duration::from_millis(30_500));
assert!(
client
.acquire_lock(&request)
.await
.expect("shared lock acquisition should succeed")
.success
);
// Let the lazily spawned 1s reaper initialize its interval at t=0 before advancing virtual time.
tokio::task::yield_now().await;
let clients: Vec<Arc<dyn rustfs_lock::client::LockClient>> = vec![client.clone()];
// At t=29.6s, 900ms remains: truncated ttl_secs is 0 while the guard is still live.
tokio::time::advance(Duration::from_millis(29_600)).await;
tokio::task::yield_now().await;
let subsecond = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager.clone(), clients.clone()).await;
let entry = subsecond
.locks
.iter()
.find(|entry| entry.bucket == "diag-bucket" && entry.object == "subsecond-read-lock")
.expect("sub-second live read lock must remain visible");
assert_eq!(entry.lock_type, "READ");
assert_eq!(entry.ttl_secs, 0, "remaining TTL under 1s truncates to 0");
assert_eq!(
client
.check_status(&request.lock_id)
.await
.expect("read live lock status")
.expect("live guard remains registered")
.status,
LockStatus::Acquired
);
// Step through the t=30.0s tick while the lease is still live (deadline is t=30.5s),
// then move to t=30.6s: the lease is expired, while the next 1s reaper tick is at t=31.0s.
// Calling top/locks must remain read-only and keep reporting the still-held physical guard.
tokio::time::advance(Duration::from_millis(400)).await;
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_millis(600)).await;
tokio::task::yield_now().await;
let before_reap = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager.clone(), clients.clone()).await;
let expired_entry = before_reap
.locks
.iter()
.find(|entry| entry.bucket == "diag-bucket" && entry.object == "subsecond-read-lock")
.expect("unreaped physical guard must remain visible to read-only top/locks");
assert_eq!(expired_entry.ttl_secs, 0);
assert_eq!(
client
.check_status(&request.lock_id)
.await
.expect("read expired lock status")
.expect("top/locks must not mutate or release an unreaped guard")
.status,
LockStatus::Expired
);
// After the t=31.0s reaper tick runs, the background reaper frees the guard on its own.
tokio::time::advance(Duration::from_millis(500)).await;
tokio::task::yield_now().await;
let after_reap = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager, clients).await;
assert!(after_reap.locks.is_empty(), "expired read lock must disappear after background reaping");
}
}
@@ -405,17 +405,18 @@ fn collect_resettable_replication_target_arns(config: &PersistedReplicationConfi
continue;
}
let arn = if config.role.trim().is_empty() {
rule.destination.bucket.trim().to_string()
let legacy_role = replication::legacy_role_target_arn(&config.role);
let arn = if let Some(role) = legacy_role {
role.to_string()
} else {
config.role.trim().to_string()
rule.destination.bucket.trim().to_string()
};
if seen.insert(arn.clone()) {
arns.push(arn);
}
if !config.role.trim().is_empty() {
if legacy_role.is_some() {
break;
}
}
@@ -271,8 +271,7 @@ fn validate_replication_check_config_targets(
}
}
let role = config.role.trim();
if !role.is_empty() {
if let Some(role) = crate::admin::storage_api::bucket::replication::legacy_role_target_arn(&config.role) {
if !configured_arns.contains(role) {
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
+2 -1
View File
@@ -568,7 +568,8 @@ pub(crate) mod replication {
OperatorRuleContract, REMOTE_TARGET_CAPABILITY_CONTRACT_VERSION, REMOTE_TARGET_READ_ONLY_HISTORICAL_FIELDS,
REMOTE_TARGET_UNSUPPORTED_FIELDS, REMOTE_TARGET_WRITABLE_FIELDS, REPLICATION_CAPABILITY_CONTRACT_VERSION,
REPLICATION_READ_ONLY_HISTORICAL_FIELDS, REPLICATION_WRITABLE_FIELDS, assign_site_replication_rule_priorities,
merge_incoming_replication_config, replication_target_arn_deployment_id, site_replication_rule_deployment_id,
legacy_role_target_arn, merge_incoming_replication_config, replication_target_arn_deployment_id,
site_replication_rule_deployment_id,
};
pub(crate) type BucketReplicationResyncStatus = super::ecstore_bucket::replication::BucketReplicationResyncStatus;
pub(crate) type BucketStats = super::ecstore_bucket::replication::BucketStats;
@@ -22,7 +22,7 @@
//! or the `?metadata=true` listing (`listing.rs`).
//! Upstream: both S3 edges. Downstream: the store, `table_list_isolation`.
use super::list_objects::{listed_etag_owned, listed_last_modified, listed_storage_class_owned};
use super::list_objects::{listed_etag, listed_last_modified, listed_storage_class};
use super::*;
use crate::app::storage_api::bucket_usecase::contract::list::ListOperations as _;
use rustfs_gateway_types::OpaqueString;
@@ -104,44 +104,16 @@ fn list_object_versions_output(
params: ListObjectVersionsParams,
encoding_type: Option<gateway_dto::EncodingType>,
) -> S3Result<gateway_dto::ListObjectVersionsOutput> {
let (version_count, delete_count) = info.objects.iter().fold((0usize, 0usize), |(v, d), object| {
if object.name.is_empty() {
(v, d)
} else if object.delete_marker {
(v, d + 1)
} else {
(v + 1, d)
}
});
let mut versions = Vec::with_capacity(version_count);
let mut delete_markers = Vec::with_capacity(delete_count);
for object in info.objects {
if object.name.is_empty() {
continue;
}
let size = if object.delete_marker {
0
} else {
object.get_actual_size_or_physical()
};
let ObjectInfo {
name,
mod_time,
etag,
storage_class,
user_defined,
delete_marker,
version_id,
is_latest,
..
} = object;
let key = dto_values::stored_object_key_owned(name)?;
let last_modified = listed_last_modified(mod_time);
if delete_marker {
let mut versions = Vec::new();
let mut delete_markers = Vec::new();
for object in info.objects.iter().filter(|object| !object.name.is_empty()) {
let key = dto_values::stored_object_key(&object.name)?;
let last_modified = listed_last_modified(object.mod_time);
if object.delete_marker {
delete_markers.push(gateway_dto::DeleteMarkerEntry {
key,
version_id: listed_version_id(version_id),
is_latest,
version_id: listed_version_id(object.version_id),
is_latest: object.is_latest,
last_modified,
..Default::default()
});
@@ -149,11 +121,11 @@ fn list_object_versions_output(
versions.push(gateway_dto::ObjectVersion {
key,
last_modified,
size,
version_id: listed_version_id(version_id),
is_latest,
e_tag: listed_etag_owned(etag, &user_defined),
storage_class: listed_storage_class_owned(storage_class),
size: object.get_actual_size_or_physical(),
version_id: listed_version_id(object.version_id),
is_latest: object.is_latest,
e_tag: listed_etag(object),
storage_class: listed_storage_class(object.storage_class.as_deref()),
..Default::default()
});
}
+39 -52
View File
@@ -239,16 +239,9 @@ pub(crate) fn list_objects_v2_output(
fetch_owner: bool,
encoding_type: Option<gateway_dto::EncodingType>,
) -> S3Result<gateway_dto::ListObjectsV2Output> {
let ListObjectsV2Info {
is_truncated,
next_continuation_token,
objects,
prefixes,
..
} = info;
let (contents, common_prefixes) = page_entries(objects, prefixes, fetch_owner)?;
let (contents, common_prefixes) = page_entries(&info, fetch_owner)?;
Ok(gateway_dto::ListObjectsV2Output {
is_truncated,
is_truncated: info.is_truncated,
key_count: key_count(contents.len() + common_prefixes.len()),
contents,
common_prefixes,
@@ -258,7 +251,8 @@ pub(crate) fn list_objects_v2_output(
max_keys: params.max_keys,
encoding_type,
continuation_token: params.response_continuation_token.map(OpaqueString::from),
next_continuation_token: next_continuation_token
next_continuation_token: info
.next_continuation_token
.map(|cursor| OpaqueString::from(encode_list_objects_v2_continuation_token(&cursor))),
start_after: params.response_start_after,
..Default::default()
@@ -281,10 +275,9 @@ fn list_objects_output(
) -> S3Result<gateway_dto::ListObjectsOutput> {
let cursor = info.next_continuation_token.as_deref().filter(|_| cursor_is_a_key);
let next_marker = list_objects_next_marker(&info, cursor);
let is_truncated = info.is_truncated;
let (contents, common_prefixes) = page_entries(info.objects, info.prefixes, false)?;
let (contents, common_prefixes) = page_entries(&info, false)?;
Ok(gateway_dto::ListObjectsOutput {
is_truncated,
is_truncated: info.is_truncated,
marker: marker.unwrap_or_default(),
next_marker,
contents,
@@ -309,50 +302,42 @@ fn key_count(entries: usize) -> i32 {
/// The entries of a page as an answer carries them. A keyless entry is the store's placeholder for
/// a page boundary, never an object.
fn page_entries(
objects: Vec<ObjectInfo>,
prefixes: Vec<String>,
info: &ListObjectsV2Info,
fetch_owner: bool,
) -> S3Result<(Vec<gateway_dto::Object>, Vec<gateway_dto::CommonPrefix>)> {
let mut contents = Vec::with_capacity(objects.len());
for object in objects {
if object.name.is_empty() {
continue;
}
// Compressed legacy objects may retain an unknown (-1) logical-size sentinel; never
// expose that internal value.
let size = object.get_actual_size_or_physical();
let ObjectInfo {
name,
mod_time,
etag,
storage_class,
user_defined,
..
} = object;
contents.push(gateway_dto::Object {
key: dto_values::stored_object_key_owned(name)?,
last_modified: listed_last_modified(mod_time),
size,
e_tag: listed_etag_owned(etag, &user_defined),
storage_class: listed_storage_class_owned(storage_class),
owner: fetch_owner.then(dto_values::owner),
..Default::default()
});
}
let common_prefixes = prefixes
.into_iter()
.map(|prefix| gateway_dto::CommonPrefix { prefix })
let contents = info
.objects
.iter()
.filter(|object| !object.name.is_empty())
.map(|object| {
Ok(gateway_dto::Object {
key: dto_values::stored_object_key(&object.name)?,
last_modified: listed_last_modified(object.mod_time),
// Compressed legacy objects may retain an unknown (-1) logical-size sentinel; never
// expose that internal value.
size: object.get_actual_size_or_physical(),
e_tag: listed_etag(object),
storage_class: listed_storage_class(object.storage_class.as_deref()),
owner: fetch_owner.then(dto_values::owner),
..Default::default()
})
})
.collect::<S3Result<_>>()?;
let common_prefixes = info
.prefixes
.iter()
.map(|prefix| gateway_dto::CommonPrefix { prefix: prefix.clone() })
.collect();
Ok((contents, common_prefixes))
}
/// The entity tag a listing shows: none for an object whose tag is an encryption fingerprint.
pub(super) fn listed_etag_owned(
etag: Option<String>,
user_defined: &HashMap<String, String>,
) -> Option<rustfs_gateway_types::ETag> {
etag.filter(|_| rustfs_utils::http::etag_can_be_listed(user_defined))
.map(dto_values::stored_etag_owned)
pub(super) fn listed_etag(object: &ObjectInfo) -> Option<rustfs_gateway_types::ETag> {
object
.etag
.as_deref()
.filter(|_| rustfs_utils::http::etag_can_be_listed(&object.user_defined))
.map(dto_values::stored_etag)
}
/// A listing entry's `LastModified`. An entry the store holds without one (an on-demand migration
@@ -363,8 +348,10 @@ pub(super) fn listed_last_modified(mod_time: Option<time::OffsetDateTime>) -> ru
}
/// A listing entry's `StorageClass`, absent as [`listed_last_modified`] is.
pub(super) fn listed_storage_class_owned(storage_class: Option<String>) -> gateway_dto::StorageClass {
storage_class.map(gateway_dto::StorageClass::custom).unwrap_or_default()
pub(super) fn listed_storage_class(storage_class: Option<&str>) -> gateway_dto::StorageClass {
storage_class
.map(|storage_class| gateway_dto::StorageClass::custom(storage_class.to_owned()))
.unwrap_or_default()
}
/// ListObjects' `NextMarker`: on a truncated page, the key the walker stopped at (the cursor the
+58 -93
View File
@@ -14,7 +14,7 @@
//! Object and version listing use-case operations, including the metadata listing extension.
use super::list_objects::listed_etag_owned;
use super::list_objects::listed_etag;
use super::*;
use crate::app::metadata_listing::{MetadataListQuery, ObjectsQuery, VersionsQuery};
use crate::app::storage_api::bucket_usecase::access::{versioned_read_action, versioned_tagging_action};
@@ -326,31 +326,15 @@ fn encode_list_versions_value(value: &str, encoding_type: Option<&EncodingType>)
}
}
fn encode_list_versions_value_owned(value: String, encoding_type: Option<&EncodingType>) -> String {
fn encode_list_objects_v2_value(value: &str, encoding_type: Option<&EncodingType>) -> String {
if encoding_type == Some(&EncodingType::URL) {
match encode(&value) {
Cow::Borrowed(_) => value,
Cow::Owned(encoded) => encoded,
}
} else {
value
}
}
fn encode_list_objects_v2_value_owned(value: String, encoding_type: Option<&EncodingType>) -> String {
if encoding_type != Some(&EncodingType::URL) {
return value;
}
// ListObjectsV2 preserves path separators and RFC 3986 unreserved characters.
const ENCODE_SET: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
.remove(b'/')
.remove(b'-')
.remove(b'.')
.remove(b'_')
.remove(b'~');
match Cow::from(percent_encoding::utf8_percent_encode(&value, ENCODE_SET)) {
Cow::Borrowed(_) => value,
Cow::Owned(encoded) => encoded,
.split('/')
.map(|part| encode(part).into_owned())
.collect::<Vec<_>>()
.join("/")
} else {
value.to_string()
}
}
@@ -479,7 +463,7 @@ fn build_list_object_versions_metadata_output(
let common_prefixes = object_infos
.prefixes
.into_iter()
.map(|prefix_value| encode_list_versions_value_owned(prefix_value, encoding_type))
.map(|prefix_value| encode_list_versions_value(&prefix_value, encoding_type))
.collect::<Vec<_>>();
let entries = object_infos
@@ -487,44 +471,26 @@ fn build_list_object_versions_metadata_output(
.into_iter()
.filter(|object| !object.name.is_empty())
.map(|object| {
let size = if object.delete_marker {
0
} else {
object.get_actual_size_or_physical()
};
let ObjectInfo {
name,
mod_time,
etag,
storage_class,
user_defined,
user_tags,
data_blocks,
parity_blocks,
delete_marker,
version_id,
is_latest,
..
} = object;
let version_id_str = list_object_version_id(version_id);
let lookup_key = (name, version_id);
let permission = permissions.get(&lookup_key).copied().unwrap_or_default();
let (name, _) = lookup_key;
let object_name = encode_list_versions_value_owned(name, encoding_type);
let object_name = encode_list_versions_value(&object.name, encoding_type);
let version_id = list_object_version_id(object.version_id);
let permission = permissions
.get(&(object.name.clone(), object.version_id))
.copied()
.unwrap_or_default();
let user_metadata = if permission.metadata_allowed {
build_metadata_extension_user_metadata(&user_defined)
build_metadata_extension_user_metadata(&object.user_defined)
} else {
None
};
let user_tags = if permission.tags_allowed && !user_tags.is_empty() {
Some((*user_tags).clone())
let user_tags = if permission.tags_allowed && !object.user_tags.is_empty() {
Some((*object.user_tags).clone())
} else {
None
};
let internal = if permission.metadata_allowed && (data_blocks > 0 || parity_blocks > 0) {
let internal = if permission.metadata_allowed && (object.data_blocks > 0 || object.parity_blocks > 0) {
Some(ObjectInternalInfo {
k: metadata_count_to_i32(data_blocks),
m: metadata_count_to_i32(parity_blocks),
k: metadata_count_to_i32(object.data_blocks),
m: metadata_count_to_i32(object.parity_blocks),
})
} else {
None
@@ -536,28 +502,32 @@ fn build_list_object_versions_metadata_output(
internal,
};
if delete_marker {
if object.delete_marker {
ListObjectVersionMetadataEntry::DeleteMarker(
MetadataObject {
key: object_name,
last_modified: mod_time,
last_modified: object.mod_time,
owner: Some(owner.clone()),
version_id: Some(version_id_str),
is_latest: Some(is_latest),
version_id: Some(version_id),
is_latest: Some(object.is_latest),
..Default::default()
},
extension,
)
} else {
ListObjectVersionMetadataEntry::Version(ObjectMetadataEntry {
e_tag: listed_etag_owned(etag, &user_defined),
e_tag: listed_etag(&object),
object: MetadataObject {
key: object_name,
last_modified: mod_time,
size: Some(size),
version_id: Some(version_id_str),
is_latest: Some(is_latest),
storage_class: Some(storage_class.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned())),
last_modified: object.mod_time,
size: Some(object.get_actual_size_or_physical()),
version_id: Some(version_id),
is_latest: Some(object.is_latest),
storage_class: Some(
object
.storage_class
.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned()),
),
owner: Some(owner.clone()),
},
extension,
@@ -569,7 +539,7 @@ fn build_list_object_versions_metadata_output(
let next_key_marker = object_infos
.next_marker
.filter(|marker| !marker.is_empty())
.map(|marker| encode_list_versions_value_owned(marker, encoding_type));
.map(|marker| encode_list_versions_value(&marker, encoding_type));
let next_version_id_marker = object_infos.next_version_idmarker.filter(|marker| !marker.is_empty());
ListObjectVersionsMetadataOutput {
@@ -604,51 +574,46 @@ fn build_list_objects_v2_metadata_output(
fetch_owner: bool,
permissions: &HashMap<String, ObjectMetadataPermissions>,
) -> ListObjectsV2MetadataOutput {
let owner = rustfs_owner();
let contents = object_infos
.objects
.into_iter()
.iter()
.filter(|object| !object.name.is_empty())
.map(|object| {
let size = object.get_actual_size_or_physical();
let ObjectInfo {
name,
mod_time,
etag,
storage_class,
user_defined,
user_tags,
data_blocks,
parity_blocks,
..
} = object;
let permission = permissions.get(&name).copied().unwrap_or_default();
let permission = permissions.get(&object.name).copied().unwrap_or_default();
let user_metadata = if permission.metadata_allowed {
build_metadata_extension_user_metadata(&user_defined)
build_metadata_extension_user_metadata(&object.user_defined)
} else {
None
};
let user_tags = if permission.tags_allowed && !user_tags.is_empty() {
Some((*user_tags).clone())
let user_tags = if permission.tags_allowed && !object.user_tags.is_empty() {
Some((*object.user_tags).clone())
} else {
None
};
let internal = if permission.metadata_allowed && (data_blocks > 0 || parity_blocks > 0) {
let internal = if permission.metadata_allowed && (object.data_blocks > 0 || object.parity_blocks > 0) {
Some(ObjectInternalInfo {
k: metadata_count_to_i32(data_blocks),
m: metadata_count_to_i32(parity_blocks),
k: metadata_count_to_i32(object.data_blocks),
m: metadata_count_to_i32(object.parity_blocks),
})
} else {
None
};
ObjectMetadataEntry {
e_tag: listed_etag_owned(etag, &user_defined),
e_tag: listed_etag(object),
object: MetadataObject {
key: encode_list_objects_v2_value_owned(name, encoding_type),
last_modified: mod_time,
size: Some(size),
storage_class: Some(storage_class.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned())),
owner: fetch_owner.then(rustfs_owner),
key: encode_list_objects_v2_value(&object.name, encoding_type),
last_modified: object.mod_time,
size: Some(object.get_actual_size_or_physical()),
storage_class: Some(
object
.storage_class
.clone()
.unwrap_or_else(|| StorageClass::STANDARD.as_str().to_owned()),
),
owner: fetch_owner.then_some(owner.clone()),
..Default::default()
},
extension: ObjectMetadataExtension {
@@ -663,7 +628,7 @@ fn build_list_objects_v2_metadata_output(
let common_prefixes = object_infos
.prefixes
.into_iter()
.map(|prefix| encode_list_objects_v2_value_owned(prefix, encoding_type))
.map(|prefix| encode_list_objects_v2_value(&prefix, encoding_type))
.collect::<Vec<_>>();
let key_count = metadata_count_to_i32(contents.len() + common_prefixes.len());
+1 -20
View File
@@ -69,14 +69,9 @@ pub(crate) fn stored_bucket_name(name: &str) -> S3Result<BucketName> {
/// The store's write rule refuses every such key (pinned by `dto_values::tests`), so this is a
/// store defect, never a key to leave out.
pub(crate) fn stored_object_key(key: &str) -> S3Result<ObjectKey> {
stored_object_key_owned(key.to_owned())
}
/// Owned counterpart of [`stored_object_key`] that moves `key` without cloning.
pub(crate) fn stored_object_key_owned(key: String) -> S3Result<ObjectKey> {
// The floor alone: a request name policy also refuses control characters, which a stored key
// can hold.
ObjectKey::new(key).map_err(|rejection| {
ObjectKey::new(key.to_owned()).map_err(|rejection| {
S3Error::with_message(
S3ErrorCode::InternalError,
format!("a stored object key the gateway cannot represent: {rejection}"),
@@ -135,16 +130,6 @@ pub(crate) fn stored_etag(stored: &str) -> ETag {
ETag::from_stored(inside.to_owned())
}
/// Owned counterpart of [`stored_etag`] that moves unquoted stored tags without cloning;
/// `stored.len() >= 2` matches `stored_etag`'s `strip_prefix('"').and_then(|r| r.strip_suffix('"'))`
/// so a single-character `"` remains unstripped.
pub(crate) fn stored_etag_owned(stored: String) -> ETag {
if stored.starts_with("W/\"") || (stored.starts_with('"') && stored.ends_with('"') && stored.len() >= 2) {
return stored_etag(&stored);
}
ETag::from_stored(stored)
}
/// A stored bucket configuration as the gateway DTO holds it: the bytes RustFS persists, read by
/// `parse`, one of the gateway's DTO bridges. The answer carries every stored member and no other.
///
@@ -351,7 +336,6 @@ mod tests {
let mut differing = Vec::new();
for (stored, opaque, weak, main_header, gateway_header, xml) in rows {
let etag = stored_etag(stored);
assert_eq!(stored_etag_owned(stored.to_owned()), etag, "stored_etag_owned mismatch for {stored:?}");
let header_fact = crate::app::object::ResponseEtag {
opaque: etag.opaque_tag().to_owned(),
weak: etag.is_weak(),
@@ -367,9 +351,6 @@ mod tests {
}
}
assert!(differing.is_empty(), "(stored tag, object header, gateway header, XML): {differing:?}");
for edge in [r#"""#, r#"W/"abc"#] {
assert_eq!(stored_etag_owned(edge.to_owned()), stored_etag(edge));
}
}
#[test]
+23 -81
View File
@@ -71,8 +71,8 @@ use std::time::{Duration, Instant};
use tokio::io::{AsyncReadExt, AsyncWrite};
use tokio::task::JoinHandle;
use tracing::{info, warn};
use transport::{Error as CuObjectError, RegisteredArena, Server as CuObjectServer, StagingChunk};
pub(crate) use transport::{RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER, RdmaToken};
use transport::{Error as CuObjectError, RdmaToken, RegisteredArena, Server as CuObjectServer, StagingChunk};
pub(crate) use transport::{RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER};
const LOG_COMPONENT_OBJECT: &str = "object";
const LOG_SUBSYSTEM_CUOBJECT: &str = "cuobject";
@@ -162,28 +162,17 @@ async fn resolve_addrs() -> io::Result<Vec<IpAddr>> {
Ok(ips.into_iter().collect())
}
/// Whether the S3-over-RDMA object surface of this build is switched on.
/// Whether the RDMA transport of this build is switched on.
#[cfg(not(feature = "nixl"))]
fn s3_transport_enabled() -> bool {
fn transport_enabled() -> bool {
get_env_bool(rustfs_config::ENV_RUSTFS_CUOBJECT_ENABLE, rustfs_config::DEFAULT_RUSTFS_CUOBJECT_ENABLE)
}
#[cfg(feature = "nixl")]
fn s3_transport_enabled() -> bool {
fn transport_enabled() -> bool {
get_env_bool(rustfs_config::ENV_RUSTFS_NIXL_ENABLE, rustfs_config::DEFAULT_RUSTFS_NIXL_ENABLE)
}
#[cfg(not(feature = "nixl"))]
fn internode_nixl_enabled() -> bool {
false
}
#[cfg(feature = "nixl")]
fn internode_nixl_enabled() -> bool {
get_env_opt_str(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT)
.is_some_and(|raw| raw.trim().eq_ignore_ascii_case(rustfs_config::INTERNODE_DATA_TRANSPORT_NIXL))
}
/// The transport servers of this node plus (control port, chunk bytes, pool
/// bytes) for the startup log; an empty list means the node has nowhere to
/// serve RDMA from and keeps serving over HTTP only.
@@ -290,16 +279,13 @@ async fn build_servers() -> io::Result<(Vec<Arc<CuObjectServer>>, u16, usize, us
Ok((vec![server], 0, chunk_bytes, pool_bytes))
}
/// Starts the RDMA transport servers of this node when the S3 transport
/// (`RUSTFS_CUOBJECT_ENABLE` or `RUSTFS_NIXL_ENABLE`) or internode NIXL
/// (`RUSTFS_INTERNODE_DATA_TRANSPORT=nixl`) is enabled.
/// Starts the RDMA transport servers of this node when the transport is
/// enabled (`RUSTFS_CUOBJECT_ENABLE` or `RUSTFS_NIXL_ENABLE`).
///
/// Invalid settings and server construction failures fail startup; a node
/// without RDMA addresses logs and serves GETs over HTTP only.
pub(crate) async fn init_cuobject_service() -> io::Result<()> {
let s3_enabled = s3_transport_enabled();
let internode_enabled = internode_nixl_enabled();
if !s3_enabled && !internode_enabled {
if !transport_enabled() {
return Ok(());
}
let inflight_writes = get_env_usize(ENV_RUSTFS_CUOBJECT_INFLIGHT_WRITES, DEFAULT_RUSTFS_CUOBJECT_INFLIGHT_WRITES).max(1);
@@ -321,11 +307,7 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> {
);
return Ok(());
}
let shard_arena = if s3_enabled {
install_cuobject_shard_arena(&servers).await?
} else {
None
};
let shard_arena = install_cuobject_shard_arena(&servers).await?;
#[cfg(feature = "nixl")]
install_nixl_recv_pool(&servers)?;
let (major, minor) = transport::library_version();
@@ -334,8 +316,6 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> {
component = LOG_COMPONENT_OBJECT,
subsystem = LOG_SUBSYSTEM_CUOBJECT,
state = "started",
s3_enabled,
internode_enabled,
server_count = servers.len(),
port,
chunk_bytes,
@@ -353,20 +333,18 @@ pub(crate) async fn init_cuobject_service() -> io::Result<()> {
if let Some(server) = servers.first() {
crate::storage::rpc::nixl_read::install_nixl_server(Arc::clone(server));
}
if s3_enabled {
let _ = SERVICE.set(Arc::new(CuObjectService {
servers,
inflight_writes,
put_read_ahead,
get_fanout,
get_fanout_min_bytes,
get_fanout_budget,
get_fanout_permits: Arc::new(tokio::sync::Semaphore::new(get_fanout_budget)),
active_gets: Arc::new(AtomicUsize::new(0)),
shard_arena,
next: AtomicUsize::new(0),
}));
}
let _ = SERVICE.set(Arc::new(CuObjectService {
servers,
inflight_writes,
put_read_ahead,
get_fanout,
get_fanout_min_bytes,
get_fanout_budget,
get_fanout_permits: Arc::new(tokio::sync::Semaphore::new(get_fanout_budget)),
active_gets: Arc::new(AtomicUsize::new(0)),
shard_arena,
next: AtomicUsize::new(0),
}));
Ok(())
}
@@ -599,9 +577,6 @@ pub(crate) fn rdma_token_for_request(headers: &HeaderMap) -> Option<RdmaToken> {
}
fn transfer_error(context: &str, error: CuObjectError) -> S3Error {
if matches!(error, CuObjectError::TokenTooSmall { .. }) {
return S3Error::with_message(S3ErrorCode::InvalidRange, error.to_string());
}
S3Error::with_message(S3ErrorCode::InternalError, format!("rdma get {context}: {error}"))
}
@@ -866,7 +841,7 @@ pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken) -> S3Res
let read_ahead = service.put_read_ahead;
let total = token.buffer_len;
let length = usize::try_from(total).map_err(|_| S3Error::with_message(S3ErrorCode::EntityTooLarge, "rdma put too large"))?;
let reads = PutReads {
let mut reads = PutReads {
server,
object: format!("{bucket}/{key}"),
token: token.clone(),
@@ -874,6 +849,7 @@ pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken) -> S3Res
read_ahead,
pending: VecDeque::new(),
};
reads.prefetch();
let stream = futures::stream::try_unfold(reads, move |mut reads| async move {
let Some(chunk) = reads.next().await? else { return Ok(None) };
Ok::<_, io::Error>(Some((Bytes::from_owner(chunk), reads)))
@@ -1433,37 +1409,3 @@ pub(crate) async fn finish_get_through_sink(
);
Ok(moved)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn token_too_small_maps_to_invalid_range() {
let error = transfer_error(
"write",
CuObjectError::TokenTooSmall {
buffer: 1024,
needed: 2048,
},
);
assert_eq!(error.code(), &S3ErrorCode::InvalidRange);
let other = transfer_error("write", CuObjectError::PoolExhausted);
assert_eq!(other.code(), &S3ErrorCode::InternalError);
}
#[cfg(feature = "nixl")]
#[test]
fn internode_nixl_switch_recognizes_trimmed_nixl_backend() {
temp_env::with_var(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, Some(" nixl "), || {
assert!(internode_nixl_enabled());
});
temp_env::with_var(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, Some("tcp-http"), || {
assert!(!internode_nixl_enabled());
});
temp_env::with_var_unset(rustfs_config::ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, || {
assert!(!internode_nixl_enabled());
});
}
}
+41 -106
View File
@@ -392,8 +392,6 @@ struct GetObjectReadSetup {
struct GetObjectPreparedRead {
io_planning: GetObjectIoPlanning,
read_setup: GetObjectReadSetup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink: Option<super::cuobject::StagingSinkHandle>,
}
struct GetObjectStrategyContext {
@@ -3026,52 +3024,6 @@ impl DefaultObjectUsecase {
})
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
fn ensure_rdma_token_fits_object(
rdma_token: Option<&super::cuobject::RdmaToken>,
rs: &Option<HTTPRangeSpec>,
opts: &ObjectOptions,
info: &ObjectInfo,
) -> S3Result<()> {
if let Some(token) = rdma_token
&& let Some(expected) = get_object_body_cache_plaintext_len(rs, opts, info)
&& u64::try_from(expected).is_ok_and(|needed| needed > token.buffer_len)
{
return Err(S3Error::with_message(
S3ErrorCode::InvalidRange,
format!(
"rdma token buffer ({} bytes) is smaller than the response ({expected} bytes)",
token.buffer_len
),
));
}
Ok(())
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
async fn prepare_rdma_sink_for_object(
bucket: &str,
key: &str,
rdma_token: Option<&super::cuobject::RdmaToken>,
rs: &Option<HTTPRangeSpec>,
opts: &ObjectOptions,
info: &ObjectInfo,
) -> S3Result<(
Option<crate::app::storage_api::object_usecase::StorageGetObjectSink>,
Option<super::cuobject::StagingSinkHandle>,
)> {
let Some(token) = rdma_token else {
return Ok((None, None));
};
Self::ensure_rdma_token_fits_object(Some(token), rs, opts, info)?;
if info.is_compressed() || info.is_encrypted() {
return Ok((None, None));
}
let handle = super::cuobject::StagingSinkHandle::new(bucket, key, token).await?;
let sink = handle.sink().with_max_bytes(token.buffer_len);
Ok((Some(sink), Some(handle)))
}
#[allow(clippy::too_many_arguments)]
async fn prepare_get_object_read_execution(
&self,
@@ -3094,8 +3046,6 @@ impl DefaultObjectUsecase {
let read_principal = SseKmsPrincipal::from_request(envelope);
let cache_adapter = self.object_data_cache();
let conditional = has_read_preconditions(envelope.headers());
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let rdma_token = super::cuobject::rdma_token_for_request(envelope.headers());
if cache_adapter.is_disabled() {
let io_planning = Self::acquire_get_object_io_planning(
manager,
@@ -3122,14 +3072,6 @@ impl DefaultObjectUsecase {
// entering `into_reader()`, which unwraps the stored DEK inside
// ecstore without a request principal (rustfs/backlog#2702).
authorize_sse_kms_object_read(read_principal.as_ref(), &prepared.object_info().user_defined).await?;
if conditional {
Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, prepared.object_info()).await?;
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let (sink, rdma_sink) =
Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info()).await?;
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let prepared = prepared.with_sink(sink);
let reader = track_object_read_setup(
object_traffic_health.as_deref(),
Self::with_get_object_conditions(
@@ -3155,12 +3097,7 @@ impl DefaultObjectUsecase {
read_principal.as_ref(),
)
.await?;
return Ok(GetObjectPreparedRead {
io_planning,
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink,
});
return Ok(GetObjectPreparedRead { io_planning, read_setup });
}
// Preserve the legacy metadata-fanout bound without making followers
@@ -3192,8 +3129,6 @@ impl DefaultObjectUsecase {
Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, initial_metadata.object_info())
.await?;
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
Self::ensure_rdma_token_fits_object(rdma_token.as_ref(), &rs, opts, initial_metadata.object_info())?;
let mut prepared = Some(initial_metadata);
'snapshot: {
let info = prepared
@@ -3258,8 +3193,6 @@ impl DefaultObjectUsecase {
return Ok(GetObjectPreparedRead {
io_planning: Self::get_object_io_planning_without_disk(manager),
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink: None,
});
}
if matches!(legacy_probe, GetObjectBodyCacheHookLookup::Miss) {
@@ -3291,8 +3224,6 @@ impl DefaultObjectUsecase {
return Ok(GetObjectPreparedRead {
io_planning: Self::get_object_io_planning_without_disk(manager),
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink: None,
});
}
@@ -3497,8 +3428,6 @@ impl DefaultObjectUsecase {
return Ok(GetObjectPreparedRead {
io_planning: Self::get_object_io_planning_without_disk(manager),
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink: None,
});
}
ColdFillCoordinateOutcome::Bypass => {
@@ -3509,20 +3438,10 @@ impl DefaultObjectUsecase {
}
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let rdma_sink;
let (mut io_planning, reader) = if let Some(prepared) = prepared.take() {
let io_planning = metadata_admission
.take()
.ok_or_else(|| s3_error!(InternalError, "prepared metadata admission is unavailable"))?;
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let prepared = {
let (sink, handle) =
Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info())
.await?;
rdma_sink = handle;
prepared.with_sink(sink)
};
let reader = track_object_read_setup(
object_traffic_health.as_deref(),
Self::with_get_object_conditions(
@@ -3558,17 +3477,6 @@ impl DefaultObjectUsecase {
.await
.map_err(map_get_object_reader_error)?;
authorize_sse_kms_object_read(read_principal.as_ref(), &prepared.object_info().user_defined).await?;
if conditional {
Self::validate_get_object_before_body(envelope, input, bucket, key, part_number, prepared.object_info()).await?;
}
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let prepared = {
let (sink, handle) =
Self::prepare_rdma_sink_for_object(bucket, key, rdma_token.as_ref(), &rs, opts, prepared.object_info())
.await?;
rdma_sink = handle;
prepared.with_sink(sink)
};
let reader = track_object_read_setup(
object_traffic_health.as_deref(),
Self::with_get_object_conditions(
@@ -3607,12 +3515,7 @@ impl DefaultObjectUsecase {
read_stage_start.elapsed().as_secs_f64(),
);
}
Ok(GetObjectPreparedRead {
io_planning,
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink,
})
Ok(GetObjectPreparedRead { io_planning, read_setup })
}
#[allow(clippy::too_many_arguments)]
@@ -5001,6 +4904,19 @@ impl DefaultObjectUsecase {
opts,
} = request_context;
drop(object_metadata_progress);
// cuObject S3-over-RDMA: hand the storage layer a sink that writes decoded
// bytes straight into registered staging (no pipe, no consumer copy). The
// owned handle moves to the body builder after the read is prepared.
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
let (opts, rdma_sink) = match super::cuobject::rdma_token_for_request(envelope.headers()) {
Some(token) => {
let handle = super::cuobject::StagingSinkHandle::new(&bucket, &key, &token).await?;
let mut opts = opts;
opts.get_object_sink = Some(handle.sink());
(opts, Some(handle))
}
None => (opts, None),
};
let manager = get_concurrency_manager();
@@ -5098,12 +5014,7 @@ impl DefaultObjectUsecase {
return finish_object_read_error(&mut envelope, helper.version_id(version_id_for_event), err).await;
}
};
let GetObjectPreparedRead {
io_planning,
read_setup,
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
rdma_sink,
} = prepared_read;
let GetObjectPreparedRead { io_planning, read_setup } = prepared_read;
let GetObjectIoPlanning {
disk_permit,
permit_wait_duration,
@@ -5140,6 +5051,12 @@ impl DefaultObjectUsecase {
// Clone ObjectInfo for event notification only when an event will
// actually be built — the clone is expensive for multipart objects.
let event_info = helper.wants_object_info().then(|| info.clone());
let has_version_id = input.version_id.is_some();
let raw_tag_count = if !info.user_tags.is_empty() {
decode_tags(&info.user_tags).len()
} else {
0
};
let output_build_start = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
let output_context = self
@@ -5205,13 +5122,31 @@ impl DefaultObjectUsecase {
);
}
let GetObjectOutputContext {
output,
mut output,
event_info,
effective_ec_block_size,
response_content_length,
optimal_buffer_size,
extra_checksum_headers,
} = output_context;
if raw_tag_count > 0 {
let tagging_action = if has_version_id {
S3Action::GetObjectVersionTaggingAction
} else {
S3Action::GetObjectTaggingAction
};
let replication_check = replication_request_authorized(&envelope)
&& get_header(envelope.headers(), SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() == Some("true");
let tag_count_allowed = match head::head_metadata_action_allowed(&envelope, tagging_action).await {
Ok(allowed) => allowed,
Err(err) => {
return Self::complete_get_object_error(helper.version_id(version_id_for_event), err);
}
};
if replication_check || tag_count_allowed {
output.dto.tag_count = i32::try_from(raw_tag_count).ok();
}
}
let total_duration = request_start.elapsed();
Self::finalize_get_object_completion(
+13 -5
View File
@@ -123,7 +123,7 @@ fn tagging_directive_is_access(headers: &http::HeaderMap) -> bool {
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"ACCESS"))
}
async fn head_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
pub(super) async fn head_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
// Metadata permissions still bind the owner when a policy explicitly denies them.
let mut probe = req.fork_for_authorization();
let Some(info) = probe.req_info_mut() else {
@@ -338,7 +338,7 @@ impl DefaultObjectUsecase {
key: &str,
opts: &ObjectOptions,
part_number: Option<i32>,
) -> Option<HeadObjectOutputFacts> {
) -> Option<(HeadObjectOutputFacts, Option<i32>)> {
let targets = get_read_proxy_targets(bucket, key, opts).await;
if targets.is_empty() {
return None;
@@ -366,7 +366,8 @@ impl DefaultObjectUsecase {
// MinIO-aligned accounting: one total per proxy attempt,
// one failed when no target served it.
record_replication_proxy(bucket, "HeadObject", false).await;
return Some(Self::proxy_sdk_head_output(remote));
let remote_tag_count = remote.tag_count;
return Some((Self::proxy_sdk_head_output(remote), remote_tag_count));
}
Err(err) if Self::proxy_sdk_error_is_not_found(&err) => {
debug!(bucket, key, arn = %target.arn, "read proxy: target does not have the object");
@@ -564,7 +565,7 @@ impl DefaultObjectUsecase {
// locally may still be served by proxying the HEAD to a
// replication target (backlog#1675 P1-5).
if req.object_tag_conditions().is_none()
&& let Some(output) = Box::pin(Self::proxy_head_object_to_replication_targets(
&& let Some((output, remote_tag_count)) = Box::pin(Self::proxy_head_object_to_replication_targets(
&req,
&bucket,
&key,
@@ -573,7 +574,14 @@ impl DefaultObjectUsecase {
))
.await
{
let response = read_answer(&bucket, req.method(), req.headers(), output).await;
let mut response = read_answer(&bucket, req.method(), req.headers(), output).await;
if let Some(tag_count) = remote_tag_count.filter(|&count| count > 0)
&& let Ok(header_value) = tag_count.to_string().parse::<HeaderValue>()
{
response
.headers
.insert(http::HeaderName::from_static(AMZ_TAG_COUNT), header_value);
}
let result = Ok(response);
complete_read(helper.version_id(version_id.unwrap_or_default()), &result);
return result;
+26 -3
View File
@@ -195,7 +195,7 @@ impl GatewayStack {
let iam = Arc::new(ServerIam {
server_ctx: Arc::clone(&assembly.server_ctx),
});
let root = Arc::new(live_root(Arc::clone(&assembly.server_ctx)));
let root = Arc::new(control_plane_root(&assembly)?);
admin::assemble(assembly, iam, root)
}
@@ -207,7 +207,7 @@ impl GatewayStack {
let iam = Arc::new(ServerIam {
server_ctx: Arc::clone(&assembly.server_ctx),
});
let root = Arc::new(live_root(Arc::clone(&assembly.server_ctx)));
let root = Arc::new(control_plane_root(&assembly)?);
control_plane::assemble(assembly, iam, root, router)
}
@@ -217,7 +217,7 @@ impl GatewayStack {
let iam = Arc::new(ServerIam {
server_ctx: Arc::clone(&assembly.server_ctx),
});
let root = Arc::new(live_root(Arc::clone(&assembly.server_ctx)));
let root = Arc::new(control_plane_root(&assembly)?);
reserved_console::assemble(assembly, iam, root)
}
@@ -728,6 +728,29 @@ impl EarlyAuthHandoff {
}
}
/// Control-plane and admin hosts bypass `ReadinessGateLayer` so their own admission gates
/// (`AdminBridge`, `S3Router::admit`, `ReservedConsole`) can return an audited `503
/// ServiceUnavailable` after signature verification. While `server_ctx` has no installed
/// `AppContext`, verify root signatures against this server's configured `GatewayAssembly`
/// credentials; once `AppContext` is installed, delegate strictly to `live_root`.
pub(super) fn control_plane_root(
assembly: &GatewayAssembly,
) -> Result<impl Fn() -> Option<Arc<RootCredentials>> + Send + Sync + 'static, GatewayAssemblyError> {
let startup_root = Arc::new(
RootCredentials::new(&assembly.root_access_key, &assembly.root_secret_key, &assembly.root_secret_key)
.map_err(GatewayAssemblyError::RootCredentials)?,
);
let server_ctx = Arc::clone(&assembly.server_ctx);
let live = live_root(Arc::clone(&server_ctx));
Ok(move || {
if server_ctx.installed_app_context().is_some() {
live()
} else {
Some(Arc::clone(&startup_root))
}
})
}
/// The root credentials of one server as they are now, read strictly from this server's installed
/// `AppContext` (never falling back to process-global credentials or token-signing keys). `None`
/// while this server context is uninstalled, lacks root credentials, or cannot verify a signature,
@@ -1128,3 +1128,34 @@ async fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned
Box::pin(assert_typed_admin_target_replication_and_heal_writes(&stack)).await;
Box::pin(assert_typed_admin_gets_and_object_lambda_fallback(&stack)).await;
}
#[tokio::test]
async fn pre_install_assembled_admin_and_control_plane_answer_503_not_500() {
let slot = ServerContextSlot::new();
let mut not_ready_assembly = assembly();
not_ready_assembly.server_ctx = Arc::clone(&slot);
let mut router = S3Router::new(false);
router.set_server_ctx(Arc::clone(&slot));
router
.insert(Method::GET, "/rustfs/admin/v3/pools/list", AdminOperation(&PROBE))
.expect("pools/list probe route");
let control_plane =
GatewayStack::assemble_control_plane(not_ready_assembly.clone(), Arc::new(router)).expect("control plane assembles");
let (status, _, body) = answer_request(&control_plane, signed(Method::GET, "/rustfs/admin/v3/pools/list", "")).await;
assert_eq!(
status,
StatusCode::SERVICE_UNAVAILABLE,
"pre-install control-plane request must return 503 ServiceUnavailable instead of 500: {body}"
);
assert!(body.contains("ServiceUnavailable"), "unexpected body: {body}");
let admin_stack = GatewayStack::assemble_admin(not_ready_assembly).expect("admin stack assembles");
let (admin_status, _, admin_body) = answer_request(&admin_stack, signed(Method::GET, "/rustfs/admin/v3/info", "")).await;
assert_eq!(
admin_status,
StatusCode::SERVICE_UNAVAILABLE,
"pre-install admin info request must return 503 ServiceUnavailable instead of 500: {admin_body}"
);
}
+8 -6
View File
@@ -1304,6 +1304,7 @@ pub(crate) fn bucket_target_matches_peer(target: &BucketTarget, peer: &PeerInfo)
}
pub(crate) fn site_replication_target_arns_by_peer(
bucket: &str,
config: Option<&PersistedReplicationConfiguration>,
) -> HashMap<String, String> {
let mut arns_by_peer = HashMap::new();
@@ -1312,12 +1313,13 @@ pub(crate) fn site_replication_target_arns_by_peer(
};
let mut configured_arns = Vec::new();
if !config.role.trim().is_empty() {
configured_arns.push(config.role.clone());
let role_arn = config.role.trim();
if !role_arn.is_empty() && role_arn.parse::<ARN>().is_ok_and(|parsed| parsed.bucket == bucket) {
configured_arns.push(role_arn.to_string());
}
for rule in &config.rules {
for rule in config.rules.iter().filter(|rule| is_derived_site_replication_rule(rule)) {
let arn = rule.destination.bucket.trim();
if !arn.is_empty() {
if !arn.is_empty() && arn.parse::<ARN>().is_ok_and(|parsed| parsed.bucket == bucket) {
configured_arns.push(arn.to_string());
}
}
@@ -1399,7 +1401,7 @@ pub(crate) fn reconcile_site_replication_bucket_targets(
return Ok(existing);
}
let configured_arns = site_replication_target_arns_by_peer(config);
let configured_arns = site_replication_target_arns_by_peer(bucket, config);
let mut targets = existing.targets;
for peer in state.peers.values() {
@@ -1662,7 +1664,7 @@ pub(crate) fn build_site_replication_config(
// Reuse the ARN already recorded for a peer so the rule keeps pointing at the same
// bucket target `reconcile_site_replication_bucket_targets` keys off (a MinIO-era
// `arn:minio:...` target would otherwise be orphaned by a freshly minted ARN).
let configured_arns = site_replication_target_arns_by_peer(existing);
let configured_arns = site_replication_target_arns_by_peer(bucket, existing);
let mut rules = Vec::new();
for peer in state.peers.values() {
if peer.deployment_id == local_peer.deployment_id || same_identity_endpoint(&peer.endpoint, &local_peer.endpoint) {
+30
View File
@@ -2139,6 +2139,36 @@ fn test_reconcile_site_replication_bucket_targets_keeps_operator_target_to_peer(
reconciled_again.targets[1].bandwidth_limit, 9,
"operator tuning of the site target carries over"
);
// An operator replication rule targeting a distinct bucket on the same peer
// deployment (`arn:minio:replication:us-east-1:remote:photos-dst`) must never
// be adopted as the site-replication target ARN, which would duplicate the
// operator target ARN in `BucketTargets` and disable both target clients.
let operator_peer_arn = "arn:minio:replication:us-east-1:remote:photos-dst".to_string();
let mut operator_on_peer = operator_target.clone();
operator_on_peer.arn = operator_peer_arn.clone();
let operator_config = PersistedReplicationConfiguration {
role: String::new(),
rules: vec![build_site_replication_rule(&operator_peer_arn, 1, "operator-bucket-repl")],
};
let reconciled_with_cfg = reconcile_site_replication_bucket_targets(
BucketTargets {
targets: vec![operator_on_peer.clone(), site_target.clone()],
},
"photos",
&state,
&local,
Some(&operator_config),
"secret",
)
.expect("reconcile targets with operator replication rule");
assert_eq!(reconciled_with_cfg.targets.len(), 2);
assert_eq!(reconciled_with_cfg.targets[0].arn, operator_peer_arn);
assert_eq!(reconciled_with_cfg.targets[1].arn, "arn:minio:replication::remote:photos");
assert_ne!(
reconciled_with_cfg.targets[0].arn, reconciled_with_cfg.targets[1].arn,
"site target must keep its own same-name bucket ARN"
);
}
#[test]
+10 -145
View File
@@ -22,12 +22,6 @@ BASELINE_REVISION="unknown"
CANDIDATE_REVISION="unknown"
ENDPOINT=""
DEPLOY_HOOK=""
CLUSTER_LOCK_FILE=""
RESTORE_HOOK=""
HOOK_TIMEOUT_SECS=180
NODE_QUEUE_DEVICES=()
NODE_QUEUE_TIMEOUT_SECS=60
REQUIRE_RENAME_RANK_METRICS=false
HEALTH_PATH="/health"
ADDRESS="127.0.0.1:9000"
DATA_ROOT="/tmp/rustfs-hotpath-abba"
@@ -109,17 +103,6 @@ Production / cluster mode:
The hook must deploy the selected binary, reset or
provision HOTPATH_ABBA_BUCKET for the requested
mode, then write a non-empty evidence file.
--cluster-lock-file <path> Reserve this cluster on the controller using flock.
--restore-hook <path> Executable run once after deployment starts, even on
failure or interruption. Requires --cluster-lock-file.
--hook-timeout-secs <n> Bound managed deploy and restore hooks (default 180).
--node-queue-devices <node=dev+dev>
Wait for two quiet 5s windows before each PUT attempt.
--node-queue-timeout-secs <n>
Bound the cluster queue wait (default 60).
--require-rename-rank-metrics
Require both rename completion ranks to advance in
each PUT attempt's service metrics.
--allow-unmanaged-external Preserve legacy external mode without a deploy
hook. Its output is not formal ABBA evidence.
--after-probe Enable per-round PUT HEAD/GET/hash verification.
@@ -231,12 +214,6 @@ while [[ $# -gt 0 ]]; do
--candidate-revision) CANDIDATE_REVISION="$2"; shift 2 ;;
--endpoint) ENDPOINT="$2"; shift 2 ;;
--deploy-hook) DEPLOY_HOOK="$2"; shift 2 ;;
--cluster-lock-file) CLUSTER_LOCK_FILE="$2"; shift 2 ;;
--restore-hook) RESTORE_HOOK="$2"; shift 2 ;;
--hook-timeout-secs) HOOK_TIMEOUT_SECS="$2"; shift 2 ;;
--node-queue-devices) NODE_QUEUE_DEVICES+=("$2"); shift 2 ;;
--node-queue-timeout-secs) NODE_QUEUE_TIMEOUT_SECS="$2"; shift 2 ;;
--require-rename-rank-metrics) REQUIRE_RENAME_RANK_METRICS=true; shift ;;
--health-path) HEALTH_PATH="$2"; shift 2 ;;
--address) ADDRESS="$2"; shift 2 ;;
--data-root) DATA_ROOT="$2"; shift 2 ;;
@@ -321,38 +298,6 @@ if [[ -n "$ENDPOINT" ]]; then
[[ -n "$DEPLOY_HOOK" ]] || log "warning: unmanaged external mode does not establish binary or data isolation and is not formal ABBA evidence"
fi
if (("${#NODE_QUEUE_DEVICES[@]}")); then
[[ "$EXTERNAL" == true && -n "$DEPLOY_HOOK" ]] || die "node queue checks require a managed endpoint with --deploy-hook"
queue_args=(--validate-only --timeout-secs "$NODE_QUEUE_TIMEOUT_SECS")
for entry in "${NODE_QUEUE_DEVICES[@]}"; do queue_args+=(--devices "$entry"); done
for entry in "${NODE_SSH_TARGETS[@]}"; do queue_args+=(--target "$entry"); done
"$PROJECT_ROOT/scripts/wait_cluster_disk_queue.sh" "${queue_args[@]}"
fi
if [[ "$REQUIRE_RENAME_RANK_METRICS" == true ]]; then
[[ -n "$SERVICE_PROMETHEUS_QUERY_URL" ]] || die "rename rank checks require --service-prometheus-query-url"
fi
if (("${#NODE_QUEUE_DEVICES[@]}")) || [[ "$REQUIRE_RENAME_RANK_METRICS" == true ]]; then
for spec in "${WORKLOADS[@]}"; do
IFS='|' read -r _ mode _ <<<"$spec"
[[ "$mode" == put ]] || die "node queue and rename rank checks require a PUT-only workload matrix"
done
fi
if [[ -n "$CLUSTER_LOCK_FILE" || -n "$RESTORE_HOOK" ]]; then
[[ "$EXTERNAL" == true && -n "$DEPLOY_HOOK" && -n "$CLUSTER_LOCK_FILE" && -n "$RESTORE_HOOK" ]] ||
die "managed cluster runs require --endpoint, --deploy-hook, --cluster-lock-file and --restore-hook"
[[ "$RESTORE_HOOK" == */* && -f "$RESTORE_HOOK" && -x "$RESTORE_HOOK" ]] ||
die "--restore-hook must be an executable file path"
validate_positive_int "$HOOK_TIMEOUT_SECS" "--hook-timeout-secs"
if [[ "$DRY_RUN" != true ]]; then
command -v flock >/dev/null && command -v timeout >/dev/null || die "managed cluster runs require flock and timeout"
exec 9>>"$CLUSTER_LOCK_FILE"
flock -n 9 || die "cluster lock is busy: $CLUSTER_LOCK_FILE"
mkdir -p -- "$(dirname -- "$OUT_DIR")"
mkdir -- "$OUT_DIR" || die "managed cluster runs require a fresh --out-dir"
fi
fi
mkdir -p "$OUT_DIR"
SERVER_LOG_DIR="$OUT_DIR/server-logs"
DEPLOY_EVIDENCE_DIR="$OUT_DIR/deploy-evidence"
@@ -374,66 +319,7 @@ tear_down() {
run kill "$SERVER_PID" 2>/dev/null || true
SERVER_PID=""
}
ACTIVE_PID=""
RESTORE_NEEDED=false
stop_active() {
[[ -n "$ACTIVE_PID" ]] || return 0
local i
kill -TERM -- "-$ACTIVE_PID" 2>/dev/null || kill -TERM "$ACTIVE_PID" 2>/dev/null || true
for ((i=0; i<5; i++)); do
kill -0 -- "-$ACTIVE_PID" 2>/dev/null || break
sleep 1
done
kill -KILL -- "-$ACTIVE_PID" 2>/dev/null || true
wait "$ACTIVE_PID" 2>/dev/null || true
ACTIVE_PID=""
}
run_managed() {
if [[ -z "$CLUSTER_LOCK_FILE" || "$DRY_RUN" == true ]]; then
run "$@"
return $?
fi
local status=0
# Give benchmark and hook descendants a process group we can stop before
# restoring the cluster. Only the controller holds the lock descriptor.
set -m
"$@" 9>&- &
ACTIVE_PID=$!
set +m
wait "$ACTIVE_PID" || status=$?
if kill -0 -- "-$ACTIVE_PID" 2>/dev/null; then
log "stopping remaining controller processes before restore"
stop_active
if ((status == 0)); then status=1; fi
fi
ACTIVE_PID=""
return "$status"
}
finish() {
local status=$?
trap - EXIT
trap '' INT TERM
stop_active
tear_down
if [[ "$RESTORE_NEEDED" == true ]]; then
log "restore hook: $DATASET_NAMESPACE"
local restore_status=0
HOTPATH_ABBA_DATASET_NAMESPACE="$DATASET_NAMESPACE" HOTPATH_ABBA_OUT_DIR="$OUT_DIR" \
timeout --kill-after=5s "${HOOK_TIMEOUT_SECS}s" "$RESTORE_HOOK" 9>&- >"$OUT_DIR/restore.log" 2>&1 || restore_status=$?
printf "exit_code=%s\n" "$restore_status" >"$OUT_DIR/restore.status"
if ((restore_status != 0)); then
log "restore hook failed; see $OUT_DIR/restore.log"
if ((status == 0)); then status=1; fi
fi
fi
exit "$status"
}
trap finish EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap tear_down EXIT INT TERM
dump_server_log() {
[[ -n "$SERVER_LOG" && -f "$SERVER_LOG" ]] || return 0
@@ -444,24 +330,19 @@ dump_server_log() {
wait_health() {
[[ "$DRY_RUN" == "true" ]] && return 0
local i remaining curl_timeout health_url="$ADDRESS" deadline=$((SECONDS+HEALTH_TIMEOUT_SECS))
case "$health_url" in http://*|https://*) ;; *) health_url="http://$health_url";; esac
while ((SECONDS < deadline)); do
i=$((HEALTH_TIMEOUT_SECS - (deadline - SECONDS)))
local i
for ((i = 0; i < HEALTH_TIMEOUT_SECS; i++)); do
if [[ "$EXTERNAL" != "true" && -n "$SERVER_PID" ]] && ! kill -0 "$SERVER_PID" 2>/dev/null; then
echo "error: rustfs server (pid $SERVER_PID) exited before becoming healthy after ${i}s" >&2
dump_server_log
return 1
fi
remaining=$((deadline - SECONDS))
((remaining > 0)) || break
curl_timeout=$((remaining < 5 ? remaining : 5))
if curl -fsS --max-time "$curl_timeout" "${health_url%/}${HEALTH_PATH}" >/dev/null 2>&1; then
if curl -fsS "http://${ADDRESS}${HEALTH_PATH}" >/dev/null 2>&1; then
return 0
fi
sleep 1
done
echo "error: endpoint ${health_url%/}${HEALTH_PATH} did not become healthy within ${HEALTH_TIMEOUT_SECS}s" >&2
echo "error: endpoint http://${ADDRESS}${HEALTH_PATH} did not become healthy within ${HEALTH_TIMEOUT_SECS}s" >&2
dump_server_log
return 1
}
@@ -501,13 +382,8 @@ bring_up() {
local binary_sha
binary_sha="$(sha256_file "$bin")"
[[ "$binary_sha" != "unknown" ]] || die "cannot attest external binary without a SHA-256 tool"
local hook_cmd=(bash -c "$DEPLOY_HOOK")
if [[ -n "$RESTORE_HOOK" && "$DRY_RUN" != true ]]; then
RESTORE_NEEDED=true
hook_cmd=(timeout --foreground --kill-after=5s "${HOOK_TIMEOUT_SECS}s" "${hook_cmd[@]}")
fi
HOTPATH_ABBA_LEG="$leg" HOTPATH_ABBA_PHASE="$phase" HOTPATH_ABBA_BINARY="$bin" HOTPATH_ABBA_BINARY_SHA256="$binary_sha" HOTPATH_ABBA_DRIVE_SYNC="$drive_sync" HOTPATH_ABBA_WORKLOAD="$workload" HOTPATH_ABBA_MODE="$mode" HOTPATH_ABBA_SIZE="$size" HOTPATH_ABBA_CELL_ID="$sync_label/$workload/$leg" HOTPATH_ABBA_DATASET_NAMESPACE="$DATASET_NAMESPACE" HOTPATH_ABBA_BUCKET="$bucket" HOTPATH_ABBA_DEPLOY_EVIDENCE_FILE="$evidence_file" \
run_managed "${hook_cmd[@]}"
run bash -c "$DEPLOY_HOOK"
if [[ "$DRY_RUN" != "true" ]]; then
[[ -s "$evidence_file" ]] || die "deploy hook did not write evidence for $sync_label/$workload/$leg: $evidence_file"
[[ "$(awk -F= '$1=="leg" {print substr($0, length($1) + 2)}' "$evidence_file")" == "$leg" ]] || die "deploy evidence leg does not match $sync_label/$workload/$leg"
@@ -589,11 +465,6 @@ measure() {
args+=(--require-node-telemetry)
fi
args+=(--node-ssh-timeout-secs "$NODE_SSH_TIMEOUT_SECS")
if (("${#NODE_QUEUE_DEVICES[@]}")); then
args+=(--node-queue-timeout-secs "$NODE_QUEUE_TIMEOUT_SECS")
for node_target in "${NODE_QUEUE_DEVICES[@]}"; do args+=(--node-queue-devices "$node_target"); done
fi
[[ "$REQUIRE_RENAME_RANK_METRICS" != true ]] || args+=(--require-rename-rank-metrics)
if [[ -n "$SERVICE_PROMETHEUS_QUERY_URL" ]]; then
args+=(--service-prometheus-query-url "$SERVICE_PROMETHEUS_QUERY_URL" --service-metrics-dir "$cell/service_metrics")
[[ -n "$SERVICE_PROMETHEUS_QUERY" ]] && args+=(--service-prometheus-query "$SERVICE_PROMETHEUS_QUERY")
@@ -607,8 +478,9 @@ measure() {
args+=(--extra-args "--objects $((CONCURRENCY * DATASET_OBJECTS_PER_WORKER)) --noclear")
fi
[[ -n "$baseline_csv" ]] && args+=(--baseline-csv "$baseline_csv")
run_managed "$ENHANCED_BENCH" "${args[@]}" >&2 || return $?
MEASURE_CELL="$cell"
# Command substitution may clear errexit; emit a cell path only after success.
run "$ENHANCED_BENCH" "${args[@]}" >&2 || return $?
echo "$cell"
}
write_schedule_header() {
@@ -699,12 +571,6 @@ external_isolation=$(isolation_mode)
evidence_mode=$(evidence_mode)
formal_evidence=$(formal_evidence)
performance_conclusion=$(performance_conclusion)
cluster_lock_enabled=$([[ -n "$CLUSTER_LOCK_FILE" ]] && echo true || echo false)
restore_hook_enabled=$([[ -n "$RESTORE_HOOK" ]] && echo true || echo false)
hook_timeout_secs=$HOOK_TIMEOUT_SECS
node_queue_device_mappings=${#NODE_QUEUE_DEVICES[@]}
node_queue_timeout_secs=$NODE_QUEUE_TIMEOUT_SECS
require_rename_rank_metrics=$REQUIRE_RENAME_RANK_METRICS
after_probe=$AFTER_PROBE
node_docker_container_count=${#NODE_DOCKER_CONTAINERS[@]}
node_ssh_target_count=${#NODE_SSH_TARGETS[@]}
@@ -749,8 +615,7 @@ for ds_spec in "${DRIVE_SYNC_MATRIX[@]}"; do
baseline_csv="$OUT_DIR/$workload/$sync_label/A1/median_summary.csv"
fi
measure "$leg" "$workload" "$mode" "$size" "$sync_label" "$bucket" "$baseline_csv" || exit $?
cell="$MEASURE_CELL"
cell="$(measure "$leg" "$workload" "$mode" "$size" "$sync_label" "$bucket" "$baseline_csv")" || exit $?
case "$leg" in
B1|B2)
CANDIDATE_COMPARE_CSVS+=("$cell/baseline_compare.csv")
+1 -91
View File
@@ -68,9 +68,6 @@ NODE_SSH_IDENTITY_FILE=""
NODE_SSH_TIMEOUT_SECS=30
REQUIRE_NODE_TELEMETRY=false
NODE_TELEMETRY_FAILED=false
NODE_QUEUE_DEVICES=()
NODE_QUEUE_TIMEOUT_SECS=60
REQUIRE_RENAME_RANK_METRICS=false
AFTER_PROBE=false
AFTER_PROBE_DIR=""
STORAGE_QUIESCENCE_CONTAINER=""
@@ -158,12 +155,6 @@ Enhanced options:
Optional SSH private key used for node telemetry
--node-ssh-timeout-secs <n> Bound each remote telemetry command (default 30)
--require-node-telemetry Mark a round failed when any node snapshot fails
--node-queue-devices <node=dev+dev>
Wait for low queue depth on these Linux devices
across all SSH nodes before each Warp PUT attempt
--node-queue-timeout-secs <n> Bound the cluster queue wait (default: 60)
--require-rename-rank-metrics Require both rename completion ranks to advance
in the before/after service metrics snapshots
--storage-quiescence-container <container>
Require a quiet storage/writeback window from this container
--storage-quiescence-docker-context <context>
@@ -292,9 +283,6 @@ parse_args() {
--node-ssh-identity-file) NODE_SSH_IDENTITY_FILE="$2"; shift 2 ;;
--node-ssh-timeout-secs) NODE_SSH_TIMEOUT_SECS="$2"; shift 2 ;;
--require-node-telemetry) REQUIRE_NODE_TELEMETRY=true; shift ;;
--node-queue-devices) NODE_QUEUE_DEVICES+=("$2"); shift 2 ;;
--node-queue-timeout-secs) NODE_QUEUE_TIMEOUT_SECS="$2"; shift 2 ;;
--require-rename-rank-metrics) REQUIRE_RENAME_RANK_METRICS=true; shift ;;
--storage-quiescence-container) STORAGE_QUIESCENCE_CONTAINER="$2"; shift 2 ;;
--storage-quiescence-docker-context) STORAGE_QUIESCENCE_DOCKER_CONTEXT="$2"; shift 2 ;;
--storage-quiescence-consecutive) STORAGE_QUIESCENCE_CONSECUTIVE="$2"; shift 2 ;;
@@ -513,20 +501,6 @@ validate_args() {
exit 1
fi
fi
if ((${#NODE_QUEUE_DEVICES[@]})); then
if [[ "$TOOL" != warp || "$WARP_MODE" != put || -n "$STORAGE_QUIESCENCE_CONTAINER" ]]; then
echo "ERROR: node queue checks require Warp PUT and cannot be combined with Docker quiescence" >&2
exit 1
fi
cluster_queue --validate-only
fi
if [[ "$REQUIRE_RENAME_RANK_METRICS" == true ]] && {
[[ "$TOOL" != warp || "$WARP_MODE" != put ]] ||
[[ -z "$SERVICE_METRICS_URL" && -z "$SERVICE_PROMETHEUS_QUERY_URL" ]];
}; then
echo "ERROR: rename rank checks require Warp PUT and service metrics capture" >&2
exit 1
fi
validate_manifest_value "$SERVER_IMAGE_REF" "--server-image-ref"
validate_manifest_value "$SERVER_IMAGE_DIGEST" "--server-image-digest"
validate_manifest_value "$SERVER_REVISION" "--server-revision"
@@ -661,9 +635,6 @@ EOF
echo "node_ssh_timeout_secs=${NODE_SSH_TIMEOUT_SECS}"
echo "require_node_telemetry=${REQUIRE_NODE_TELEMETRY}"
echo "after_probe=${AFTER_PROBE}"
echo "node_queue_device_mappings=${#NODE_QUEUE_DEVICES[@]}"
echo "node_queue_timeout_secs=$NODE_QUEUE_TIMEOUT_SECS"
echo "require_rename_rank_metrics=$REQUIRE_RENAME_RANK_METRICS"
echo "storage_quiescence_container=${STORAGE_QUIESCENCE_CONTAINER:-N/A}"
echo "storage_quiescence_docker_context=${STORAGE_QUIESCENCE_DOCKER_CONTEXT:-N/A}"
echo "storage_quiescence_consecutive=${STORAGE_QUIESCENCE_CONSECUTIVE}"
@@ -672,49 +643,6 @@ EOF
} >>"$manifest_file"
}
cluster_queue() {
local entry
local args=(--timeout-secs "$NODE_QUEUE_TIMEOUT_SECS" --identity-file "$NODE_SSH_IDENTITY_FILE")
for entry in "${NODE_SSH_TARGETS[@]}"; do args+=(--target "$entry"); done
for entry in "${NODE_QUEUE_DEVICES[@]}"; do args+=(--devices "$entry"); done
"$SCRIPT_DIR/wait_cluster_disk_queue.sh" "${args[@]}" "$@"
}
check_rename_rank_metrics() {
local size="$1" round="$2" attempt="$3" phase="$4" token
[[ "$REQUIRE_RENAME_RANK_METRICS" == true && "$DRY_RUN" != true ]] || return 0
token=$(metric_snapshot_token "$size" "$round" "$attempt")
local snapshots=("$SERVICE_METRICS_DIR/${token}_before.prom")
if [[ "$phase" == after ]]; then snapshots+=("$SERVICE_METRICS_DIR/${token}_after.prom"); fi
if ! LC_ALL=C awk '
/^rustfs_s3_put_object_rename_disk_wait_completion_ms_count\{/ {
close_at=match($0,/\}[[:space:]]+/)
if (!close_at) next
series=substr($0,1,close_at)
if (series ~ /[{,]position="quorum_first"[,}]/) rank="first"
else if (series ~ /[{,]position="quorum_tail"[,}]/) rank="tail"
else next
split(substr($0,close_at+RLENGTH),fields,/[[:space:]]+/)
if (fields[1] !~ /^[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?$/) { bad=1; next }
if (FILENAME==ARGV[1]) {
if (series in before) bad=1
before[series]=fields[1]+0
present[rank]=1
} else {
if (!(series in before) || seen[series]++ || fields[1]+0 < before[series]) bad=1
else if (fields[1]+0 > before[series]) grew[rank]=1
}
}
END {
if (ARGC>2) for (series in before) if (!seen[series]) bad=1
exit (bad || !present["first"] || !present["tail"] || (ARGC>2 && (!grew["first"] || !grew["tail"])))
}
' "${snapshots[@]}"; then
echo "ERROR: incomplete rename rank metrics for $size round=$round attempt=$attempt phase=$phase" >&2
return 1
fi
}
wait_for_storage_quiescence() {
local size="$1" round="$2" attempt="$3" output_file
if [[ -z "$STORAGE_QUIESCENCE_CONTAINER" ]]; then
@@ -1326,7 +1254,7 @@ capture_round_node_telemetry() {
echo "$size,$TOOL,$round,$attempt,$phase,$node,$host,not_run_dry_run,$snapshot_file" >>"$NODE_SSH_CSV"
continue
fi
if timeout --foreground --kill-after=1s "$NODE_SSH_TIMEOUT_SECS" ssh "${ssh_args[@]}" "$host" 'set -u
if timeout "$NODE_SSH_TIMEOUT_SECS" ssh "${ssh_args[@]}" "$host" 'set -u
pid="$(pgrep -o -f /usr/local/bin/rustfs || true)"
echo "captured_at_utc=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "pid=${pid:-N/A}"
@@ -1484,19 +1412,6 @@ run_one_attempt() {
capture_round_node_telemetry "$size" "$round" "$attempt" before
if [[ "$TOOL" == "warp" ]]; then
if ! check_rename_rank_metrics "$size" "$round" "$attempt" before || {
[[ "$DRY_RUN" != true ]] && ((${#NODE_QUEUE_DEVICES[@]})) &&
! cluster_queue >"$OUT_DIR/node_telemetry/queue_${size}_r${round}_a${attempt}.tsv";
}; then
finished_at_utc="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
: >"$log_file"
echo "$size,$TOOL,$round,$attempt,$CONCURRENCY,failed,1,$started_at_utc,$finished_at_utc,N/A,N/A,N/A,N/A,N/A,$log_file,N/A,N/A,N/A,N/A" >> "$ROUND_CSV"
echo "failed"
return
fi
if [[ "$DRY_RUN" != true ]] && ((${#NODE_QUEUE_DEVICES[@]})); then
started_at_utc="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi
local warp_host bucket
warp_host="$(normalize_warp_host "$ENDPOINT")"
bucket="$(bucket_for_size "$size")"
@@ -1516,7 +1431,6 @@ run_one_attempt() {
if [[ "$AFTER_PROBE" == "true" && "$WARP_MODE" == "put" ]]; then
cmd+=("--noclear")
fi
if [[ "$ENDPOINT" == https://* ]]; then cmd+=("--tls"); fi
if [[ "$INSECURE" == "true" ]]; then
cmd+=("--insecure")
fi
@@ -1580,10 +1494,6 @@ run_one_attempt() {
status="failed"
exit_code=1
fi
if [[ "$status" == ok ]] && ! check_rename_rank_metrics "$size" "$round" "$attempt" after; then
status="failed"
exit_code=1
fi
if ! capture_after_probe "$size" "$round" "$attempt"; then
status="failed"
exit_code=1
+2 -105
View File
@@ -322,7 +322,7 @@ for bad_field in leg phase bucket binary_sha256 dataset_reset; do
rg -qx 'performance_conclusion=not_claimed_gate_and_artifacts_required' "$bad_out_dir/manifest.env"
done
# Exercise failure propagation with a failing load driver.
# Exercise the actual command-substitution path with a failing load driver.
FAILURE_REPO="$TMP_DIR/failed-driver-repo"
mkdir -p "$FAILURE_REPO/scripts" "$FAILURE_REPO/bin"
git init -q "$FAILURE_REPO"
@@ -336,14 +336,7 @@ while [[ $# -gt 0 ]]; do
fi
shift
done
if [[ "${DRIVER_HANG:-false}" == true ]]; then
sleep 60 &
child=$!
trap 'wait "$child" 2>/dev/null || true; exit 143' TERM
printf '%s\n' "$child" > "$DRIVER_PID_FILE"
wait "$child"
fi
exit "${DRIVER_STATUS:-42}"
exit 42
DRIVER
cat >"$FAILURE_REPO/scripts/hotpath_warp_ab_gate.sh" <<'GATE'
#!/usr/bin/env bash
@@ -376,8 +369,6 @@ cat >"$FAILURE_REPO/deploy.sh" <<'DEPLOY'
#!/usr/bin/env bash
set -euo pipefail
echo "deploy:$HOTPATH_ABBA_LEG" >>"$FAILURE_TRACE"
if [[ "${DEPLOY_HANG:-false}" == true ]]; then exec sleep 60; fi
if [[ "${DEPLOY_STATUS:-0}" != 0 ]]; then exit "$DEPLOY_STATUS"; fi
cat >"$HOTPATH_ABBA_DEPLOY_EVIDENCE_FILE" <<EOF
leg=$HOTPATH_ABBA_LEG
phase=$HOTPATH_ABBA_PHASE
@@ -442,98 +433,4 @@ for failure_mode in external local; do
[[ ! -e "$FAILURE_OUT_DIR/baseline_drift_gate.md" ]]
done
# Managed lifecycle checks use actual locks and process groups on Linux.
if command -v flock >/dev/null 2>&1; then
export MANAGED_LOCK="$TMP_DIR/cluster.lock"
cat > "$FAILURE_REPO/restore.sh" <<'RESTORE'
#!/usr/bin/env bash
set -euo pipefail
test -d "$HOTPATH_ABBA_OUT_DIR"
test -n "$HOTPATH_ABBA_DATASET_NAMESPACE"
if flock -n "$MANAGED_LOCK" true; then
echo "expected the controller to still own the lock during restore" >&2
exit 1
fi
if [[ -n "${DRIVER_PID_FILE:-}" && -f "$DRIVER_PID_FILE" ]]; then
read -r pid < "$DRIVER_PID_FILE"
if kill -0 "$pid" 2>/dev/null; then
echo "the measured workload survived interruption" >&2
exit 1
fi
fi
echo restore >> "$FAILURE_TRACE"
exit "${RESTORE_STATUS:-0}"
RESTORE
chmod +x "$FAILURE_REPO/restore.sh"
run_managed_fixture() (
local scenario="$1"
shift
cd "$FAILURE_REPO"
export PATH="$FAILURE_REPO/bin:$PATH" FAILURE_TRACE="$TMP_DIR/managed-$scenario.trace"
if [[ -n "${RUNNER_PID_FILE:-}" ]]; then printf "%s\n" "$BASHPID" > "$RUNNER_PID_FILE"; fi
exec "$RUNNER" --baseline-bin "$FAILURE_REPO/bin/rustfs" --candidate-bin "$FAILURE_REPO/bin/rustfs" \
--baseline-revision baseline-test --candidate-revision candidate-test --warp-bin /usr/bin/true \
--endpoint 'https://localhost:9000' --deploy-hook "$FAILURE_REPO/deploy.sh" \
--cluster-lock-file "$MANAGED_LOCK" --restore-hook "$FAILURE_REPO/restore.sh" \
--workload 'put-32kib|put|32KiB' --drive-sync 'sync-on|true' \
--out-dir "$TMP_DIR/managed-$scenario" "$@"
)
(
exec 8>>"$MANAGED_LOCK"
flock -n 8
if run_managed_fixture busy >"$TMP_DIR/managed-busy.log" 2>&1; then
echo "expected an occupied cluster lock to fail" >&2
exit 1
fi
test ! -e "$TMP_DIR/managed-busy.trace"
)
for scenario in driver-error deploy-error success restore-error; do
expected=0
driver=0
deploy=0
restore=0
case "$scenario" in
driver-error) driver=42; expected=42 ;;
deploy-error) deploy=43; expected=43 ;;
restore-error) restore=1; expected=1 ;;
esac
status=0
DRIVER_STATUS="$driver" DEPLOY_STATUS="$deploy" RESTORE_STATUS="$restore" \
run_managed_fixture "$scenario" >"$TMP_DIR/managed-$scenario.log" 2>&1 || status=$?
[[ "$status" == "$expected" ]]
[[ "$(grep -cx restore "$TMP_DIR/managed-$scenario.trace")" == 1 ]]
[[ "$(tail -1 "$TMP_DIR/managed-$scenario.trace")" == restore ]]
grep -qx "exit_code=$restore" "$TMP_DIR/managed-$scenario/restore.status"
if [[ "$scenario" == deploy-error ]]; then
[[ "$(cat "$TMP_DIR/managed-$scenario.trace")" == $'deploy:A1\nrestore' ]]
fi
flock -n "$MANAGED_LOCK" true
done
status=0
DEPLOY_HANG=true run_managed_fixture hook-timeout --hook-timeout-secs 1 >"$TMP_DIR/managed-timeout.log" 2>&1 || status=$?
[[ "$status" == 124 ]]
[[ "$(cat "$TMP_DIR/managed-hook-timeout.trace")" == $'deploy:A1\nrestore' ]]
flock -n "$MANAGED_LOCK" true
export DRIVER_PID_FILE="$TMP_DIR/managed-driver.pid" RUNNER_PID_FILE="$TMP_DIR/managed-runner.pid"
DRIVER_HANG=true run_managed_fixture interrupt >"$TMP_DIR/managed-interrupt.log" 2>&1 &
runner_pid=$!
for ((i=0; i<500; i++)); do
[[ -s "$DRIVER_PID_FILE" ]] && break
kill -0 "$runner_pid" 2>/dev/null || break
sleep 0.01
done
test -s "$DRIVER_PID_FILE"
read -r controller_pid < "$RUNNER_PID_FILE"
kill -TERM "$controller_pid"
status=0
wait "$runner_pid" || status=$?
[[ "$status" == 143 ]]
[[ "$(cat "$TMP_DIR/managed-interrupt.trace")" == $'deploy:A1\nmeasure:A1\nrestore' ]]
! grep -q 'restore hook failed' "$TMP_DIR/managed-interrupt.log"
flock -n "$MANAGED_LOCK" true
fi
echo "hotpath warp ABBA tests passed"
@@ -271,102 +271,4 @@ done
--compare-csv "${TMP_DIR}/fake-warp-zero-candidate/baseline_compare.csv" \
--require-tail-error >/dev/null
GUARD_BIN="$TMP_DIR/guard-bin"
mkdir "$GUARD_BIN"
cat > "$GUARD_BIN/ssh" <<'SSH'
#!/usr/bin/env bash
set -euo pipefail
command="${*: -1}"
if [[ "$command" != devices=* ]]; then
printf 'telemetry fixture\n'
exit 0
fi
host="${@: -2:1}"
marker="$GUARD_DIR/$host"
case "${QUEUE_FIXTURE:-quiet}" in
missing) exit 2 ;;
hung) exec sleep 60 ;;
reset)
n=0
[[ ! -f "$marker" ]] || read -r n < "$marker"
n=$((n+1))
printf '%s\n' "$n" > "$marker"
if [[ "$host" == host-b && "$n" == 2 ]]; then
echo '0.050000 0.800000'
exit 0
fi
;;
esac
echo '0.050000 0.070000'
SSH
cat > "$GUARD_BIN/curl" <<'CURL'
#!/usr/bin/env bash
set -euo pipefail
first=10
tail=3
if [[ -e "$GUARD_DIR/warp-called" ]]; then
first=12; tail=4
case "${RANK_FIXTURE:-valid}" in
reset) tail=2 ;;
stale) tail=3 ;;
esac
fi
metric=rustfs_s3_put_object_rename_disk_wait_completion_ms_count
printf '%s{position="quorum_first"} %s\n' "$metric" "$first"
if [[ "${RANK_FIXTURE:-valid}" != missing ]]; then
printf '%s{position="quorum_tail"} %s\n' "$metric" "$tail"
fi
CURL
cat > "$GUARD_BIN/warp" <<'WARP'
#!/usr/bin/env bash
set -euo pipefail
[[ " $* " == *" --tls "* ]]
touch "$GUARD_DIR/warp-called"
exec "$GUARD_FAKE_WARP" "$@"
WARP
chmod +x "$GUARD_BIN/"*
export GUARD_DIR="$TMP_DIR" GUARD_FAKE_WARP="$FAKE_WARP"
guard_args=(--tool warp --warp-mode put --warp-bin "$GUARD_BIN/warp"
--endpoint https://localhost:9000 --access-key test --secret-key fixture --sizes 32KiB
--rounds 1 --retry-per-round 1 --retry-sleep-secs 1 --cooldown-secs 0 --duration 1s
--node-ssh-target a=host-a --node-ssh-target b=host-b
--node-queue-devices a=nvme0n1+nvme1n1 --node-queue-devices b=nvme0n1+nvme1n1
--service-metrics-url http://localhost:9001/metrics --service-metrics-dir "$TMP_DIR/guard-metrics"
--require-rename-rank-metrics)
if ! PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE=reset "$RUNNER" "${guard_args[@]}" --out-dir "$TMP_DIR/guard-pass" >"$TMP_DIR/guard-pass.log" 2>&1; then
cat "$TMP_DIR/guard-pass.log" >&2
exit 1
fi
test -f "$GUARD_DIR/warp-called"
awk -F '\t' 'NR>1{last=$1; n++} END{exit !(last==4 && n==8)}' "$TMP_DIR/guard-pass/node_telemetry/queue_32KiB_r1_a1.tsv"
rg -q ',ok,0,' "$TMP_DIR/guard-pass/round_results.csv"
for fixture in missing-rank reset-rank stale-rank missing-node; do
rm -f "$GUARD_DIR/warp-called"
if [[ "$fixture" == missing-node ]]; then
rank=valid
queue=missing
else
rank="${fixture%-rank}"
queue=quiet
fi
if PATH="$GUARD_BIN:$PATH" RANK_FIXTURE="$rank" QUEUE_FIXTURE="$queue" "$RUNNER" \
"${guard_args[@]}" --out-dir "$TMP_DIR/$fixture" >"$TMP_DIR/$fixture.log" 2>&1; then
echo "expected $fixture to fail the round" >&2
exit 1
fi
rg -q ',failed,1,' "$TMP_DIR/$fixture/round_results.csv"
case "$fixture" in
missing-rank|missing-node) test ! -e "$GUARD_DIR/warp-called" ;;
*) test -f "$GUARD_DIR/warp-called" ;;
esac
done
if PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE=hung "$SCRIPT_DIR/wait_cluster_disk_queue.sh" \
--target a=host-a --devices a=nvme0n1 --timeout-secs 11 >"$TMP_DIR/queue-timeout.log" 2>&1; then
echo "expected an unresponsive SSH sample to time out" >&2
exit 1
fi
rg -q 'failed or timed out' "$TMP_DIR/queue-timeout.log"
echo "object batch benchmark enhanced tests passed"
-144
View File
@@ -1,144 +0,0 @@
#!/usr/bin/env bash
# Wait for two consecutive low-queue samples across the SSH inventory.
set -euo pipefail
export LC_ALL=C
targets=()
mappings=()
identity=""
budget=60
validate_only=false
while (($#)); do
case "$1" in
--validate-only) validate_only=true; shift; continue ;;
--target|--devices|--identity-file|--timeout-secs)
[[ $# -ge 2 ]] || { echo "missing value for $1" >&2; exit 2; }
case "$1" in
--target) targets+=("$2") ;;
--devices) mappings+=("$2") ;;
--identity-file) identity="$2" ;;
--timeout-secs) budget="$2" ;;
esac
shift 2 ;;
*) echo "unknown disk queue option: $1" >&2; exit 2 ;;
esac
done
if ! [[ "$budget" =~ ^[1-9][0-9]{0,5}$ ]] || ((budget < 11)); then
echo "disk queue timeout must be at least 11 seconds" >&2
exit 2
fi
(("${#targets[@]}" > 0 && "${#targets[@]}" == "${#mappings[@]}")) || { echo "disk queue check requires one device mapping per SSH target" >&2; exit 2; }
nodes=""
hosts=""
device_lists=()
for target in "${targets[@]}"; do
[[ "$target" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*=[A-Za-z0-9][A-Za-z0-9@._:%+-]*$ ]] || { echo "invalid disk queue SSH target" >&2; exit 2; }
node="${target%%=*}"
host="${target#*=}"
[[ "$nodes" != *" $node "* ]] || { echo "duplicate disk queue node: $node" >&2; exit 2; }
[[ "$hosts" != *" $host "* ]] || { echo "duplicate disk queue SSH host: $host" >&2; exit 2; }
hosts="$hosts $host "
nodes="$nodes $node "
matches=0
for mapping in "${mappings[@]}"; do
[[ "${mapping%%=*}" == "$node" ]] || continue
[[ "$mapping" =~ ^[^=]+=([A-Za-z0-9][A-Za-z0-9._-]*)(\+[A-Za-z0-9][A-Za-z0-9._-]*)*$ ]] || { echo "invalid device list for $node" >&2; exit 2; }
devices="${mapping#*=}"
if ! awk -v devices="$devices" 'BEGIN { n=split(devices,d,"+"); for(i=1;i<=n;i++) if(seen[d[i]]++) exit 1 }'; then
echo "duplicate disk queue device for $node" >&2; exit 2
fi
device_lists+=("${devices//+/ }")
matches=$((matches+1))
done
[[ "$matches" == 1 ]] || { echo "expected one device mapping for $node" >&2; exit 2; }
done
[[ "$validate_only" == false ]] || exit 0
ssh_args=(-o BatchMode=yes -o ConnectTimeout=5)
if [[ -n "$identity" ]]; then ssh_args+=(-i "$identity"); fi
artifacts=$(mktemp -d)
pids=()
cleanup() {
local pid
if ((${#pids[@]})); then
kill -TERM "${pids[@]}" 2>/dev/null || true
for pid in "${pids[@]}"; do wait "$pid" 2>/dev/null || true; done
fi
rm -rf -- "$artifacts"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
# Only validated device names are placed in the SSH command. The sampler uses
# monotonic uptime and the weighted I/O milliseconds from /proc/diskstats.
sample=$(cat <<'REMOTE'
set -eu
export LC_ALL=C
snapshot() {
awk -v devices="$devices" '
BEGIN { n=split(devices,d," "); for(i=1;i<=n;i++) want[d[i]]=1 }
FNR==NR { t=$1; next }
$3 in want {
if (NF<14 || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14
got++
}
END { if (got!=n) exit 2 }
' /proc/uptime /proc/diskstats
}
before=$(snapshot)
sleep 5
after=$(snapshot)
printf '%s\n--\n%s\n' "$before" "$after" | awk '
$0=="--" { second=1; next }
!second { if ($1 in t) bad=1; t[$1]=$2; w[$1]=$3; count++; next }
{ if (!($1 in t) || seen[$1]++ || $2<=t[$1] || $3<w[$1]) { bad=1; next }
q=($3-w[$1])/(1000*($2-t[$1])); sum+=q; if(q>peak)peak=q; got++ }
END { if (bad||!count||got!=count) exit 2; printf "%.6f %.6f\n",sum/count,peak }
'
REMOTE
)
end=$((SECONDS+budget))
streak=0
sample_number=0
printf 'sample\tnode\tmean_queue\tpeak_queue\n'
while ((end-SECONDS >= 5)); do
sample_number=$((sample_number+1))
remaining=$((end-SECONDS))
for i in "${!targets[@]}"; do
timeout --foreground --kill-after=1s "${remaining}s" ssh "${ssh_args[@]}" -- "${targets[i]#*=}" \
"devices='${device_lists[i]}'; $sample" >"$artifacts/$i" &
pids+=("$!")
done
valid=true
for pid in "${pids[@]}"; do
if ! wait "$pid"; then valid=false; fi
done
pids=()
if [[ "$valid" != true ]]; then
echo "disk queue sample failed or timed out" >&2
exit 1
fi
quiet=true
for i in "${!targets[@]}"; do
result=$(cat "$artifacts/$i")
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([0-9]+\.[0-9]+)$ ]]; then
echo "invalid disk queue sample from ${targets[i]%%=*}" >&2; exit 1
fi
mean="${BASH_REMATCH[1]}"
peak="${BASH_REMATCH[2]}"
printf '%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak"
if ! awk -v mean="$mean" -v peak="$peak" 'BEGIN {exit !(mean<=0.25 && peak<=0.75)}'; then quiet=false; fi
done
if [[ "$quiet" == true ]]; then
streak=$((streak+1))
if ((streak == 2 && SECONDS <= end)); then exit 0; fi
else
streak=0
fi
done
echo "disk queues did not settle within ${budget}s" >&2
exit 1