mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-30 12:53:08 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1d3499b72f | |||
| deea5040a9 | |||
| d82bf5b1f5 | |||
| c09643a2d9 | |||
| f6cee83802 | |||
| 840582da85 | |||
| ff4f38b1b2 | |||
| 1b557aa336 | |||
| b25cc96157 |
Generated
+57
-57
@@ -5100,7 +5100,7 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
|
||||
|
||||
[[package]]
|
||||
name = "e2e_test"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-compression",
|
||||
@@ -11566,7 +11566,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
@@ -11749,7 +11749,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-audit"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"const-str",
|
||||
"futures",
|
||||
@@ -11771,7 +11771,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-checksums"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -11786,7 +11786,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-common"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"metrics",
|
||||
@@ -11800,7 +11800,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-concurrency"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"insta",
|
||||
"rustfs-io-core",
|
||||
@@ -11812,7 +11812,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-config"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"const-str",
|
||||
"serde",
|
||||
@@ -11821,7 +11821,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-connect-symbol-catalog"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"hex-simd",
|
||||
"object 0.41.0",
|
||||
@@ -11833,7 +11833,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-credentials"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"hmac 0.13.0",
|
||||
@@ -11846,7 +11846,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-crypto"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"argon2",
|
||||
@@ -11866,7 +11866,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-cuobject"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"parking_lot 0.13.0",
|
||||
@@ -11877,7 +11877,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-cuobject-sys"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"cxx",
|
||||
"cxx-build",
|
||||
@@ -11886,7 +11886,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-data-usage"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"hotpath",
|
||||
"rmp-serde",
|
||||
@@ -11923,7 +11923,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-ecstore"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-channel",
|
||||
@@ -12062,7 +12062,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-extension-schema"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -12071,7 +12071,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-filemeta"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"base64-simd",
|
||||
@@ -12130,7 +12130,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-gateway-adapter"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"http 1.5.0",
|
||||
@@ -12293,7 +12293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-heal"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64-simd",
|
||||
@@ -12334,7 +12334,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-heal-contracts"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -12344,7 +12344,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-iam"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -12394,7 +12394,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-io-core"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"metrics",
|
||||
@@ -12406,7 +12406,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-io-metrics"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"metrics",
|
||||
@@ -12469,7 +12469,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-keystone"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures",
|
||||
@@ -12495,7 +12495,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-kms"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
@@ -12545,14 +12545,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-license"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-lifecycle"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"hotpath",
|
||||
@@ -12574,7 +12574,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-lock"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"compact_str",
|
||||
@@ -12598,7 +12598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-log-analyzer"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"jiff 1.0.3",
|
||||
@@ -12616,7 +12616,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-madmin"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"http 1.5.0",
|
||||
"humantime",
|
||||
@@ -12652,7 +12652,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-nixl"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aws-credential-types",
|
||||
"aws-sigv4",
|
||||
@@ -12673,7 +12673,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-notify"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -12709,7 +12709,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-object-capacity"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"futures",
|
||||
@@ -12728,7 +12728,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-object-data-cache"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"criterion",
|
||||
@@ -12744,7 +12744,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-obs"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
"crossbeam-deque",
|
||||
@@ -12806,7 +12806,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-policy"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64-simd",
|
||||
@@ -12836,7 +12836,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-protocols"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"async-trait",
|
||||
@@ -12907,7 +12907,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-protos"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"flatbuffers",
|
||||
"hyper",
|
||||
@@ -12936,7 +12936,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-replication"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"bytes",
|
||||
@@ -12953,7 +12953,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-rio"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"arc-swap",
|
||||
@@ -12999,7 +12999,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-rio-v2"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"bytes",
|
||||
@@ -13021,7 +13021,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-client"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -13066,14 +13066,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-ops"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"rustfs-s3-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-types"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
@@ -13092,7 +13092,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3select-api"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-compression",
|
||||
@@ -13135,7 +13135,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3select-query"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
@@ -13156,7 +13156,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-scanner"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
@@ -13210,7 +13210,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-scanner-metrics"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"jiff 1.0.3",
|
||||
"metrics",
|
||||
@@ -13224,14 +13224,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-security-governance"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-signer"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -13250,7 +13250,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-sse"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
@@ -13278,7 +13278,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-storage-api"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"hotpath",
|
||||
@@ -13293,7 +13293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-targets"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-nats",
|
||||
@@ -13346,7 +13346,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-test-utils"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"hotpath",
|
||||
"rustfs-data-usage",
|
||||
@@ -13362,7 +13362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-tls-runtime"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"metrics",
|
||||
@@ -13400,7 +13400,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-trusted-proxies"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
@@ -13437,7 +13437,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-utils"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64-simd",
|
||||
@@ -13480,7 +13480,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-zip"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"futures",
|
||||
|
||||
+55
-55
@@ -86,7 +86,7 @@ edition = "2024"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/rustfs/rustfs"
|
||||
rust-version = "1.99.0"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
homepage = "https://rustfs.com"
|
||||
keywords = ["RustFS", "Minio", "object-storage", "filesystem", "s3"]
|
||||
categories = ["web-programming", "development-tools", "filesystem", "network-programming"]
|
||||
@@ -102,60 +102,60 @@ redundant_clone = "warn"
|
||||
|
||||
[workspace.dependencies]
|
||||
# RustFS Internal Crates
|
||||
rustfs-gateway-adapter = { path = "crates/gateway-adapter", version = "1.0.5" }
|
||||
rustfs-heal = { path = "crates/heal", version = "1.0.5" }
|
||||
rustfs-heal-contracts = { path = "crates/heal-contracts", version = "1.0.5" }
|
||||
rustfs-scanner-metrics = { path = "crates/scanner-metrics", version = "1.0.5" }
|
||||
rustfs-audit = { path = "crates/audit", version = "1.0.5" }
|
||||
rustfs-checksums = { path = "crates/checksums", version = "1.0.5" }
|
||||
rustfs-common = { path = "crates/common", version = "1.0.5" }
|
||||
rustfs-data-usage = { path = "crates/data-usage", version = "1.0.5" }
|
||||
rustfs-config = { path = "./crates/config", version = "1.0.5" }
|
||||
rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.5" }
|
||||
rustfs-credentials = { path = "crates/credentials", version = "1.0.5" }
|
||||
rustfs-crypto = { path = "crates/crypto", version = "1.0.5" }
|
||||
rustfs-cuobject = { path = "crates/cuobject", version = "1.0.5" }
|
||||
rustfs-cuobject-sys = { path = "crates/cuobject-sys", version = "1.0.5" }
|
||||
rustfs-nixl = { path = "crates/nixl", version = "1.0.5" }
|
||||
rustfs-ecstore = { path = "crates/ecstore", version = "1.0.5" }
|
||||
rustfs-filemeta = { path = "crates/filemeta", version = "1.0.5" }
|
||||
rustfs-iam = { path = "crates/iam", version = "1.0.5" }
|
||||
rustfs-keystone = { path = "crates/keystone", version = "1.0.5" }
|
||||
rustfs-license = { path = "crates/license", version = "1.0.5" }
|
||||
rustfs-lifecycle = { path = "crates/lifecycle", version = "1.0.5" }
|
||||
rustfs-kms = { path = "crates/kms", version = "1.0.5" }
|
||||
rustfs-lock = { path = "crates/lock", version = "1.0.5" }
|
||||
rustfs-madmin = { path = "crates/madmin", version = "1.0.5" }
|
||||
rustfs-notify = { path = "crates/notify", version = "1.0.5" }
|
||||
rustfs-io-metrics = { path = "crates/io-metrics", version = "1.0.5" }
|
||||
rustfs-io-core = { path = "crates/io-core", version = "1.0.5" }
|
||||
rustfs-object-capacity = { path = "crates/object-capacity", version = "1.0.5" }
|
||||
rustfs-object-data-cache = { path = "crates/object-data-cache", version = "1.0.5", default-features = false }
|
||||
rustfs-log-analyzer = { path = "crates/log-analyzer", version = "1.0.5" }
|
||||
rustfs-obs = { path = "crates/obs", version = "1.0.5" }
|
||||
rustfs-policy = { path = "crates/policy", version = "1.0.5" }
|
||||
rustfs-protos = { path = "crates/protos", version = "1.0.5" }
|
||||
rustfs-protocols = { path = "crates/protocols", version = "1.0.5" }
|
||||
rustfs-replication = { path = "crates/replication", version = "1.0.5" }
|
||||
rustfs-rio = { path = "crates/rio", version = "1.0.5" }
|
||||
rustfs-rio-v2 = { path = "crates/rio-v2", version = "1.0.5" }
|
||||
rustfs-s3-client = { path = "crates/s3-client", version = "1.0.5" }
|
||||
rustfs-s3-types = { path = "crates/s3-types", version = "1.0.5" }
|
||||
rustfs-s3-ops = { path = "crates/s3-ops", version = "1.0.5" }
|
||||
rustfs-s3select-api = { path = "crates/s3select-api", version = "1.0.5" }
|
||||
rustfs-s3select-query = { path = "crates/s3select-query", version = "1.0.5" }
|
||||
rustfs-scanner = { path = "crates/scanner", version = "1.0.5" }
|
||||
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.5" }
|
||||
rustfs-extension-schema = { path = "crates/extension-schema", version = "1.0.5" }
|
||||
rustfs-signer = { path = "crates/signer", version = "1.0.5" }
|
||||
rustfs-sse = { path = "crates/sse", version = "1.0.5" }
|
||||
rustfs-storage-api = { path = "crates/storage-api", version = "1.0.5" }
|
||||
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.5" }
|
||||
rustfs-targets = { path = "crates/targets", version = "1.0.5" }
|
||||
rustfs-test-utils = { path = "crates/test-utils", version = "1.0.5" }
|
||||
rustfs-tls-runtime = { path = "crates/tls-runtime", version = "1.0.5" }
|
||||
rustfs-utils = { path = "crates/utils", version = "1.0.5" }
|
||||
rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
|
||||
rustfs-gateway-adapter = { path = "crates/gateway-adapter", version = "1.0.8" }
|
||||
rustfs-heal = { path = "crates/heal", version = "1.0.8" }
|
||||
rustfs-heal-contracts = { path = "crates/heal-contracts", version = "1.0.8" }
|
||||
rustfs-scanner-metrics = { path = "crates/scanner-metrics", version = "1.0.8" }
|
||||
rustfs-audit = { path = "crates/audit", version = "1.0.8" }
|
||||
rustfs-checksums = { path = "crates/checksums", version = "1.0.8" }
|
||||
rustfs-common = { path = "crates/common", version = "1.0.8" }
|
||||
rustfs-data-usage = { path = "crates/data-usage", version = "1.0.8" }
|
||||
rustfs-config = { path = "./crates/config", version = "1.0.8" }
|
||||
rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.8" }
|
||||
rustfs-credentials = { path = "crates/credentials", version = "1.0.8" }
|
||||
rustfs-crypto = { path = "crates/crypto", version = "1.0.8" }
|
||||
rustfs-cuobject = { path = "crates/cuobject", version = "1.0.8" }
|
||||
rustfs-cuobject-sys = { path = "crates/cuobject-sys", version = "1.0.8" }
|
||||
rustfs-nixl = { path = "crates/nixl", version = "1.0.8" }
|
||||
rustfs-ecstore = { path = "crates/ecstore", version = "1.0.8" }
|
||||
rustfs-filemeta = { path = "crates/filemeta", version = "1.0.8" }
|
||||
rustfs-iam = { path = "crates/iam", version = "1.0.8" }
|
||||
rustfs-keystone = { path = "crates/keystone", version = "1.0.8" }
|
||||
rustfs-license = { path = "crates/license", version = "1.0.8" }
|
||||
rustfs-lifecycle = { path = "crates/lifecycle", version = "1.0.8" }
|
||||
rustfs-kms = { path = "crates/kms", version = "1.0.8" }
|
||||
rustfs-lock = { path = "crates/lock", version = "1.0.8" }
|
||||
rustfs-madmin = { path = "crates/madmin", version = "1.0.8" }
|
||||
rustfs-notify = { path = "crates/notify", version = "1.0.8" }
|
||||
rustfs-io-metrics = { path = "crates/io-metrics", version = "1.0.8" }
|
||||
rustfs-io-core = { path = "crates/io-core", version = "1.0.8" }
|
||||
rustfs-object-capacity = { path = "crates/object-capacity", version = "1.0.8" }
|
||||
rustfs-object-data-cache = { path = "crates/object-data-cache", version = "1.0.8", default-features = false }
|
||||
rustfs-log-analyzer = { path = "crates/log-analyzer", version = "1.0.8" }
|
||||
rustfs-obs = { path = "crates/obs", version = "1.0.8" }
|
||||
rustfs-policy = { path = "crates/policy", version = "1.0.8" }
|
||||
rustfs-protos = { path = "crates/protos", version = "1.0.8" }
|
||||
rustfs-protocols = { path = "crates/protocols", version = "1.0.8" }
|
||||
rustfs-replication = { path = "crates/replication", version = "1.0.8" }
|
||||
rustfs-rio = { path = "crates/rio", version = "1.0.8" }
|
||||
rustfs-rio-v2 = { path = "crates/rio-v2", version = "1.0.8" }
|
||||
rustfs-s3-client = { path = "crates/s3-client", version = "1.0.8" }
|
||||
rustfs-s3-types = { path = "crates/s3-types", version = "1.0.8" }
|
||||
rustfs-s3-ops = { path = "crates/s3-ops", version = "1.0.8" }
|
||||
rustfs-s3select-api = { path = "crates/s3select-api", version = "1.0.8" }
|
||||
rustfs-s3select-query = { path = "crates/s3select-query", version = "1.0.8" }
|
||||
rustfs-scanner = { path = "crates/scanner", version = "1.0.8" }
|
||||
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.8" }
|
||||
rustfs-extension-schema = { path = "crates/extension-schema", version = "1.0.8" }
|
||||
rustfs-signer = { path = "crates/signer", version = "1.0.8" }
|
||||
rustfs-sse = { path = "crates/sse", version = "1.0.8" }
|
||||
rustfs-storage-api = { path = "crates/storage-api", version = "1.0.8" }
|
||||
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.8" }
|
||||
rustfs-targets = { path = "crates/targets", version = "1.0.8" }
|
||||
rustfs-test-utils = { path = "crates/test-utils", version = "1.0.8" }
|
||||
rustfs-tls-runtime = { path = "crates/tls-runtime", version = "1.0.8" }
|
||||
rustfs-utils = { path = "crates/utils", version = "1.0.8" }
|
||||
rustfs-zip = { path = "./crates/zip", version = "1.0.8" }
|
||||
rustfs-dst-runtime = { path = "vendor/rustfs-dst-runtime", default-features = false }
|
||||
rustfs-dst-faults = { path = "vendor/rustfs-dst-faults", default-features = false }
|
||||
|
||||
|
||||
@@ -11,9 +11,9 @@ use std::fs::{self, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::Path;
|
||||
|
||||
const MAX_BINARY_BYTES: u64 = 1_073_741_824;
|
||||
const MAX_CATALOG_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_SYMBOLS: usize = 200_000;
|
||||
const MAX_BINARY_BYTES: u64 = 2 * 1_073_741_824;
|
||||
const MAX_CATALOG_BYTES: usize = 128 * 1024 * 1024;
|
||||
const MAX_SYMBOLS: usize = 500_000;
|
||||
const NORMALIZATION: &str = "pyroscope-2.1.1-symbolic-demangle-13.9.0";
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -251,13 +251,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn release_sized_catalog_retains_all_function_names() {
|
||||
let binary = bulk_executable(110_000, 160);
|
||||
// Exercises above the observed release GNU binary footprint (~268,737 symbols / ~62.5 MiB JSON).
|
||||
let binary = bulk_executable(280_000, 200);
|
||||
let encoded = catalog(&binary, &"a".repeat(40), "x86_64-unknown-linux-gnu", vec!["pyroscope".into()])
|
||||
.expect("retain complete bounded symbol catalog");
|
||||
assert!(encoded.len() > 16 * 1024 * 1024);
|
||||
assert!(encoded.len() > 60 * 1024 * 1024);
|
||||
assert!(encoded.len() <= MAX_CATALOG_BYTES);
|
||||
let value: serde_json::Value = serde_json::from_slice(&encoded).expect("catalog JSON");
|
||||
assert_eq!(value["symbols"].as_array().expect("symbol array").len(), 110_000);
|
||||
assert_eq!(value["symbols"].as_array().expect("symbol array").len(), 280_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -273,7 +274,7 @@ mod tests {
|
||||
assert!(too_many.to_string().contains("reviewed symbol limit"));
|
||||
|
||||
let too_large = catalog(
|
||||
&bulk_executable(10_000, 3_500),
|
||||
&bulk_executable(38_000, 3_500),
|
||||
&source,
|
||||
"x86_64-unknown-linux-gnu",
|
||||
vec!["pyroscope".into()],
|
||||
|
||||
@@ -672,6 +672,7 @@ pub mod rio {
|
||||
}
|
||||
|
||||
pub mod rpc {
|
||||
pub use crate::cluster::rpc::{current_propagated_request_id, in_propagated_request_id, with_captured_request_id};
|
||||
#[cfg(all(feature = "test-util", feature = "internode-transport"))]
|
||||
pub mod test_util {
|
||||
/// Build a remote disk using a controlled transport and no health monitor.
|
||||
|
||||
@@ -1007,6 +1007,65 @@ fn prepare_msgpack_send_policy_with_gates(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn peer_authenticated_boot_epoch_for_addr(addr: &str) -> Option<Uuid> {
|
||||
let uri = addr.parse::<Uri>().ok()?;
|
||||
let audience = uri
|
||||
.authority()
|
||||
.and_then(|authority| normalize_tonic_rpc_audience(authority.as_str()).ok())?;
|
||||
PEER_REPLAY_STATES
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|states| states.replay.get(&audience).and_then(|state| state.boot_epoch))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn set_peer_authenticated_boot_epoch_for_addr_for_test(addr: &str, boot_epoch: Option<Uuid>) {
|
||||
let Ok(uri) = addr.parse::<Uri>() else {
|
||||
return;
|
||||
};
|
||||
let Some(Ok(audience)) = uri
|
||||
.authority()
|
||||
.map(|authority| normalize_tonic_rpc_audience(authority.as_str()))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let previous = if let Ok(mut states) = PEER_REPLAY_STATES.lock() {
|
||||
let entry = states.replay.entry(audience.clone()).or_default();
|
||||
let prev = entry.boot_epoch;
|
||||
entry.boot_epoch = boot_epoch;
|
||||
prev
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let (Some(old_epoch), Some(new_epoch)) = (previous, boot_epoch)
|
||||
&& old_epoch != new_epoch
|
||||
{
|
||||
super::internode_data_transport::on_authenticated_peer_boot_epoch_changed(&audience, old_epoch, new_epoch);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ForceBootEpochProbe;
|
||||
|
||||
/// Actively probe a peer's cryptographically authenticated boot epoch via a signed v2 gRPC `Ping`
|
||||
/// with a fresh challenge nonce (bypassing any stale v3 replay-scope epoch so a restarted peer can
|
||||
/// answer the challenge and prove its new boot epoch).
|
||||
pub(crate) async fn probe_authenticated_peer_boot_epoch_for_addr(addr: &str, timeout: Duration) -> Option<Uuid> {
|
||||
let probe = async {
|
||||
let mut client = node_service_time_out_client(addr, TonicInterceptor::Signature(gen_tonic_signature_interceptor()))
|
||||
.await
|
||||
.ok()?;
|
||||
let mut request = tonic::Request::new(rustfs_protos::proto_gen::node_service::PingRequest {
|
||||
version: 1,
|
||||
body: bytes::Bytes::new(),
|
||||
});
|
||||
request.extensions_mut().insert(ForceBootEpochProbe);
|
||||
let _ = client.ping(request).await;
|
||||
peer_authenticated_boot_epoch_for_addr(addr)
|
||||
};
|
||||
tokio::time::timeout(timeout, probe).await.ok().flatten()
|
||||
}
|
||||
|
||||
pub(crate) fn clear_peer_replay_state_for_addr(addr: &str) -> std::io::Result<()> {
|
||||
let uri = addr
|
||||
.parse::<Uri>()
|
||||
@@ -1048,6 +1107,7 @@ fn apply_peer_capabilities_response(
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn apply_peer_capabilities_response_for_connection(
|
||||
audience: String,
|
||||
sent_state: PeerReplayStateSnapshot,
|
||||
@@ -1055,17 +1115,36 @@ fn apply_peer_capabilities_response_for_connection(
|
||||
msgpack_response: Option<std::io::Result<AuthenticatedPeerMsgpackCapabilities>>,
|
||||
current_connection: Option<GrpcConnectionSnapshot>,
|
||||
) {
|
||||
apply_peer_capabilities_response_for_connection_inner(
|
||||
audience,
|
||||
sent_state,
|
||||
replay_response,
|
||||
msgpack_response,
|
||||
current_connection,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
fn apply_peer_capabilities_response_for_connection_inner(
|
||||
audience: String,
|
||||
sent_state: PeerReplayStateSnapshot,
|
||||
replay_response: std::io::Result<AuthenticatedPeerReplayCapabilities>,
|
||||
msgpack_response: Option<std::io::Result<AuthenticatedPeerMsgpackCapabilities>>,
|
||||
current_connection: Option<GrpcConnectionSnapshot>,
|
||||
force_boot_epoch_update: bool,
|
||||
) {
|
||||
let mut changed_boot_epoch: Option<(Uuid, Uuid)> = None;
|
||||
if let Ok(mut states) = PEER_REPLAY_STATES.lock() {
|
||||
let current_snapshot = states.snapshot(&audience, sent_state.connection);
|
||||
let current_state = current_snapshot.replay;
|
||||
let mut next_state = current_state;
|
||||
if let Ok(response) = &replay_response
|
||||
&& sent_state.replay.boot_epoch == current_state.boot_epoch
|
||||
&& (force_boot_epoch_update || sent_state.replay.boot_epoch == current_state.boot_epoch)
|
||||
{
|
||||
next_state.boot_epoch = Some(response.boot_epoch);
|
||||
}
|
||||
|
||||
if sent_state.replay.boot_epoch == current_state.boot_epoch {
|
||||
if force_boot_epoch_update || sent_state.replay.boot_epoch == current_state.boot_epoch {
|
||||
let response_capability = replay_response
|
||||
.as_ref()
|
||||
.ok()
|
||||
@@ -1106,6 +1185,9 @@ fn apply_peer_capabilities_response_for_connection(
|
||||
if current_state.boot_epoch != next_state.boot_epoch {
|
||||
states.msgpack_by_channel.remove(&audience);
|
||||
states.rename_batch_rejections.remove(&audience);
|
||||
if let (Some(old_epoch), Some(new_epoch)) = (current_state.boot_epoch, next_state.boot_epoch) {
|
||||
changed_boot_epoch = Some((old_epoch, new_epoch));
|
||||
}
|
||||
}
|
||||
if next_state.cache_capability == Some(PeerReplayCapability::Revoked) {
|
||||
states.rename_batch_rejections.remove(&audience);
|
||||
@@ -1133,7 +1215,10 @@ fn apply_peer_capabilities_response_for_connection(
|
||||
}
|
||||
}
|
||||
}
|
||||
states.replay.insert(audience, next_state);
|
||||
states.replay.insert(audience.clone(), next_state);
|
||||
}
|
||||
if let Some((old_epoch, new_epoch)) = changed_boot_epoch {
|
||||
super::internode_data_transport::on_authenticated_peer_boot_epoch_changed(&audience, old_epoch, new_epoch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1179,6 +1264,7 @@ where
|
||||
== Some(RPC_AUTH_VERSION_V2)
|
||||
});
|
||||
let challenge = authenticated.then(Uuid::new_v4);
|
||||
let force_boot_epoch_probe = request.extensions().get::<ForceBootEpochProbe>().is_some();
|
||||
let sent_state = request
|
||||
.extensions()
|
||||
.get::<PeerReplayStateSnapshot>()
|
||||
@@ -1210,14 +1296,16 @@ where
|
||||
.expect("static msgpack capability must be a valid header value"),
|
||||
);
|
||||
}
|
||||
if let (Some(boot_epoch), Some(timestamp), Some(content_sha256)) = (
|
||||
sent_state.replay.boot_epoch,
|
||||
request.headers().get(TIMESTAMP_HEADER).and_then(|value| value.to_str().ok()),
|
||||
request
|
||||
.headers()
|
||||
.get(RPC_CONTENT_SHA256_HEADER)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
) {
|
||||
if !force_boot_epoch_probe
|
||||
&& let (Some(boot_epoch), Some(timestamp), Some(content_sha256)) = (
|
||||
sent_state.replay.boot_epoch,
|
||||
request.headers().get(TIMESTAMP_HEADER).and_then(|value| value.to_str().ok()),
|
||||
request
|
||||
.headers()
|
||||
.get(RPC_CONTENT_SHA256_HEADER)
|
||||
.and_then(|value| value.to_str().ok()),
|
||||
)
|
||||
{
|
||||
match rpc_background_admission(request.headers()).and_then(|background| {
|
||||
gen_tonic_replay_scope_headers_with_admission(
|
||||
audience,
|
||||
@@ -1305,12 +1393,13 @@ where
|
||||
} else {
|
||||
None
|
||||
};
|
||||
apply_peer_capabilities_response_for_connection(
|
||||
apply_peer_capabilities_response_for_connection_inner(
|
||||
audience,
|
||||
sent_state,
|
||||
response_state,
|
||||
msgpack_response,
|
||||
current_connection,
|
||||
force_boot_epoch_probe,
|
||||
);
|
||||
if let Some((audience, connection, boot_epoch)) = rejection {
|
||||
remember_rename_batch_rejection(audience, connection, boot_epoch);
|
||||
|
||||
@@ -15,9 +15,42 @@
|
||||
use http::{HeaderMap, HeaderValue};
|
||||
use opentelemetry::{global, propagation::Injector, trace::TraceContextExt};
|
||||
pub(crate) use rustfs_utils::http::headers::REQUEST_ID_HEADER;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use tracing::Span;
|
||||
use tracing_opentelemetry::OpenTelemetrySpanExt;
|
||||
|
||||
tokio::task_local! {
|
||||
static PROPAGATED_REQUEST_ID: Option<Arc<str>>;
|
||||
}
|
||||
|
||||
pub fn in_propagated_request_id<T>(request_id: Option<&Arc<str>>, operation: impl FnOnce() -> T) -> T {
|
||||
PROPAGATED_REQUEST_ID.sync_scope(request_id.cloned(), operation)
|
||||
}
|
||||
|
||||
pub fn current_propagated_request_id() -> Option<Arc<str>> {
|
||||
PROPAGATED_REQUEST_ID.try_with(Clone::clone).ok().flatten()
|
||||
}
|
||||
|
||||
pub fn with_captured_request_id<F>(future: F) -> impl Future<Output = F::Output>
|
||||
where
|
||||
F: Future,
|
||||
{
|
||||
let captured = current_propagated_request_id();
|
||||
async move {
|
||||
match captured {
|
||||
Some(request_id) => PROPAGATED_REQUEST_ID.scope(Some(request_id), future).await,
|
||||
None => future.await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_request_id_or_fallback(fallback: impl FnOnce() -> String) -> String {
|
||||
current_propagated_request_id()
|
||||
.map(|id| id.to_string())
|
||||
.unwrap_or_else(fallback)
|
||||
}
|
||||
|
||||
struct HttpHeaderInjector<'a> {
|
||||
headers: &'a mut HeaderMap,
|
||||
}
|
||||
@@ -64,9 +97,10 @@ fn fallback_request_id() -> String {
|
||||
format!("req-{}", &uuid::Uuid::new_v4().to_string()[..8])
|
||||
}
|
||||
|
||||
fn propagated_request_id() -> String {
|
||||
current_trace_id()
|
||||
.map(|trace_id| format!("trace-{trace_id}"))
|
||||
pub(crate) fn propagated_request_id() -> String {
|
||||
current_propagated_request_id()
|
||||
.map(|id| id.to_string())
|
||||
.or_else(|| current_trace_id().map(|trace_id| format!("trace-{trace_id}")))
|
||||
.unwrap_or_else(fallback_request_id)
|
||||
}
|
||||
|
||||
@@ -151,6 +185,23 @@ mod tests {
|
||||
assert_eq!(headers.get(REQUEST_ID_HEADER).and_then(|v| v.to_str().ok()), Some("req-upstream-123"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_propagated_request_id_prefers_scoped_s3_request_id_across_spawns() {
|
||||
let s3_req_id: Arc<str> = Arc::from("s3-req-3390-abcd");
|
||||
let (hdr_id, spawned_id) = in_propagated_request_id(Some(&s3_req_id), || {
|
||||
let mut headers = HeaderMap::new();
|
||||
inject_request_id_into_http_headers(&mut headers);
|
||||
let hdr_id = headers
|
||||
.get(REQUEST_ID_HEADER)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(ToOwned::to_owned);
|
||||
let handle = tokio::spawn(with_captured_request_id(async { propagated_request_id() }));
|
||||
(hdr_id, handle)
|
||||
});
|
||||
assert_eq!(hdr_id.as_deref(), Some("s3-req-3390-abcd"));
|
||||
assert_eq!(spawned_id.await.expect("spawned task"), "s3-req-3390-abcd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inject_request_id_into_http_headers_uses_trace_id_when_missing() {
|
||||
let trace_id = "abcdefabcdefabcdefabcdefabcdefab";
|
||||
|
||||
@@ -12,11 +12,13 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use crate::cluster::rpc::client::{peer_authenticated_boot_epoch_for_addr, probe_authenticated_peer_boot_epoch_for_addr};
|
||||
use crate::cluster::rpc::{
|
||||
StreamResponseAuthDomain, build_auth_headers, build_put_file_auth_trailer,
|
||||
verify_ns_scanner_capability_with_checkpoint_coverage, verify_ns_scanner_capability_with_durable_progress,
|
||||
verify_ns_scanner_capability_with_tier_registry_generation, verify_ns_scanner_capability_with_usage_capabilities,
|
||||
verify_put_file_capability, verify_stream_auth_data_frame, verify_stream_auth_eof_frame,
|
||||
StreamResponseAuthDomain, build_auth_headers, build_put_file_auth_trailer, context_propagation::propagated_request_id,
|
||||
normalize_tonic_rpc_audience, verify_ns_scanner_capability_with_checkpoint_coverage,
|
||||
verify_ns_scanner_capability_with_durable_progress, verify_ns_scanner_capability_with_tier_registry_generation,
|
||||
verify_ns_scanner_capability_with_usage_capabilities, verify_put_file_capability, verify_stream_auth_data_frame,
|
||||
verify_stream_auth_eof_frame,
|
||||
};
|
||||
use crate::disk::error::{Error, Result};
|
||||
use crate::disk::{FileReader, FileWriter};
|
||||
@@ -45,7 +47,7 @@ use rustfs_rio::{
|
||||
ChunkReader, ChunkReaderBox, HttpChunkReader, HttpReader, HttpWriter, HttpWriterMemoryReservation, HttpWriterMemoryReserver,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
@@ -54,6 +56,7 @@ use std::task::{Context, Poll};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
|
||||
use tokio::sync::OnceCell;
|
||||
use tracing::{info, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[allow(
|
||||
@@ -73,6 +76,7 @@ const PUT_FILE_MAX_CAPABILITY_RESPONSE_SIZE: usize = 1024;
|
||||
const PUT_FILE_LEGACY_CAPABILITY_TTL: Duration = Duration::from_secs(30);
|
||||
pub(super) const PUT_FILE_V1_CAPABILITY_TTL: Duration = Duration::from_secs(30);
|
||||
const PUT_FILE_CAPABILITY_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const STREAM_AUTH_ROLLBACK_PROBE_TIMEOUT: Duration = Duration::from_millis(1500);
|
||||
const CONTENT_TYPE_JSON: &str = "application/json";
|
||||
const CONTENT_TYPE_MSGPACK: &str = "application/msgpack";
|
||||
|
||||
@@ -99,7 +103,11 @@ fn unsupported_transport_message(transport: &str) -> String {
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum PutFileCapabilityState {
|
||||
LegacyUntil(Instant),
|
||||
V1 { server_epoch: Uuid, revalidate_after: Instant },
|
||||
V1 {
|
||||
server_epoch: Uuid,
|
||||
peer_boot_epoch: Option<Uuid>,
|
||||
revalidate_after: Instant,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -122,6 +130,7 @@ type PutFileCapabilityProbeOutcome = std::result::Result<Option<Uuid>, PutFileCa
|
||||
struct PutFileCapabilityFlight {
|
||||
generation: u64,
|
||||
v1_was_pinned: bool,
|
||||
pinned_boot_epoch: Option<Uuid>,
|
||||
outcome: Arc<OnceCell<PutFileCapabilityProbeOutcome>>,
|
||||
}
|
||||
|
||||
@@ -145,19 +154,119 @@ static STREAM_RESPONSE_AUTH_STRICT: LazyLock<bool> =
|
||||
LazyLock::new(|| rustfs_utils::get_env_bool(ENV_INTERNODE_RPC_STREAM_AUTH_STRICT, DEFAULT_INTERNODE_RPC_STREAM_AUTH_STRICT));
|
||||
|
||||
// Once a peer proves cryptographic support for authenticated framed response streams,
|
||||
// pin it so an on-path attacker cannot strip the header and downgrade subsequent responses.
|
||||
static STREAM_AUTH_PINNED_ENDPOINTS: LazyLock<parking_lot::RwLock<HashSet<String>>> =
|
||||
LazyLock::new(|| parking_lot::RwLock::new(HashSet::new()));
|
||||
// pin it to its HMAC-authenticated gRPC boot_epoch so an on-path attacker cannot strip
|
||||
// the header and downgrade subsequent responses within the same peer incarnation, while
|
||||
// a legitimate rolling rollback (proving possession of the cluster secret with a fresh
|
||||
// boot_epoch) cleanly unpins when strict mode is disabled.
|
||||
static STREAM_AUTH_PINNED_ENDPOINTS: LazyLock<parking_lot::RwLock<HashMap<String, Option<Uuid>>>> =
|
||||
LazyLock::new(|| parking_lot::RwLock::new(HashMap::new()));
|
||||
|
||||
fn normalize_stream_auth_endpoint(endpoint: &str) -> String {
|
||||
endpoint.trim().trim_end_matches('/').to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn endpoint_matches_audience(endpoint: &str, audience: &str) -> bool {
|
||||
endpoint
|
||||
.parse::<http::Uri>()
|
||||
.ok()
|
||||
.and_then(|uri| uri.authority().map(|a| normalize_tonic_rpc_audience(a.as_str())))
|
||||
.and_then(std::result::Result::ok)
|
||||
.is_some_and(|normalized| normalized == audience)
|
||||
}
|
||||
|
||||
pub(crate) fn on_authenticated_peer_boot_epoch_changed(audience: &str, old_epoch: Uuid, new_epoch: Uuid) {
|
||||
if old_epoch == new_epoch || *STREAM_RESPONSE_AUTH_STRICT {
|
||||
return;
|
||||
}
|
||||
let mut removed_endpoints = Vec::new();
|
||||
{
|
||||
let mut pinned = STREAM_AUTH_PINNED_ENDPOINTS.write();
|
||||
pinned.retain(|endpoint, pinned_epoch| {
|
||||
let matches_peer =
|
||||
endpoint_matches_audience(endpoint, audience) && pinned_epoch.is_none_or(|epoch| epoch == old_epoch);
|
||||
if matches_peer {
|
||||
removed_endpoints.push(endpoint.clone());
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
if !removed_endpoints.is_empty() {
|
||||
info!(
|
||||
event = "internode_stream_auth_unpinned_on_peer_restart",
|
||||
audience,
|
||||
old_boot_epoch = %old_epoch,
|
||||
new_boot_epoch = %new_epoch,
|
||||
endpoints = ?removed_endpoints,
|
||||
"Unpinned internode stream auth endpoints after authenticated peer boot_epoch transition"
|
||||
);
|
||||
}
|
||||
|
||||
let matching_entries: Vec<(String, PutFileCapabilityCacheEntry)> = PUT_FILE_CAPABILITY_CACHE
|
||||
.read()
|
||||
.iter()
|
||||
.filter(|(endpoint, _)| endpoint_matches_audience(endpoint, audience))
|
||||
.map(|(endpoint, entry)| (endpoint.clone(), Arc::clone(entry)))
|
||||
.collect();
|
||||
for (endpoint, entry) in matching_entries {
|
||||
let mut state = entry.write();
|
||||
if matches!(
|
||||
state.cached,
|
||||
Some(PutFileCapabilityState::V1 { peer_boot_epoch, .. })
|
||||
if peer_boot_epoch.is_none_or(|epoch| epoch == old_epoch)
|
||||
) {
|
||||
state.cached = None;
|
||||
state.rejected_server_epoch = None;
|
||||
info!(
|
||||
event = "internode_put_file_capability_unpinned_on_peer_restart",
|
||||
endpoint,
|
||||
audience,
|
||||
old_boot_epoch = %old_epoch,
|
||||
new_boot_epoch = %new_epoch,
|
||||
"Cleared put_file v1 capability pin after authenticated peer boot_epoch transition"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pin_stream_auth_endpoint(endpoint: &str) {
|
||||
let key = normalize_stream_auth_endpoint(endpoint);
|
||||
if !key.is_empty() && !STREAM_AUTH_PINNED_ENDPOINTS.read().contains(&key) {
|
||||
STREAM_AUTH_PINNED_ENDPOINTS.write().insert(key);
|
||||
if key.is_empty() {
|
||||
return;
|
||||
}
|
||||
let current_boot_epoch = peer_authenticated_boot_epoch_for_addr(endpoint);
|
||||
let needs_update = {
|
||||
let pinned = STREAM_AUTH_PINNED_ENDPOINTS.read();
|
||||
match pinned.get(&key) {
|
||||
None => true,
|
||||
Some(stored) => current_boot_epoch.is_some() && *stored != current_boot_epoch,
|
||||
}
|
||||
};
|
||||
if needs_update {
|
||||
STREAM_AUTH_PINNED_ENDPOINTS.write().insert(key, current_boot_epoch);
|
||||
}
|
||||
}
|
||||
|
||||
fn try_unpin_if_boot_epoch_advanced(endpoint: &str, key: &str, pinned_epoch: Uuid, live_epoch: Uuid) -> bool {
|
||||
if live_epoch == pinned_epoch {
|
||||
return false;
|
||||
}
|
||||
let mut pinned = STREAM_AUTH_PINNED_ENDPOINTS.write();
|
||||
if pinned.get(key).copied() == Some(Some(pinned_epoch)) {
|
||||
pinned.remove(key);
|
||||
drop(pinned);
|
||||
info!(
|
||||
event = "internode_stream_auth_unpinned_on_peer_restart",
|
||||
request_id = %propagated_request_id(),
|
||||
endpoint,
|
||||
pinned_boot_epoch = %pinned_epoch,
|
||||
live_boot_epoch = %live_epoch,
|
||||
"Unpinned internode stream auth endpoint after verifying peer restart boot_epoch"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn should_authenticate_response_stream(endpoint: &str, response_headers: &HeaderMap, strict: bool) -> Result<bool> {
|
||||
@@ -167,7 +276,17 @@ fn should_authenticate_response_stream(endpoint: &str, response_headers: &Header
|
||||
(Some(_), _) => Err(Error::other("unsupported or duplicate internode stream response auth header")),
|
||||
(None, _) => {
|
||||
let key = normalize_stream_auth_endpoint(endpoint);
|
||||
if strict || STREAM_AUTH_PINNED_ENDPOINTS.read().contains(&key) {
|
||||
if strict {
|
||||
return Err(Error::other("internode stream response auth missing or downgraded"));
|
||||
}
|
||||
let pinned_entry = STREAM_AUTH_PINNED_ENDPOINTS.read().get(&key).copied();
|
||||
if let Some(pinned_epoch_opt) = pinned_entry {
|
||||
if let Some(pinned_epoch) = pinned_epoch_opt
|
||||
&& let Some(live_epoch) = peer_authenticated_boot_epoch_for_addr(endpoint)
|
||||
&& try_unpin_if_boot_epoch_advanced(endpoint, &key, pinned_epoch, live_epoch)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
return Err(Error::other("internode stream response auth missing or downgraded"));
|
||||
}
|
||||
Ok(false)
|
||||
@@ -175,6 +294,40 @@ fn should_authenticate_response_stream(endpoint: &str, response_headers: &Header
|
||||
}
|
||||
}
|
||||
|
||||
async fn should_authenticate_response_stream_async(endpoint: &str, response_headers: &HeaderMap, strict: bool) -> Result<bool> {
|
||||
match should_authenticate_response_stream(endpoint, response_headers, strict) {
|
||||
Ok(auth) => Ok(auth),
|
||||
Err(err) => {
|
||||
if !strict && response_headers.get(STREAM_RESPONSE_AUTH_HEADER).is_none() {
|
||||
let key = normalize_stream_auth_endpoint(endpoint);
|
||||
let pinned_epoch = STREAM_AUTH_PINNED_ENDPOINTS.read().get(&key).copied().flatten();
|
||||
if let Some(pinned_epoch) = pinned_epoch {
|
||||
let live_epoch =
|
||||
probe_authenticated_peer_boot_epoch_for_addr(endpoint, STREAM_AUTH_ROLLBACK_PROBE_TIMEOUT).await;
|
||||
if let Some(live_epoch) = live_epoch
|
||||
&& try_unpin_if_boot_epoch_advanced(endpoint, &key, pinned_epoch, live_epoch)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
// Also handle the case where the probe's ReplayScopeChannel hook already unpinned the entry.
|
||||
if !STREAM_AUTH_PINNED_ENDPOINTS.read().contains_key(&key) {
|
||||
return Ok(false);
|
||||
}
|
||||
warn!(
|
||||
event = "internode_stream_auth_downgrade_rejected",
|
||||
request_id = %propagated_request_id(),
|
||||
endpoint,
|
||||
pinned_boot_epoch = %pinned_epoch,
|
||||
live_boot_epoch = ?live_epoch,
|
||||
"Rejected missing internode stream response auth header on same or unverified peer boot_epoch"
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AuthenticatedStreamReader<R> {
|
||||
inner: R,
|
||||
endpoint: String,
|
||||
@@ -422,6 +575,7 @@ fn fresh_put_file_capability(state: Option<PutFileCapabilityState>, now: Instant
|
||||
Some(PutFileCapabilityState::V1 {
|
||||
server_epoch,
|
||||
revalidate_after,
|
||||
..
|
||||
}) if now < revalidate_after => Some(Some(server_epoch)),
|
||||
Some(PutFileCapabilityState::LegacyUntil(expires_at)) if now < expires_at => Some(None),
|
||||
Some(PutFileCapabilityState::V1 { .. }) | Some(PutFileCapabilityState::LegacyUntil(_)) | None => None,
|
||||
@@ -625,7 +779,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
let mut headers = json_headers();
|
||||
build_auth_headers(&url, &Method::GET, &mut headers)?;
|
||||
let reader = HttpReader::new_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout).await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -647,7 +803,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
let reader =
|
||||
HttpReader::new_fresh_connection_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout)
|
||||
.await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -668,7 +826,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
build_auth_headers(&url, &Method::GET, &mut headers)?;
|
||||
let reader =
|
||||
HttpChunkReader::new_with_stall_timeout(url.clone(), Method::GET, headers, None, request.stall_timeout).await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Some(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -695,7 +855,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
request.stall_timeout,
|
||||
)
|
||||
.await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Some(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -735,7 +897,9 @@ impl InternodeDataTransport for TcpHttpInternodeDataTransport {
|
||||
let reader =
|
||||
HttpReader::new_with_stall_timeout(url.clone(), Method::GET, headers, Some(request.body), request.stall_timeout)
|
||||
.await?;
|
||||
if should_authenticate_response_stream(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)? {
|
||||
if should_authenticate_response_stream_async(&request.endpoint, reader.response_headers(), *STREAM_RESPONSE_AUTH_STRICT)
|
||||
.await?
|
||||
{
|
||||
Ok(Box::new(AuthenticatedStreamReader::new(
|
||||
reader,
|
||||
request.endpoint,
|
||||
@@ -1086,9 +1250,14 @@ where
|
||||
.generation
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| Error::other("put_file capability probe generation exhausted"))?;
|
||||
let (v1_was_pinned, pinned_boot_epoch) = match state.cached {
|
||||
Some(PutFileCapabilityState::V1 { peer_boot_epoch, .. }) => (true, peer_boot_epoch),
|
||||
_ => (false, None),
|
||||
};
|
||||
let flight = PutFileCapabilityFlight {
|
||||
generation: state.generation,
|
||||
v1_was_pinned: matches!(state.cached, Some(PutFileCapabilityState::V1 { .. })),
|
||||
v1_was_pinned,
|
||||
pinned_boot_epoch,
|
||||
outcome: Arc::new(OnceCell::new()),
|
||||
};
|
||||
state.in_flight = Some(flight.clone());
|
||||
@@ -1101,6 +1270,33 @@ where
|
||||
.get_or_init(|| async { probe().await.map_err(PutFileCapabilityProbeFailure) })
|
||||
.await;
|
||||
|
||||
let rollback_verified = if matches!(outcome, Ok(None)) && flight.v1_was_pinned && !*STREAM_RESPONSE_AUTH_STRICT {
|
||||
if let Some(pinned_boot_epoch) = flight.pinned_boot_epoch {
|
||||
let cached_boot_epoch = peer_authenticated_boot_epoch_for_addr(endpoint);
|
||||
let live_boot_epoch = if cached_boot_epoch.is_some_and(|live| live != pinned_boot_epoch) {
|
||||
cached_boot_epoch
|
||||
} else {
|
||||
probe_authenticated_peer_boot_epoch_for_addr(endpoint, STREAM_AUTH_ROLLBACK_PROBE_TIMEOUT).await
|
||||
};
|
||||
let verified = live_boot_epoch.is_some_and(|live| live != pinned_boot_epoch);
|
||||
if verified {
|
||||
info!(
|
||||
event = "internode_put_file_capability_unpinned_on_peer_restart",
|
||||
request_id = %propagated_request_id(),
|
||||
endpoint,
|
||||
pinned_boot_epoch = %pinned_boot_epoch,
|
||||
live_boot_epoch = ?live_boot_epoch,
|
||||
"Allowed put_file legacy fallback after authenticated peer boot_epoch change"
|
||||
);
|
||||
}
|
||||
verified
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
{
|
||||
let mut state = entry.write();
|
||||
let is_current_flight = state
|
||||
@@ -1115,11 +1311,13 @@ where
|
||||
}
|
||||
state.cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch: *server_epoch,
|
||||
peer_boot_epoch: peer_authenticated_boot_epoch_for_addr(endpoint),
|
||||
revalidate_after: Instant::now() + PUT_FILE_V1_CAPABILITY_TTL,
|
||||
});
|
||||
}
|
||||
Ok(None) if !flight.v1_was_pinned => {
|
||||
Ok(None) if !flight.v1_was_pinned || rollback_verified => {
|
||||
state.cached = Some(PutFileCapabilityState::LegacyUntil(Instant::now() + PUT_FILE_LEGACY_CAPABILITY_TTL));
|
||||
state.rejected_server_epoch = None;
|
||||
}
|
||||
Ok(None) | Err(_) => {}
|
||||
}
|
||||
@@ -1129,7 +1327,9 @@ where
|
||||
|
||||
match outcome {
|
||||
Ok(Some(server_epoch)) => Ok(Some(*server_epoch)),
|
||||
Ok(None) if flight.v1_was_pinned => Err(Error::other("remote put_file capability downgrade rejected")),
|
||||
Ok(None) if flight.v1_was_pinned && !rollback_verified => {
|
||||
Err(Error::other("remote put_file capability downgrade rejected"))
|
||||
}
|
||||
Ok(None) => Ok(None),
|
||||
Err(failure) => Err(failure.to_error()),
|
||||
}
|
||||
@@ -1494,6 +1694,7 @@ mod tests {
|
||||
put_file_capability_cache_entry(&endpoint).write().cached = Some(if authenticated {
|
||||
PutFileCapabilityState::V1 {
|
||||
server_epoch: Uuid::new_v4(),
|
||||
peer_boot_epoch: None,
|
||||
revalidate_after: Instant::now() + PUT_FILE_V1_CAPABILITY_TTL,
|
||||
}
|
||||
} else {
|
||||
@@ -2475,6 +2676,7 @@ mod tests {
|
||||
let server_epoch = Uuid::new_v4();
|
||||
v1_entry.write().cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch,
|
||||
peer_boot_epoch: None,
|
||||
revalidate_after: Instant::now() + PUT_FILE_V1_CAPABILITY_TTL,
|
||||
});
|
||||
assert_eq!(
|
||||
@@ -2494,6 +2696,7 @@ mod tests {
|
||||
assert!(!cache_probe_called.load(Ordering::SeqCst));
|
||||
v1_entry.write().cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch,
|
||||
peer_boot_epoch: None,
|
||||
revalidate_after: Instant::now(),
|
||||
});
|
||||
assert!(
|
||||
@@ -2777,6 +2980,7 @@ mod tests {
|
||||
state.generation = state.generation.checked_add(1).expect("test generation should advance");
|
||||
state.cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch: newer_epoch,
|
||||
peer_boot_epoch: None,
|
||||
revalidate_after: Instant::now() + PUT_FILE_V1_CAPABILITY_TTL,
|
||||
});
|
||||
state.in_flight = None;
|
||||
@@ -3449,6 +3653,7 @@ mod tests {
|
||||
STREAM_AUTH_PINNED_ENDPOINTS
|
||||
.write()
|
||||
.remove(&normalize_stream_auth_endpoint(&endpoint))
|
||||
.is_some()
|
||||
);
|
||||
let mut reader = transport.open_walk_dir(walk()).await.unwrap();
|
||||
assert_eq!(reader.read_to_end(&mut Vec::new()).await.unwrap(), 0);
|
||||
@@ -3522,4 +3727,112 @@ mod tests {
|
||||
.write()
|
||||
.remove(&normalize_stream_auth_endpoint(&endpoint));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_response_auth_unpins_on_authenticated_boot_epoch_change_and_rejects_same_epoch() {
|
||||
use crate::cluster::rpc::client::{
|
||||
clear_peer_replay_state_for_addr, set_peer_authenticated_boot_epoch_for_addr_for_test,
|
||||
};
|
||||
use crate::cluster::rpc::encode_stream_auth_eof_frame;
|
||||
use std::io::Cursor;
|
||||
|
||||
crate::runtime::sources::ensure_test_rpc_secret();
|
||||
let endpoint = format!("http://rollback-epoch-{}.invalid:9000", Uuid::new_v4());
|
||||
let empty = HeaderMap::new();
|
||||
let epoch_v2 = Uuid::new_v4();
|
||||
let epoch_rolled_back = Uuid::new_v4();
|
||||
|
||||
// Peer authenticates under epoch_v2 and proves framed stream support -> pinned to epoch_v2.
|
||||
set_peer_authenticated_boot_epoch_for_addr_for_test(&endpoint, Some(epoch_v2));
|
||||
let nonce = Uuid::new_v4();
|
||||
let url = format!("{endpoint}/rustfs/rpc/read_file_stream?disk=d1&stream_auth=framed-v1&stream_auth_nonce={nonce}");
|
||||
let empty_digest: [u8; 32] = Sha256::digest([]).into();
|
||||
let eof = encode_stream_auth_eof_frame(
|
||||
StreamResponseAuthDomain::ReadFileStream,
|
||||
&url,
|
||||
&Method::GET,
|
||||
nonce,
|
||||
0,
|
||||
0,
|
||||
&empty_digest,
|
||||
)
|
||||
.expect("empty EOF");
|
||||
let mut reader = AuthenticatedStreamReader::new(
|
||||
Cursor::new(eof.to_vec()),
|
||||
endpoint.clone(),
|
||||
StreamResponseAuthDomain::ReadFileStream,
|
||||
url,
|
||||
Method::GET,
|
||||
nonce,
|
||||
);
|
||||
reader.read_to_end(&mut Vec::new()).await.expect("verified stream");
|
||||
|
||||
// Same boot_epoch + stripped header MUST still fail closed (MITM downgrade protection).
|
||||
assert!(
|
||||
should_authenticate_response_stream(&endpoint, &empty, false).is_err(),
|
||||
"header stripping within same boot_epoch must still be rejected"
|
||||
);
|
||||
// Strict mode MUST reject even after boot_epoch transition.
|
||||
set_peer_authenticated_boot_epoch_for_addr_for_test(&endpoint, Some(epoch_rolled_back));
|
||||
assert!(
|
||||
should_authenticate_response_stream(&endpoint, &empty, true).is_err(),
|
||||
"strict mode must still reject unframed stream after peer restart"
|
||||
);
|
||||
// Non-strict mode allows unframed legacy stream once peer proves a new authenticated boot_epoch.
|
||||
assert!(
|
||||
!should_authenticate_response_stream(&endpoint, &empty, false)
|
||||
.expect("authenticated peer restart should unpin stream auth in non-strict mode")
|
||||
);
|
||||
|
||||
let _ = clear_peer_replay_state_for_addr(&endpoint);
|
||||
STREAM_AUTH_PINNED_ENDPOINTS
|
||||
.write()
|
||||
.remove(&normalize_stream_auth_endpoint(&endpoint));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_file_capability_allows_rollback_on_authenticated_boot_epoch_change_and_rejects_same_epoch() {
|
||||
use crate::cluster::rpc::client::{
|
||||
clear_peer_replay_state_for_addr, set_peer_authenticated_boot_epoch_for_addr_for_test,
|
||||
};
|
||||
|
||||
crate::runtime::sources::ensure_test_rpc_secret();
|
||||
let endpoint = format!("http://put-rollback-{}.invalid:9000", Uuid::new_v4());
|
||||
let epoch_v2 = Uuid::new_v4();
|
||||
let epoch_rolled_back = Uuid::new_v4();
|
||||
let server_epoch = Uuid::new_v4();
|
||||
|
||||
set_peer_authenticated_boot_epoch_for_addr_for_test(&endpoint, Some(epoch_v2));
|
||||
assert_eq!(
|
||||
resolve_put_file_auth_capability(&endpoint, || async { Ok(Some(server_epoch)) })
|
||||
.await
|
||||
.expect("initial v1 capability"),
|
||||
Some(server_epoch)
|
||||
);
|
||||
|
||||
// Expire TTL under SAME boot_epoch -> probe returning Ok(None) (404) MUST fail closed.
|
||||
put_file_capability_cache_entry(&endpoint).write().cached = Some(PutFileCapabilityState::V1 {
|
||||
server_epoch,
|
||||
peer_boot_epoch: Some(epoch_v2),
|
||||
revalidate_after: Instant::now(),
|
||||
});
|
||||
assert!(
|
||||
resolve_put_file_auth_capability(&endpoint, || async { Ok(None) })
|
||||
.await
|
||||
.is_err(),
|
||||
"same-epoch downgrade to legacy put_file must be rejected"
|
||||
);
|
||||
|
||||
// Peer restarts and authenticates a new boot_epoch -> rollback to legacy put_file MUST succeed.
|
||||
set_peer_authenticated_boot_epoch_for_addr_for_test(&endpoint, Some(epoch_rolled_back));
|
||||
assert_eq!(
|
||||
resolve_put_file_auth_capability(&endpoint, || async { Ok(None) })
|
||||
.await
|
||||
.expect("authenticated peer restart should allow legacy put_file rollback"),
|
||||
None
|
||||
);
|
||||
|
||||
let _ = clear_peer_replay_state_for_addr(&endpoint);
|
||||
PUT_FILE_CAPABILITY_CACHE.write().remove(&endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use client::{
|
||||
AuthenticatedChannel, TonicInterceptor, gen_tonic_signature_interceptor, node_service_time_out_client,
|
||||
node_service_time_out_client_no_auth,
|
||||
};
|
||||
pub use context_propagation::{current_propagated_request_id, in_propagated_request_id, with_captured_request_id};
|
||||
// Re-exported through `api::rpc`; not every item is consumed inside this crate.
|
||||
#[allow(unused_imports)]
|
||||
pub use http_auth::{
|
||||
|
||||
@@ -63,6 +63,8 @@ pub const READ_FILE_NIXL_PATH: &str = "/rustfs/rpc/read_file_nixl";
|
||||
pub const WRITE_FILE_NIXL_PATH: &str = "/rustfs/rpc/write_file_nixl";
|
||||
/// Comma-separated buffers a NIXL shard write pulls, in file order (signed).
|
||||
pub const NIXL_BUFFERS_QUERY: &str = "nixl_buffers";
|
||||
/// Starting file offset of a NIXL shard write segment (signed).
|
||||
pub const NIXL_OFFSET_QUERY: &str = "nixl_offset";
|
||||
/// One-time nonce of a NIXL shard write (signed; recorded to refuse replays).
|
||||
pub const NIXL_NONCE_QUERY: &str = "nixl_nonce";
|
||||
/// Buffers a writer fills before it sends a segment; a part's shard file
|
||||
@@ -428,6 +430,7 @@ async fn send_segment(
|
||||
request: WriteStreamRequest,
|
||||
buffers: Vec<(LentBuffer, usize)>,
|
||||
append: bool,
|
||||
offset: Option<u64>,
|
||||
last: bool,
|
||||
timeout: Duration,
|
||||
) -> io::Result<()> {
|
||||
@@ -443,7 +446,7 @@ async fn send_segment(
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let url = format!(
|
||||
let mut url = format!(
|
||||
"{}{WRITE_FILE_NIXL_PATH}?disk={}&volume={}&path={}&append={append}&size={}&last={last}&{NIXL_NONCE_QUERY}={}&{NIXL_AGENT_QUERY}={}&{NIXL_BUFFERS_QUERY}={}&{NIXL_METADATA_SHA256_QUERY}={}",
|
||||
request.endpoint,
|
||||
urlencoding::encode(&request.disk),
|
||||
@@ -455,6 +458,9 @@ async fn send_segment(
|
||||
urlencoding::encode(&descriptors),
|
||||
pool.metadata_sha256_hex()
|
||||
);
|
||||
if let Some(offset) = offset {
|
||||
url.push_str(&format!("&{NIXL_OFFSET_QUERY}={offset}"));
|
||||
}
|
||||
let mut headers = json_headers();
|
||||
headers.insert(
|
||||
NIXL_METADATA_HEADER,
|
||||
@@ -509,6 +515,7 @@ struct WriterState {
|
||||
reserving: Option<ReserveFuture>,
|
||||
sending: Option<SegmentFuture>,
|
||||
segments_sent: usize,
|
||||
bytes_sent: u64,
|
||||
shut_down: bool,
|
||||
}
|
||||
|
||||
@@ -516,12 +523,16 @@ impl WriterState {
|
||||
fn start_segment(&mut self, last: bool) {
|
||||
let buffers = std::mem::take(&mut self.filled);
|
||||
let append = self.base.append || self.segments_sent > 0;
|
||||
let offset = (!self.base.append).then_some(self.bytes_sent);
|
||||
let segment_bytes = buffers.iter().fold(0u64, |acc, (_, len)| acc.saturating_add(*len as u64));
|
||||
self.bytes_sent = self.bytes_sent.saturating_add(segment_bytes);
|
||||
self.segments_sent += 1;
|
||||
self.sending = Some(Box::pin(send_segment(
|
||||
Arc::clone(&self.pool),
|
||||
self.base.clone(),
|
||||
buffers,
|
||||
append,
|
||||
offset,
|
||||
last,
|
||||
self.timeout,
|
||||
)));
|
||||
@@ -595,6 +606,26 @@ impl WriterState {
|
||||
}
|
||||
}
|
||||
self.shut_down = true;
|
||||
if !self.base.append
|
||||
&& let Ok(expected) = u64::try_from(self.base.size)
|
||||
{
|
||||
let pending_bytes = self.filled.iter().fold(0u64, |acc, (_, len)| acc.saturating_add(*len as u64));
|
||||
let total_bytes = self.bytes_sent.saturating_add(pending_bytes);
|
||||
if total_bytes != expected {
|
||||
debug!(
|
||||
component = LOG_COMPONENT_INTERNODE,
|
||||
subsystem = LOG_SUBSYSTEM_NIXL,
|
||||
result = "failed",
|
||||
total_bytes,
|
||||
expected,
|
||||
"nixl internode write length does not match declared size"
|
||||
);
|
||||
for (buffer, _) in std::mem::take(&mut self.filled) {
|
||||
buffer.release();
|
||||
}
|
||||
return Poll::Ready(Err(io::Error::other("nixl internode write length does not match declared size")));
|
||||
}
|
||||
}
|
||||
if !self.filled.is_empty() || self.segments_sent == 0 {
|
||||
// The last segment; with nothing written at all it still creates the file.
|
||||
self.start_segment(true);
|
||||
@@ -623,6 +654,7 @@ impl NixlFileWriter {
|
||||
reserving: None,
|
||||
sending: None,
|
||||
segments_sent: 0,
|
||||
bytes_sent: 0,
|
||||
shut_down: false,
|
||||
}),
|
||||
}
|
||||
@@ -857,6 +889,14 @@ mod tests {
|
||||
let request = std::str::from_utf8(&request).expect("request text");
|
||||
let target = request.split_whitespace().nth(1).expect("request target");
|
||||
let url = url::Url::parse(&format!("http://{address}{target}")).expect("segment URL");
|
||||
let offset = url
|
||||
.query_pairs()
|
||||
.find(|(name, _)| name == NIXL_OFFSET_QUERY)
|
||||
.expect("signed segment offset")
|
||||
.1
|
||||
.parse::<usize>()
|
||||
.expect("numeric offset");
|
||||
assert_eq!(offset, received, "each segment carries its starting file offset");
|
||||
let descriptors = url
|
||||
.query_pairs()
|
||||
.find(|(name, _)| name == NIXL_BUFFERS_QUERY)
|
||||
@@ -968,4 +1008,23 @@ mod tests {
|
||||
assert_eq!(bytes.len(), 5);
|
||||
assert_eq!(released.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shutdown_rejects_short_or_long_declared_shard_writes() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
for (declared, written) in [(20, 12usize), (12, 20usize), (0, 4usize)] {
|
||||
let request = WriteStreamRequest {
|
||||
endpoint: "http://127.0.0.1:1".to_owned(),
|
||||
disk: "disk".to_owned(),
|
||||
volume: "volume".to_owned(),
|
||||
path: "path".to_owned(),
|
||||
append: false,
|
||||
size: declared,
|
||||
};
|
||||
let mut writer = NixlFileWriter::new(Arc::new(VecPool), request);
|
||||
writer.write_all(&vec![3u8; written]).await.expect("stage bytes");
|
||||
let error = writer.shutdown().await.expect_err("mismatched declared size must fail");
|
||||
assert!(error.to_string().contains("does not match declared size"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1463,6 +1463,87 @@ fn internode_idempotent_read_retries() -> usize {
|
||||
static PREWARMED_PEERS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
|
||||
std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));
|
||||
|
||||
/// Tracks multi-disk timeout bursts per peer `addr` so that when a single host
|
||||
/// stops answering across multiple drives (e.g. `SIGSTOP` grey failure in 3x4),
|
||||
/// sibling drives on that host fast-fail instead of each paying independent 5-10s
|
||||
/// timeouts. A single disk timing out never triggers host-level fast-fail, and
|
||||
/// any successful RPC or periodic re-probe clears degradation immediately.
|
||||
#[derive(Default)]
|
||||
struct HostTimeoutDegradationState {
|
||||
timed_out_endpoints: std::collections::HashMap<String, tokio::time::Instant>,
|
||||
degraded_until: Option<tokio::time::Instant>,
|
||||
last_probe_allowed: Option<tokio::time::Instant>,
|
||||
}
|
||||
|
||||
const HOST_TIMEOUT_CORRELATION_WINDOW: Duration = Duration::from_secs(15);
|
||||
const HOST_TIMEOUT_DEGRADATION_TTL: Duration = Duration::from_secs(5);
|
||||
const HOST_TIMEOUT_REPROBE_INTERVAL: Duration = Duration::from_secs(2);
|
||||
const HOST_TIMEOUT_MIN_DISTINCT_DISKS: usize = 2;
|
||||
|
||||
static HOST_TIMEOUT_DEGRADATION: std::sync::LazyLock<
|
||||
std::sync::Mutex<std::collections::HashMap<String, HostTimeoutDegradationState>>,
|
||||
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
|
||||
|
||||
fn record_host_disk_timeout(addr: &str, endpoint: &str) {
|
||||
let now = tokio::time::Instant::now();
|
||||
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
|
||||
return;
|
||||
};
|
||||
let state = map.entry(addr.to_owned()).or_default();
|
||||
state
|
||||
.timed_out_endpoints
|
||||
.retain(|_, ts| now.saturating_duration_since(*ts) <= HOST_TIMEOUT_CORRELATION_WINDOW);
|
||||
state.timed_out_endpoints.insert(endpoint.to_owned(), now);
|
||||
if state.timed_out_endpoints.len() >= HOST_TIMEOUT_MIN_DISTINCT_DISKS {
|
||||
state.degraded_until = Some(now + HOST_TIMEOUT_DEGRADATION_TTL);
|
||||
state.last_probe_allowed.get_or_insert(now);
|
||||
}
|
||||
}
|
||||
|
||||
fn is_host_timeout_degraded(addr: &str) -> bool {
|
||||
let now = tokio::time::Instant::now();
|
||||
let Ok(map) = HOST_TIMEOUT_DEGRADATION.lock() else {
|
||||
return false;
|
||||
};
|
||||
map.get(addr)
|
||||
.and_then(|state| state.degraded_until)
|
||||
.is_some_and(|until| now < until)
|
||||
}
|
||||
|
||||
fn clear_host_timeout_degradation(addr: &str) {
|
||||
if let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() {
|
||||
map.remove(addr);
|
||||
}
|
||||
}
|
||||
|
||||
fn host_timeout_fast_fail_should_bypass(addr: &str) -> bool {
|
||||
let now = tokio::time::Instant::now();
|
||||
let Ok(mut map) = HOST_TIMEOUT_DEGRADATION.lock() else {
|
||||
return false;
|
||||
};
|
||||
let Some(state) = map.get_mut(addr) else {
|
||||
return false;
|
||||
};
|
||||
let Some(until) = state.degraded_until else {
|
||||
return false;
|
||||
};
|
||||
if now >= until {
|
||||
state.degraded_until = None;
|
||||
state
|
||||
.timed_out_endpoints
|
||||
.retain(|_, ts| now.saturating_duration_since(*ts) <= HOST_TIMEOUT_CORRELATION_WINDOW);
|
||||
return false;
|
||||
}
|
||||
if state
|
||||
.last_probe_allowed
|
||||
.is_none_or(|last| now.saturating_duration_since(last) >= HOST_TIMEOUT_REPROBE_INTERVAL)
|
||||
{
|
||||
state.last_probe_allowed = Some(now);
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn claim_control_channel_prewarm(addr: &str) -> bool {
|
||||
let Ok(mut prewarmed) = PREWARMED_PEERS.lock() else {
|
||||
return false;
|
||||
@@ -2354,6 +2435,7 @@ impl RemoteDisk {
|
||||
cancel_token: CancellationToken,
|
||||
) {
|
||||
let mut interval = time::interval(get_drive_returning_probe_interval());
|
||||
let initial_boot_epoch = crate::cluster::rpc::client::peer_authenticated_boot_epoch_for_addr(&addr);
|
||||
debug!(
|
||||
event = EVENT_REMOTE_DISK_HEALTH,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
@@ -2380,14 +2462,22 @@ impl RemoteDisk {
|
||||
}
|
||||
_ = interval.tick() => {
|
||||
if Self::perform_recovery_probe(&addr, &endpoint).await.is_ok() {
|
||||
clear_host_timeout_degradation(&addr);
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable(&addr);
|
||||
let became_online = health.mark_recovery_success(&endpoint, "disk_info_probe_success");
|
||||
let current_boot_epoch = crate::cluster::rpc::client::peer_authenticated_boot_epoch_for_addr(&addr);
|
||||
let peer_restarted = current_boot_epoch.is_some() && current_boot_epoch != initial_boot_epoch;
|
||||
let became_online = if peer_restarted {
|
||||
health.mark_peer_restarted_online(&endpoint, "peer_restarted_disk_info_probe_success")
|
||||
} else {
|
||||
health.mark_recovery_success(&endpoint, "disk_info_probe_success")
|
||||
};
|
||||
debug!(
|
||||
event = EVENT_REMOTE_DISK_HEALTH,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REMOTE_DISK,
|
||||
endpoint = %endpoint,
|
||||
addr,
|
||||
peer_restarted,
|
||||
state = "recovery_probe_succeeded",
|
||||
"Remote disk recovery probe succeeded"
|
||||
);
|
||||
@@ -2411,6 +2501,31 @@ impl RemoteDisk {
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a post-quorum straggler timeout observed during metadata fanout.
|
||||
/// Requires `HOST_TIMEOUT_MIN_DISTINCT_DISKS` (>= 2) distinct drives on the
|
||||
/// same host to time out within the correlation window, so a single slow HDD
|
||||
/// never engages host-level fast-fail while a `SIGSTOP`'d peer holding 4
|
||||
/// drives fast-fails immediately on subsequent requests.
|
||||
pub(crate) fn record_straggler_timeout(&self) {
|
||||
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
|
||||
}
|
||||
|
||||
/// On-demand bounded recovery probe used only when a read is about to fail read quorum due to
|
||||
/// `FaultyDisk` remote drives (e.g., drives waiting in `Returning` right after a rolling restart).
|
||||
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
|
||||
if !self.health.is_faulty() {
|
||||
return false;
|
||||
}
|
||||
let Ok(Ok(())) = timeout(Duration::from_millis(1000), Self::perform_recovery_probe(&self.addr, &self.endpoint)).await
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
clear_host_timeout_degradation(&self.addr);
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable(&self.addr);
|
||||
self.health
|
||||
.mark_peer_restarted_online(&self.endpoint, "on_demand_quorum_recovery_probe_success")
|
||||
}
|
||||
|
||||
async fn perform_recovery_probe(addr: &str, endpoint: &Endpoint) -> Result<()> {
|
||||
let mut evict_cached_connection = false;
|
||||
let result = match timeout(get_drive_active_check_timeout(), async {
|
||||
@@ -2528,6 +2643,9 @@ impl RemoteDisk {
|
||||
.await
|
||||
{
|
||||
Err(err) if attempt < max_retries && is_network_like_disk_error(&err) => {
|
||||
if matches!(err, DiskError::Timeout) && is_host_timeout_degraded(&self.addr) {
|
||||
return Err(err);
|
||||
}
|
||||
if matches!(err, DiskError::Timeout) && deadline.is_some_and(|deadline| time::Instant::now() >= deadline) {
|
||||
self.mark_faulty("read_operation_deadline");
|
||||
return Err(err);
|
||||
@@ -2604,6 +2722,14 @@ impl RemoteDisk {
|
||||
return Err(DiskError::FaultyDisk);
|
||||
}
|
||||
|
||||
// Host-level grey-failure fast-fail: when multiple distinct drives on the
|
||||
// same peer host recently timed out, short-circuit sibling drives (including
|
||||
// idempotent read attempts whose attempt-0 health action is IgnoreFailure)
|
||||
// so quorum operations stay sub-second while allowing periodic self-healing probes.
|
||||
if host_timeout_fast_fail_should_bypass(&self.addr) {
|
||||
return Err(DiskError::Timeout);
|
||||
}
|
||||
|
||||
// Record operation start
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
@@ -2615,6 +2741,7 @@ impl RemoteDisk {
|
||||
if timeout_duration == Duration::ZERO {
|
||||
let operation_result = operation().await;
|
||||
if operation_result.is_ok() {
|
||||
clear_host_timeout_degradation(&self.addr);
|
||||
self.health.record_operation_success(&self.endpoint, "operation_success");
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
|
||||
}
|
||||
@@ -2630,6 +2757,7 @@ impl RemoteDisk {
|
||||
Ok(operation_result) => {
|
||||
// Log success; the waiting guard balances every exit path.
|
||||
if operation_result.is_ok() {
|
||||
clear_host_timeout_degradation(&self.addr);
|
||||
self.health.record_operation_success(&self.endpoint, "operation_success");
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
|
||||
}
|
||||
@@ -2640,6 +2768,7 @@ impl RemoteDisk {
|
||||
Err(_) => {
|
||||
self.record_timeout(op, timeout_duration);
|
||||
if failure_health_action == FailureHealthAction::MarkFailure {
|
||||
record_host_disk_timeout(&self.addr, &self.endpoint.to_string());
|
||||
self.mark_faulty_and_evict("operation_timeout").await;
|
||||
}
|
||||
Err(DiskError::Timeout)
|
||||
@@ -4110,7 +4239,8 @@ impl DiskAPI for RemoteDisk {
|
||||
"Remote disk RPC started"
|
||||
);
|
||||
|
||||
self.execute_with_timeout(
|
||||
self.execute_with_timeout_for_op(
|
||||
"stat_volume",
|
||||
|| async {
|
||||
let mut client = self.get_client().await?;
|
||||
let request = Request::new(StatVolumeRequest {
|
||||
@@ -14873,4 +15003,35 @@ mod tests {
|
||||
.await;
|
||||
peer.stop().await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_timeout_fast_fail_requires_two_distinct_disks_and_clears_on_success() {
|
||||
let addr = "http://127.0.0.1:19390";
|
||||
clear_host_timeout_degradation(addr);
|
||||
|
||||
// Single disk timing out once (or repeatedly) must NOT engage host-level fast-fail.
|
||||
record_host_disk_timeout(addr, "http://127.0.0.1:19390/data1");
|
||||
record_host_disk_timeout(addr, "http://127.0.0.1:19390/data1");
|
||||
assert!(
|
||||
!host_timeout_fast_fail_should_bypass(addr),
|
||||
"single timed-out disk must not trip host-level fast-fail"
|
||||
);
|
||||
|
||||
// Second distinct disk on the same host timing out engages host-level fast-fail
|
||||
// immediately until the periodic re-probe interval elapses.
|
||||
record_host_disk_timeout(addr, "http://127.0.0.1:19390/data2");
|
||||
assert!(is_host_timeout_degraded(addr));
|
||||
assert!(
|
||||
host_timeout_fast_fail_should_bypass(addr),
|
||||
"sibling requests during degradation window must fast-fail immediately"
|
||||
);
|
||||
|
||||
// Any single successful RPC on the host clears degradation immediately.
|
||||
clear_host_timeout_degradation(addr);
|
||||
assert!(!is_host_timeout_degraded(addr));
|
||||
assert!(
|
||||
!host_timeout_fast_fail_should_bypass(addr),
|
||||
"host degradation must clear immediately after a successful RPC"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1472,6 +1472,23 @@ impl DiskHealthTracker {
|
||||
became_online
|
||||
}
|
||||
|
||||
/// Promote an offline/returning/suspect drive directly to `Online` once an authenticated peer
|
||||
/// restart (`boot_epoch` change) or quorum-critical recovery probe succeeds, avoiding a multi-second
|
||||
/// `Returning` stall during rolling upgrades and rollbacks.
|
||||
pub fn mark_peer_restarted_online(&self, endpoint: &Endpoint, reason: &'static str) -> bool {
|
||||
#[cfg(test)]
|
||||
if self.test_forced_offline.load(Ordering::Acquire) {
|
||||
return false;
|
||||
}
|
||||
let _guard = self.transition_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let current = self.runtime_state();
|
||||
self.consecutive_failures.store(0, Ordering::Release);
|
||||
self.consecutive_successes.store(0, Ordering::Release);
|
||||
self.transition_state(endpoint, current, RuntimeDriveHealthState::Online, reason);
|
||||
self.log_success();
|
||||
true
|
||||
}
|
||||
|
||||
pub fn record_operation_success(&self, endpoint: &Endpoint, reason: &'static str) {
|
||||
if self.runtime_state() == RuntimeDriveHealthState::Online {
|
||||
self.log_success();
|
||||
|
||||
@@ -62,14 +62,15 @@ use crate::disk::{
|
||||
DeleteOptions, DeleteRecoveryAction, DeleteRecoveryCursor, DeleteRecoveryDigest, DeleteRecoveryInspection,
|
||||
DeleteRecoveryJournal, DeleteRecoveryPage, DeleteRecoverySettlementOutcome, DeleteRecoveryState,
|
||||
DeleteRecoveryVersionIdentity, DeleteTransactionId, Disk, DiskAPI, DiskInfo, DiskInfoOptions, DiskLocation, DiskStore,
|
||||
FORMAT_CONFIG_FILE, FileInfoVersions, FileReader, FileWriter, GuardedFileInfoVersions, OldCurrentSize, RUSTFS_META_BUCKET,
|
||||
FORMAT_CONFIG_FILE, FileInfoVersions, FileReader, FileWriter, GuardedFileInfoVersions, OldCurrentSize,
|
||||
PART_TRANSACTION_NEW_META, PART_TRANSACTION_OLD_META, PART_TRANSACTION_ROLLBACK, PartTransactionAction, RUSTFS_META_BUCKET,
|
||||
RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET, ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp,
|
||||
STORAGE_FORMAT_FILE, STORAGE_FORMAT_FILE_BACKUP, ScanGuard, UpdateMetadataOpts, VolumeInfo, WalkDirOptions,
|
||||
conv_part_err_to_int,
|
||||
endpoint::Endpoint,
|
||||
error::{DiskError, Error, Result},
|
||||
format::FormatV3,
|
||||
validate_delete_recovery_options, validate_format_control_path,
|
||||
part_transaction_path, validate_delete_recovery_options, validate_format_control_path,
|
||||
};
|
||||
use crate::erasure::coding::{self, bitrot_verify};
|
||||
use crate::runtime::instance::InstanceContext;
|
||||
@@ -226,6 +227,7 @@ pub struct DstSimDisk {
|
||||
delete_tx_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
cas_lock: Arc<tokio::sync::Mutex<()>>,
|
||||
configured_capacity: Arc<RwLock<Option<u64>>>,
|
||||
multipart_proof_authority: Arc<RwLock<Option<crate::disk::multipart_source::ProofVerificationContext>>>,
|
||||
}
|
||||
|
||||
impl Debug for DstSimDisk {
|
||||
@@ -280,9 +282,19 @@ impl DstSimDisk {
|
||||
delete_tx_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
cas_lock: Arc::new(tokio::sync::Mutex::new(())),
|
||||
configured_capacity: Arc::new(RwLock::new(None)),
|
||||
multipart_proof_authority: Arc::new(RwLock::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bind_multipart_proof_authority(
|
||||
&self,
|
||||
authority: &crate::disk::multipart_source::ProofVerificationContext,
|
||||
) -> Result<()> {
|
||||
let mut guard = self.multipart_proof_authority.write().unwrap_or_else(|p| p.into_inner());
|
||||
*guard = Some(authority.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn sim(&self) -> &SimDiskIo {
|
||||
&self.sim
|
||||
}
|
||||
@@ -1472,12 +1484,22 @@ impl DiskAPI for DstSimDisk {
|
||||
self.sim.create_dir_all(&src_dir).await.map_err(map_sim_err)?;
|
||||
self.sim.create_dir_all(&dst_dir).await.map_err(map_sim_err)?;
|
||||
|
||||
let has_external_parts = !file_info.inline_data() && file_info.data.is_none() && file_info.size > 0;
|
||||
let multipart_pub_identity = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
|
||||
crate::disk::multipart_source::publication_identity(&file_info)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let has_external_parts =
|
||||
!file_info.inline_data() && file_info.data.as_ref().is_none_or(|d| d.is_empty()) && file_info.size > 0;
|
||||
if has_external_parts
|
||||
&& let Some(data_dir) = file_info.data_dir
|
||||
&& !data_dir.is_nil()
|
||||
{
|
||||
let src_data = format!("{src_dir}/{data_dir}");
|
||||
let src_data_dir = multipart_pub_identity
|
||||
.as_ref()
|
||||
.map(|p| p.lineage.original_data_dir)
|
||||
.unwrap_or(data_dir);
|
||||
let src_data = format!("{src_dir}/{src_data_dir}");
|
||||
let dst_data = format!("{dst_dir}/{data_dir}");
|
||||
if self.sim.stat(&src_data).await.is_ok() {
|
||||
let staged_parts = self.sim.list_dir(&src_data).await.map_err(map_sim_err)?;
|
||||
@@ -1519,13 +1541,62 @@ impl DiskAPI for DstSimDisk {
|
||||
|
||||
self.fsync_parent_chain(&dst_dir).await?;
|
||||
let _ = self.sim.remove_file(&bkp_meta).await;
|
||||
let _ = self.sim.remove_dir_all(&src_dir).await;
|
||||
if src_volume == RUSTFS_META_TMP_BUCKET {
|
||||
let _ = self.sim.remove_dir_all(&src_dir).await;
|
||||
}
|
||||
|
||||
let multipart_source = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
|
||||
let publication = crate::disk::multipart_source::publication_identity(&file_info)?;
|
||||
let authority = self
|
||||
.multipart_proof_authority
|
||||
.read()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.clone();
|
||||
if let (Some(publication), Some(authority)) = (publication, authority) {
|
||||
let disk_id = self
|
||||
.disk_id
|
||||
.read()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.ok_or(DiskError::InconsistentDisk)?;
|
||||
let undo_capability = crate::disk::multipart_source::MultipartUndoCapability::new();
|
||||
let snapshot = crate::disk::multipart_source::MultipartSourceSnapshot {
|
||||
disk_id,
|
||||
physical_slot: self.disk_idx,
|
||||
lineage: publication.lineage.clone(),
|
||||
generation: publication.source_generation,
|
||||
revision: 1,
|
||||
phase: crate::disk::multipart_source::MultipartSourcePhase::ConsumedUnsealed,
|
||||
state_sha256: [0; 32],
|
||||
head_sha256: None,
|
||||
inventory_sha256: [0; 32],
|
||||
capability_sha256: Some(undo_capability.digest()),
|
||||
publication: Some(publication.clone()),
|
||||
};
|
||||
let proof = crate::disk::multipart_source::MultipartSourceProof::issue(
|
||||
&authority,
|
||||
crate::disk::multipart_source::MultipartProofKind::Published,
|
||||
Uuid::new_v4(),
|
||||
None,
|
||||
snapshot,
|
||||
)?;
|
||||
Some(Box::new(crate::disk::multipart_source::MultipartPublicationResult {
|
||||
publication,
|
||||
proof,
|
||||
undo_capability,
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(RenameDataResp {
|
||||
old_data_dir: has_old_data_dir,
|
||||
cleanup_data_dir: has_old_data_dir,
|
||||
old_current_size,
|
||||
old_current_source_checked: true,
|
||||
multipart_source,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
@@ -1632,20 +1703,149 @@ impl DiskAPI for DstSimDisk {
|
||||
self.fsync_parent_chain(dst_parent).await
|
||||
}
|
||||
|
||||
async fn prepare_part_transaction(
|
||||
&self,
|
||||
src_volume: &str,
|
||||
src_path: &str,
|
||||
dst_volume: &str,
|
||||
dst_path: &str,
|
||||
meta: Bytes,
|
||||
) -> Result<()> {
|
||||
self.ensure_online()?;
|
||||
let part = ObjectPartInfo::unmarshal(&meta)?;
|
||||
let src = join_vol_path(src_volume, src_path)?;
|
||||
let dst = join_vol_path(dst_volume, dst_path)?;
|
||||
let dst_meta = format!("{dst}.meta");
|
||||
let txn_dir = join_vol_path(dst_volume, &part_transaction_path(dst_path))?;
|
||||
self.sim.create_dir_all(&txn_dir).await.map_err(map_sim_err)?;
|
||||
|
||||
// Snapshot existing committed data/meta (or record explicit absence markers)
|
||||
match self.sim.read_file(&dst).await {
|
||||
Ok(old_data) => {
|
||||
self.write_durable_file(&format!("{txn_dir}/old.data"), old_data).await?;
|
||||
}
|
||||
Err(SimErr::NotFound(_)) => {
|
||||
self.write_durable_file(&format!("{txn_dir}/old.data.absent"), Bytes::new())
|
||||
.await?;
|
||||
}
|
||||
Err(e) => return Err(map_sim_err(e)),
|
||||
}
|
||||
match self.sim.read_file(&dst_meta).await {
|
||||
Ok(old_meta) => {
|
||||
self.write_durable_file(&format!("{txn_dir}/{PART_TRANSACTION_OLD_META}"), old_meta)
|
||||
.await?;
|
||||
}
|
||||
Err(SimErr::NotFound(_)) => {
|
||||
self.write_durable_file(&format!("{txn_dir}/old.meta.absent"), Bytes::new())
|
||||
.await?;
|
||||
}
|
||||
Err(e) => return Err(map_sim_err(e)),
|
||||
}
|
||||
|
||||
// Stage incoming part payload (and optional shard integrity proof) inside txn_dir
|
||||
let new_data = self.sim.read_file(&src).await.map_err(map_sim_err)?;
|
||||
self.write_durable_file(&format!("{txn_dir}/new.data"), new_data).await?;
|
||||
if let Some(integrity) = part.integrity {
|
||||
let proof_name = integrity.file_name();
|
||||
let src_parent = src.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
|
||||
let src_proof = if src_parent.is_empty() {
|
||||
proof_name.clone()
|
||||
} else {
|
||||
format!("{src_parent}/{proof_name}")
|
||||
};
|
||||
if let Ok(proof_bytes) = self.sim.read_file(&src_proof).await {
|
||||
self.write_durable_file(&format!("{txn_dir}/{proof_name}"), proof_bytes)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
self.write_durable_file(&format!("{txn_dir}/{PART_TRANSACTION_NEW_META}"), meta)
|
||||
.await?;
|
||||
self.fsync_parent_chain(&txn_dir).await
|
||||
}
|
||||
|
||||
async fn rename_part(&self, src_volume: &str, src_path: &str, dst_volume: &str, dst_path: &str, meta: Bytes) -> Result<()> {
|
||||
self.ensure_online()?;
|
||||
let part = ObjectPartInfo::unmarshal(&meta).ok();
|
||||
let src = join_vol_path(src_volume, src_path)?;
|
||||
let dst = join_vol_path(dst_volume, dst_path)?;
|
||||
let dst_parent = dst.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
|
||||
if !dst_parent.is_empty() {
|
||||
self.sim.create_dir_all(dst_parent).await.map_err(map_sim_err)?;
|
||||
}
|
||||
self.sim.fsync_file(&src).await.map_err(map_sim_err)?;
|
||||
self.sim.rename(&src, &dst).await.map_err(map_sim_err)?;
|
||||
let txn_dir = join_vol_path(dst_volume, &part_transaction_path(dst_path))?;
|
||||
let prepared_data = format!("{txn_dir}/new.data");
|
||||
if self.sim.stat(&prepared_data).await.is_ok() {
|
||||
self.sim.fsync_file(&prepared_data).await.map_err(map_sim_err)?;
|
||||
self.sim.rename(&prepared_data, &dst).await.map_err(map_sim_err)?;
|
||||
let _ = self.sim.remove_file(&src).await;
|
||||
} else {
|
||||
self.sim.fsync_file(&src).await.map_err(map_sim_err)?;
|
||||
self.sim.rename(&src, &dst).await.map_err(map_sim_err)?;
|
||||
}
|
||||
if let Some(integrity) = part.and_then(|p| p.integrity) {
|
||||
let proof_name = integrity.file_name();
|
||||
let dst_proof = if dst_parent.is_empty() {
|
||||
proof_name.clone()
|
||||
} else {
|
||||
format!("{dst_parent}/{proof_name}")
|
||||
};
|
||||
let txn_proof = format!("{txn_dir}/{proof_name}");
|
||||
if self.sim.stat(&txn_proof).await.is_ok() {
|
||||
let _ = self.sim.rename(&txn_proof, &dst_proof).await;
|
||||
} else {
|
||||
let src_parent = src.rsplit_once('/').map(|(p, _)| p).unwrap_or("");
|
||||
let src_proof = if src_parent.is_empty() {
|
||||
proof_name
|
||||
} else {
|
||||
format!("{src_parent}/{proof_name}")
|
||||
};
|
||||
if self.sim.stat(&src_proof).await.is_ok() {
|
||||
let _ = self.sim.rename(&src_proof, &dst_proof).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
let meta_path = format!("{dst}.meta");
|
||||
self.write_durable_file(&meta_path, meta).await
|
||||
}
|
||||
|
||||
async fn settle_part_transaction(&self, volume: &str, path: &str, action: PartTransactionAction) -> Result<()> {
|
||||
self.ensure_online()?;
|
||||
let dst = join_vol_path(volume, path)?;
|
||||
let dst_meta = format!("{dst}.meta");
|
||||
let txn_dir = join_vol_path(volume, &part_transaction_path(path))?;
|
||||
if self.sim.stat(&txn_dir).await.is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
match action {
|
||||
PartTransactionAction::Commit => {}
|
||||
PartTransactionAction::Rollback => {
|
||||
let _ = self
|
||||
.write_durable_file(&format!("{txn_dir}/{PART_TRANSACTION_ROLLBACK}"), Bytes::new())
|
||||
.await;
|
||||
let old_data = format!("{txn_dir}/old.data");
|
||||
if self.sim.stat(&old_data).await.is_ok() {
|
||||
self.sim.rename(&old_data, &dst).await.map_err(map_sim_err)?;
|
||||
} else if self.sim.stat(&format!("{txn_dir}/old.data.absent")).await.is_ok() {
|
||||
let _ = self.sim.remove_file(&dst).await;
|
||||
}
|
||||
let old_meta = format!("{txn_dir}/{PART_TRANSACTION_OLD_META}");
|
||||
if self.sim.stat(&old_meta).await.is_ok() {
|
||||
self.sim.rename(&old_meta, &dst_meta).await.map_err(map_sim_err)?;
|
||||
} else if self.sim.stat(&format!("{txn_dir}/old.meta.absent")).await.is_ok() {
|
||||
let _ = self.sim.remove_file(&dst_meta).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
match self.sim.remove_dir_all(&txn_dir).await {
|
||||
Ok(()) | Err(SimErr::NotFound(_)) => {}
|
||||
Err(e) => return Err(map_sim_err(e)),
|
||||
}
|
||||
if let Some((parent, _)) = txn_dir.rsplit_once('/') {
|
||||
let _ = self.fsync_parent_chain(parent).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete(&self, volume: &str, path: &str, opt: DeleteOptions) -> Result<()> {
|
||||
self.ensure_online()?;
|
||||
self.ensure_volume_exists(volume).await?;
|
||||
|
||||
@@ -1752,7 +1752,7 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_faulty(&self) -> bool {
|
||||
pub fn is_faulty(&self) -> bool {
|
||||
match self {
|
||||
Disk::Local(local_disk) => local_disk.is_faulty(),
|
||||
Disk::Remote(remote_disk) => remote_disk.is_faulty(),
|
||||
@@ -1761,6 +1761,15 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn probe_quorum_recovery_if_faulty(&self) -> bool {
|
||||
match self {
|
||||
Disk::Remote(remote_disk) => remote_disk.probe_quorum_recovery_if_faulty().await,
|
||||
Disk::Local(_) => false,
|
||||
#[cfg(feature = "dst")]
|
||||
Disk::Sim(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe a local wrapper's retirement. Remote handles have their own RPC lifecycle.
|
||||
/// Cancelling the returned child token does not retire the underlying wrapper.
|
||||
pub fn local_retirement_token(&self) -> Option<CancellationToken> {
|
||||
|
||||
@@ -186,6 +186,7 @@ pub(crate) fn bind_multipart_proof_snapshot(
|
||||
if sim.disk_index() != slot {
|
||||
return Err(DiskError::InconsistentDisk);
|
||||
}
|
||||
sim.bind_multipart_proof_authority(authority)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,6 +302,18 @@ impl PreparedIntegrity {
|
||||
volume: &str,
|
||||
directory: &str,
|
||||
) -> io::Result<PartIntegrity> {
|
||||
self.write_with_quorum(disks, original_volume, volume, directory, None).await
|
||||
}
|
||||
|
||||
pub(crate) async fn write_with_quorum(
|
||||
self,
|
||||
disks: &mut [Option<DiskStore>],
|
||||
original_volume: &str,
|
||||
volume: &str,
|
||||
directory: &str,
|
||||
post_quorum_quorum: Option<usize>,
|
||||
) -> io::Result<PartIntegrity> {
|
||||
const INTEGRITY_POST_QUORUM_GRACE: std::time::Duration = std::time::Duration::from_millis(300);
|
||||
let length = self.part.index_size().map_err(|_| corrupt())?;
|
||||
let length_i64 = i64::try_from(length).map_err(|_| corrupt())?;
|
||||
let path = format!("{directory}/{}", self.part.file_name());
|
||||
@@ -316,6 +328,71 @@ impl PreparedIntegrity {
|
||||
}
|
||||
let payload = Bytes::from(bytes);
|
||||
let prewritten_disks = &self.prewritten_disks;
|
||||
if let Some(quorum) = post_quorum_quorum {
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
let mut succeeded = vec![false; disks.len()];
|
||||
let mut ok_count = 0usize;
|
||||
let mut pending = FuturesUnordered::new();
|
||||
for (idx, disk_opt) in disks.iter().enumerate() {
|
||||
if prewritten_disks.get(idx).copied().unwrap_or(false) && disk_opt.is_some() {
|
||||
succeeded[idx] = true;
|
||||
ok_count = ok_count.saturating_add(1);
|
||||
continue;
|
||||
}
|
||||
let Some(disk) = disk_opt.clone() else {
|
||||
continue;
|
||||
};
|
||||
let path = path.clone();
|
||||
let payload = payload.clone();
|
||||
pending.push(async move {
|
||||
let res = tokio::time::timeout(std::time::Duration::from_secs(60), async {
|
||||
let mut writer = disk
|
||||
.create_file(original_volume, volume, &path, length_i64)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
if let Some(local) = crate::disk::as_lazy_local_file_writer_mut(&mut *writer) {
|
||||
local.write_all_bytes(payload).await?;
|
||||
} else {
|
||||
writer.write_all(&payload).await?;
|
||||
}
|
||||
writer.shutdown().await
|
||||
})
|
||||
.await;
|
||||
(idx, matches!(res, Ok(Ok(()))))
|
||||
});
|
||||
}
|
||||
let mut grace_deadline = (ok_count >= quorum && !pending.is_empty())
|
||||
.then(|| tokio::time::Instant::now() + INTEGRITY_POST_QUORUM_GRACE);
|
||||
loop {
|
||||
let next = if let Some(deadline) = grace_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = pending.next() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => None,
|
||||
}
|
||||
} else {
|
||||
pending.next().await
|
||||
};
|
||||
let Some((idx, ok)) = next else {
|
||||
break;
|
||||
};
|
||||
if ok {
|
||||
succeeded[idx] = true;
|
||||
ok_count = ok_count.saturating_add(1);
|
||||
if grace_deadline.is_none() && ok_count >= quorum && !pending.is_empty() {
|
||||
grace_deadline = Some(tokio::time::Instant::now() + INTEGRITY_POST_QUORUM_GRACE);
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(pending);
|
||||
for (idx, disk_opt) in disks.iter_mut().enumerate() {
|
||||
if !succeeded[idx] {
|
||||
*disk_opt = None;
|
||||
}
|
||||
}
|
||||
return Ok(self.part);
|
||||
}
|
||||
futures::future::join_all(disks.iter_mut().enumerate().map(|(idx, disk_opt)| {
|
||||
let path = &path;
|
||||
let payload = payload.clone();
|
||||
@@ -350,21 +427,64 @@ impl PreparedIntegrity {
|
||||
}
|
||||
Spool::File(file) => file,
|
||||
};
|
||||
let mut writers = futures::future::join_all(disks.iter().map(|disk| async {
|
||||
match disk {
|
||||
Some(disk) => disk
|
||||
.create_file(original_volume, volume, &path, length_i64)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(io::Error::other),
|
||||
None => Ok(None),
|
||||
let mut writers = if let Some(quorum) = post_quorum_quorum {
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
let mut out: Vec<Option<_>> = std::iter::repeat_with(|| None).take(disks.len()).collect();
|
||||
let mut pending: FuturesUnordered<_> = disks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, disk)| {
|
||||
let disk = disk.clone()?;
|
||||
let path = path.clone();
|
||||
Some(async move {
|
||||
let w = disk.create_file(original_volume, volume, &path, length_i64).await.ok();
|
||||
(idx, w)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut ok_count = 0usize;
|
||||
let mut grace_deadline: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let next = if let Some(deadline) = grace_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = pending.next() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => None,
|
||||
}
|
||||
} else {
|
||||
pending.next().await
|
||||
};
|
||||
let Some((idx, writer)) = next else {
|
||||
break;
|
||||
};
|
||||
if writer.is_some() {
|
||||
ok_count = ok_count.saturating_add(1);
|
||||
}
|
||||
out[idx] = writer;
|
||||
if grace_deadline.is_none() && ok_count >= quorum && !pending.is_empty() {
|
||||
grace_deadline = Some(tokio::time::Instant::now() + INTEGRITY_POST_QUORUM_GRACE);
|
||||
}
|
||||
}
|
||||
}))
|
||||
.await
|
||||
.into_iter()
|
||||
.map(Result::ok)
|
||||
.map(Option::flatten)
|
||||
.collect::<Vec<_>>();
|
||||
drop(pending);
|
||||
out
|
||||
} else {
|
||||
futures::future::join_all(disks.iter().map(|disk| async {
|
||||
match disk {
|
||||
Some(disk) => disk
|
||||
.create_file(original_volume, volume, &path, length_i64)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(io::Error::other),
|
||||
None => Ok(None),
|
||||
}
|
||||
}))
|
||||
.await
|
||||
.into_iter()
|
||||
.map(Result::ok)
|
||||
.map(Option::flatten)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// The file has a single owner; duplicated descriptors share offsets.
|
||||
file = tokio::task::spawn_blocking(move || {
|
||||
file.seek(SeekFrom::Start(0))?;
|
||||
|
||||
@@ -4421,19 +4421,60 @@ impl SetDisks {
|
||||
object: &str,
|
||||
write_quorum: usize,
|
||||
) -> Result<(Vec<Option<DiskStore>>, Vec<Option<SnapshotLeaseToken>>)> {
|
||||
const QUOTA_FENCE_POST_QUORUM_GRACE: Duration = Duration::from_millis(300);
|
||||
let fence_path = disk::quota_mutation_fence_path(bucket, object);
|
||||
let results = join_all(disks.iter().map(|disk| {
|
||||
let disk = disk.clone();
|
||||
let fence_path = fence_path.clone();
|
||||
async move {
|
||||
let disk = disk?;
|
||||
match disk.acquire_snapshot_lease(RUSTFS_META_BUCKET, &fence_path).await {
|
||||
Ok(token) => Some((disk, token)),
|
||||
Err(_) => None,
|
||||
let mut results: Vec<Option<(DiskStore, SnapshotLeaseToken)>> = vec![None; disks.len()];
|
||||
let mut pending: futures::stream::FuturesUnordered<_> = disks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, disk)| {
|
||||
let disk = disk.clone()?;
|
||||
let fence_path = fence_path.clone();
|
||||
Some(async move {
|
||||
let lease = disk
|
||||
.acquire_snapshot_lease(RUSTFS_META_BUCKET, &fence_path)
|
||||
.await
|
||||
.ok()
|
||||
.map(|token| (disk, token));
|
||||
(idx, lease)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut acquired = 0usize;
|
||||
let mut grace_deadline: Option<tokio::time::Instant> = None;
|
||||
loop {
|
||||
let next = if let Some(deadline) = grace_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = futures::StreamExt::next(&mut pending) => item,
|
||||
_ = tokio::time::sleep_until(deadline) => None,
|
||||
}
|
||||
} else {
|
||||
futures::StreamExt::next(&mut pending).await
|
||||
};
|
||||
let Some((idx, lease)) = next else {
|
||||
break;
|
||||
};
|
||||
if lease.is_some() {
|
||||
acquired = acquired.saturating_add(1);
|
||||
}
|
||||
}))
|
||||
.await;
|
||||
results[idx] = lease;
|
||||
if grace_deadline.is_none() && acquired >= write_quorum && !pending.is_empty() {
|
||||
grace_deadline = Some(tokio::time::Instant::now() + QUOTA_FENCE_POST_QUORUM_GRACE);
|
||||
}
|
||||
}
|
||||
if !pending.is_empty() {
|
||||
let cleanup_fence_path = fence_path.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some((_, lease)) = futures::StreamExt::next(&mut pending).await {
|
||||
if let Some((disk, token)) = lease {
|
||||
let _ = disk
|
||||
.release_snapshot_lease(RUSTFS_META_BUCKET, &cleanup_fence_path, token)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if results.iter().flatten().count() < write_quorum {
|
||||
for (disk, token) in results.iter().flatten() {
|
||||
let _ = disk.release_snapshot_lease(RUSTFS_META_BUCKET, &fence_path, *token).await;
|
||||
@@ -5581,16 +5622,22 @@ impl SetDisks {
|
||||
let plan = producers.plan();
|
||||
let mut results = Vec::with_capacity(disk_count);
|
||||
let mut successful = 0;
|
||||
let mut accept = |outcome: SlotRenameOutcome| {
|
||||
if let Some(tx) = dispatch_deadline_tx.as_ref()
|
||||
&& matches!(&outcome.completion, Ok(Ok(_)))
|
||||
{
|
||||
let mut post_quorum_completion_deadline: Option<tokio::time::Instant> = None;
|
||||
let mut post_quorum_detached = false;
|
||||
const PUT_RENAME_POST_QUORUM_COMPLETION_GRACE: Duration = Duration::from_millis(500);
|
||||
let mut accept = |outcome: SlotRenameOutcome| -> Option<tokio::time::Instant> {
|
||||
let mut armed_deadline = None;
|
||||
if matches!(&outcome.completion, Ok(Ok(_))) {
|
||||
successful += 1;
|
||||
if successful == write_quorum {
|
||||
if let Some(tx) = dispatch_deadline_tx.as_ref()
|
||||
&& successful == write_quorum
|
||||
{
|
||||
tx.send_replace(Some(tokio::time::Instant::now() + PUT_RENAME_POST_QUORUM_DISPATCH_GRACE));
|
||||
armed_deadline = Some(tokio::time::Instant::now() + PUT_RENAME_POST_QUORUM_COMPLETION_GRACE);
|
||||
}
|
||||
}
|
||||
results.push(outcome);
|
||||
armed_deadline
|
||||
};
|
||||
// Publication-scoped and protected multipart renames retain the
|
||||
// streamed path. A pure unary plan returns one outcome per task.
|
||||
@@ -5613,25 +5660,77 @@ impl SetDisks {
|
||||
tasks.spawn(crate::disk::with_detached_disk_io_context(producer));
|
||||
}
|
||||
drop((producers, resource_unit, successful_completion_rank));
|
||||
while let Some(joined) = tasks.join_next().await {
|
||||
loop {
|
||||
let joined = if let Some(deadline) = post_quorum_completion_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = tasks.join_next() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
if !tasks.is_empty() {
|
||||
post_quorum_detached = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tasks.join_next().await
|
||||
};
|
||||
let Some(joined) = joined else { break };
|
||||
// A missing outcome still has the original conservative rollback state.
|
||||
if let Ok(outcome) = joined {
|
||||
accept(outcome);
|
||||
if let Ok(outcome) = joined
|
||||
&& let Some(deadline) = accept(outcome)
|
||||
{
|
||||
post_quorum_completion_deadline = Some(deadline);
|
||||
}
|
||||
}
|
||||
if post_quorum_detached {
|
||||
let detached_scope = _fanout_publication_scope.clone();
|
||||
let detached_guard = _namespace_commit_guard.clone();
|
||||
tokio::spawn(async move {
|
||||
let _scope = detached_scope;
|
||||
let _guard = detached_guard;
|
||||
while tasks.join_next().await.is_some() {}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let RenameOutcomeProducers {
|
||||
outcomes: mut outcome_rx,
|
||||
mut tasks,
|
||||
} = Self::spawn_rename_outcome_producers(producers, plan);
|
||||
while let Some(outcome) = outcome_rx.recv().await {
|
||||
accept(outcome);
|
||||
loop {
|
||||
let received = if let Some(deadline) = post_quorum_completion_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = outcome_rx.recv() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => {
|
||||
post_quorum_detached = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
outcome_rx.recv().await
|
||||
};
|
||||
let Some(outcome) = received else { break };
|
||||
if let Some(deadline) = accept(outcome) {
|
||||
post_quorum_completion_deadline = Some(deadline);
|
||||
}
|
||||
}
|
||||
if post_quorum_detached {
|
||||
let detached_scope = _fanout_publication_scope.clone();
|
||||
let detached_guard = _namespace_commit_guard.clone();
|
||||
tokio::spawn(async move {
|
||||
let _scope = detached_scope;
|
||||
let _guard = detached_guard;
|
||||
while outcome_rx.recv().await.is_some() {}
|
||||
while tasks.join_next().await.is_some() {}
|
||||
});
|
||||
} else {
|
||||
while tasks.join_next().await.is_some() {}
|
||||
}
|
||||
while tasks.join_next().await.is_some() {}
|
||||
}
|
||||
#[cfg(test)]
|
||||
rollback_fault_injection::after_fanout(&fanout_paths.dst_object);
|
||||
(results, fanout_file_infos)
|
||||
(results, fanout_file_infos, post_quorum_detached)
|
||||
};
|
||||
let fanout_future = crate::disk::with_detached_disk_io_context(fanout_future);
|
||||
let fanout = if protected_multipart {
|
||||
@@ -5661,7 +5760,7 @@ impl SetDisks {
|
||||
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_QUORUM_WAIT,
|
||||
quorum_wait_started,
|
||||
);
|
||||
let (results, file_infos) = match fanout_result {
|
||||
let (results, file_infos, post_quorum_detached) = match fanout_result {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
drop(disk_snapshot);
|
||||
@@ -5749,6 +5848,13 @@ impl SetDisks {
|
||||
}
|
||||
}
|
||||
}
|
||||
if post_quorum_detached {
|
||||
for (idx, seen) in seen_slots.iter().enumerate() {
|
||||
if !*seen {
|
||||
errs[idx] = Some(DiskError::Timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if issue3031_diag_enabled() {
|
||||
let success_count = errs.iter().filter(|err| err.is_none()).count();
|
||||
@@ -11012,6 +11118,82 @@ mod tests {
|
||||
drop(dirs);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn metadata_read_hedges_and_completes_sub_second_when_four_of_twelve_drives_hang() {
|
||||
const DISKS: usize = 12;
|
||||
const PARITY: usize = 4;
|
||||
let bucket = "metadata-sigstop-3x4-bucket";
|
||||
let object = "objects/sigstop-3x4-object";
|
||||
let (dirs, disks) = call_counter_local_disks(bucket, DISKS).await;
|
||||
|
||||
// Install a 12-disk (8 data + 4 parity) non-inline object matching a 3x4 set.
|
||||
let version_id = Uuid::new_v4();
|
||||
let data_dir = Uuid::from_u128(0x3390_0000_0000_0001);
|
||||
let mod_time = OffsetDateTime::now_utc();
|
||||
let distribution = FileInfo::new(&metadata_distribution_key(bucket, object), 8, 4)
|
||||
.erasure
|
||||
.distribution;
|
||||
for (slot, disk) in disks.iter().enumerate() {
|
||||
let disk = disk.as_ref().expect("local disk");
|
||||
disk.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from_static(b"x"))
|
||||
.await
|
||||
.expect("seed 12-disk part.1");
|
||||
let mut fi = FileInfo::new(object, 8, 4);
|
||||
fi.volume = bucket.to_string();
|
||||
fi.name = object.to_string();
|
||||
fi.size = 256 * 1024;
|
||||
fi.version_id = Some(version_id);
|
||||
fi.is_latest = true;
|
||||
fi.mod_time = Some(mod_time);
|
||||
fi.erasure.index = distribution[slot];
|
||||
fi.erasure.distribution = distribution.clone();
|
||||
fi.erasure.block_size = 1024 * 1024;
|
||||
fi.data_dir = Some(data_dir);
|
||||
fi.metadata.insert("etag".to_string(), "deadbeef".to_string());
|
||||
fi.add_object_part(1, "deadbeef".to_string(), 256 * 1024, fi.mod_time, 256 * 1024, None, None);
|
||||
disk.write_metadata(bucket, bucket, object, fi)
|
||||
.await
|
||||
.expect("seed 12-disk metadata");
|
||||
}
|
||||
|
||||
// Simulate 1 SIGSTOP'd node in 3x4 owning 4 drives (indices 0, 1, 2, 3) hanging for 5000ms.
|
||||
temp_env::async_with_vars(
|
||||
[
|
||||
(ENV_RUSTFS_GET_METADATA_TWO_PHASE_READ_PLAN_ENABLE, Some("true")),
|
||||
(ENV_RUSTFS_GET_METADATA_EARLY_STOP_ENABLE, Some("true")),
|
||||
(ENV_RUSTFS_GET_METADATA_DATA_READ_EARLY_STOP_ENABLE, Some("true")),
|
||||
(ENV_RUSTFS_GET_METADATA_EARLY_STOP_BOUNDED_FANOUT, Some("true")),
|
||||
(ENV_RUSTFS_GET_METADATA_SLOWTAIL_FAULT_DELAY_MS, Some("5000")),
|
||||
(ENV_RUSTFS_GET_METADATA_SLOWTAIL_FAULT_DISKS, Some("0,1,2,3")),
|
||||
(ENV_RUSTFS_GET_METADATA_SLOWTAIL_FAULT_BUCKET, Some(bucket)),
|
||||
(ENV_RUSTFS_GET_METADATA_SLOWTAIL_FAULT_OBJECT_PREFIX, Some("objects/")),
|
||||
],
|
||||
async {
|
||||
let started = Instant::now();
|
||||
let (parts_metadata, errs, _diagnostics) = tokio::time::timeout(
|
||||
Duration::from_millis(1200),
|
||||
SetDisks::read_all_fileinfo_observed(&disks, bucket, bucket, object, "", true, false, false, true, PARITY),
|
||||
)
|
||||
.await
|
||||
.expect("3x4 metadata read with 4 hung drives must NOT stall for 5s")
|
||||
.expect("metadata fanout should succeed on 8 surviving drives");
|
||||
let elapsed = started.elapsed();
|
||||
assert!(
|
||||
elapsed < Duration::from_millis(1000),
|
||||
"3x4 SIGSTOP metadata read must finish sub-second, took {elapsed:?}"
|
||||
);
|
||||
let ok_count = parts_metadata.iter().filter(|fi| fi.name == object).count();
|
||||
assert_eq!(ok_count, 8, "all 8 surviving drives must be observed");
|
||||
for (hung_slot, err) in errs.iter().enumerate().take(4) {
|
||||
assert_eq!(*err, Some(DiskError::Timeout), "hung slot {hung_slot} should be reported as Timeout");
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
drop(dirs);
|
||||
}
|
||||
|
||||
/// Demo / regression guard for the backlog#1325 per-disk call counters.
|
||||
///
|
||||
/// The metadata fan-out issues each `read_version` inside its own
|
||||
|
||||
@@ -724,6 +724,17 @@ pub(in crate::set_disk) fn non_inline_data_read_early_stop_allowed(read_data: bo
|
||||
}
|
||||
|
||||
const NON_INLINE_SINGLE_PENDING_HEDGE_DELAY: Duration = Duration::from_millis(100);
|
||||
/// Delay before fanning out remaining spare disks when multiple initial disks
|
||||
/// in bounded-fanout mode are simultaneously unresponsive (e.g., a SIGSTOP'd
|
||||
/// node owning 4 drives in a 3x4 set).
|
||||
const BOUNDED_FANOUT_MULTI_PENDING_HEDGE_DELAY: Duration = Duration::from_millis(100);
|
||||
/// Post-quorum straggler grace once all disks have been queried and a valid,
|
||||
/// conflict-free read quorum has already been observed. Prevents hung drives
|
||||
/// from pinning GET latency to the full 5s drive metadata timeout.
|
||||
const METADATA_POST_QUORUM_STRAGGLER_GRACE: Duration = Duration::from_millis(250);
|
||||
/// Post-quorum straggler grace for non-healing remote full-wait metadata reads
|
||||
/// once a verified, conflict-free write/read quorum has already replied.
|
||||
const FULL_WAIT_REMOTE_POST_QUORUM_STRAGGLER_GRACE: Duration = Duration::from_millis(350);
|
||||
|
||||
fn data_read_inline_missing_shards_are_pending(
|
||||
candidate: &FileInfo,
|
||||
@@ -1025,7 +1036,7 @@ impl SetDisks {
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
#[allow(clippy::redundant_locals)]
|
||||
let diagnostic_context = diagnostic_context;
|
||||
AbortOnDropJoinHandle(tokio::spawn(async move {
|
||||
AbortOnDropJoinHandle(tokio::spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
let read = async move {
|
||||
let response_start = observe.then(Instant::now);
|
||||
let result = if let Some(disk) = disk {
|
||||
@@ -1053,34 +1064,137 @@ impl SetDisks {
|
||||
.await;
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
read.await
|
||||
}))
|
||||
})))
|
||||
});
|
||||
|
||||
// Wait for all futures to complete
|
||||
let results = join_all(futures).await;
|
||||
// Non-healing distributed metadata reads (e.g. bucket metadata /
|
||||
// incarnation checks during PUT) should not stall for the full 5s
|
||||
// drive timeout on a SIGSTOP'd peer once a clean, conflict-free quorum
|
||||
// has already replied.
|
||||
let bound_remote_stragglers = !healing && !incl_free_versions && disks.iter().flatten().any(|disk| !disk.is_local());
|
||||
if bound_remote_stragglers {
|
||||
use futures::stream::{FuturesUnordered, StreamExt};
|
||||
|
||||
for (index, join_result) in results.into_iter().enumerate() {
|
||||
match join_result {
|
||||
Ok((res, elapsed)) => match res {
|
||||
Ok(file_info) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_file_info(&file_info, elapsed));
|
||||
}
|
||||
slots[index].result = Some(Ok(file_info));
|
||||
let mut pending: FuturesUnordered<_> = futures
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, handle)| async move { (index, handle.await) })
|
||||
.collect();
|
||||
let mut valid_candidate: Option<FileInfo> = None;
|
||||
let mut matching_votes = 0usize;
|
||||
let mut conflicting = false;
|
||||
let mut required_quorum: Option<usize> = None;
|
||||
let mut grace_deadline: Option<tokio::time::Instant> = None;
|
||||
|
||||
loop {
|
||||
let next = if let Some(deadline) = grace_deadline {
|
||||
tokio::select! {
|
||||
biased;
|
||||
item = pending.next() => item,
|
||||
_ = tokio::time::sleep_until(deadline) => None,
|
||||
}
|
||||
Err(e) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_error(&e, elapsed));
|
||||
} else {
|
||||
pending.next().await
|
||||
};
|
||||
let Some((index, join_result)) = next else {
|
||||
break;
|
||||
};
|
||||
match join_result {
|
||||
Ok((res, elapsed)) => match res {
|
||||
Ok(file_info) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_file_info(&file_info, elapsed));
|
||||
}
|
||||
if file_info_is_valid_for_metadata(&file_info) {
|
||||
if let Some(candidate) = valid_candidate.as_ref() {
|
||||
if metadata_early_stop_candidate_matches(candidate, &file_info) {
|
||||
matching_votes = matching_votes.saturating_add(1);
|
||||
} else {
|
||||
conflicting = true;
|
||||
}
|
||||
} else {
|
||||
let data_blocks = file_info.erasure.data_blocks;
|
||||
let parity_blocks = file_info.erasure.parity_blocks;
|
||||
if data_blocks > 0 && data_blocks + parity_blocks == disks.len() {
|
||||
required_quorum = Some(if data_blocks == parity_blocks {
|
||||
data_blocks.saturating_add(1)
|
||||
} else {
|
||||
data_blocks
|
||||
});
|
||||
}
|
||||
valid_candidate = Some(file_info.clone());
|
||||
matching_votes = 1;
|
||||
}
|
||||
}
|
||||
slots[index].result = Some(Ok(file_info));
|
||||
}
|
||||
slots[index].result = Some(Err(e));
|
||||
Err(e) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_error(&e, elapsed));
|
||||
}
|
||||
slots[index].result = Some(Err(e));
|
||||
}
|
||||
},
|
||||
Err(_join_err) => {
|
||||
if let Some(observations) = &mut observations {
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Unexpected, Duration::ZERO));
|
||||
}
|
||||
slots[index].result = Some(Err(DiskError::Unexpected));
|
||||
}
|
||||
}
|
||||
if grace_deadline.is_none()
|
||||
&& !conflicting
|
||||
&& !pending.is_empty()
|
||||
&& required_quorum.is_some_and(|quorum| matching_votes >= quorum)
|
||||
{
|
||||
grace_deadline = Some(tokio::time::Instant::now() + FULL_WAIT_REMOTE_POST_QUORUM_STRAGGLER_GRACE);
|
||||
}
|
||||
}
|
||||
// Dropping remaining `AbortOnDropJoinHandle`s aborts hung remote tasks.
|
||||
drop(pending);
|
||||
for slot in &mut slots {
|
||||
if slot.result.is_none() {
|
||||
if let Some(Some(disk)) = disks.get(slot.disk_index)
|
||||
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
|
||||
{
|
||||
remote.record_straggler_timeout();
|
||||
}
|
||||
},
|
||||
Err(_join_err) => {
|
||||
// A spawned task panicked — treat as unexpected disk error
|
||||
if let Some(observations) = &mut observations {
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Unexpected, Duration::ZERO));
|
||||
observations.push(MetadataFanoutObservation::from_error(
|
||||
&DiskError::Timeout,
|
||||
fanout_start.map_or(Duration::ZERO, |s| s.elapsed()),
|
||||
));
|
||||
}
|
||||
slot.result = Some(Err(DiskError::Timeout));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Wait for all futures to complete
|
||||
let results = join_all(futures).await;
|
||||
|
||||
for (index, join_result) in results.into_iter().enumerate() {
|
||||
match join_result {
|
||||
Ok((res, elapsed)) => match res {
|
||||
Ok(file_info) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_file_info(&file_info, elapsed));
|
||||
}
|
||||
slots[index].result = Some(Ok(file_info));
|
||||
}
|
||||
Err(e) => {
|
||||
if let (Some(observations), Some(elapsed)) = (&mut observations, elapsed) {
|
||||
observations.push(MetadataFanoutObservation::from_error(&e, elapsed));
|
||||
}
|
||||
slots[index].result = Some(Err(e));
|
||||
}
|
||||
},
|
||||
Err(_join_err) => {
|
||||
// A spawned task panicked — treat as unexpected disk error
|
||||
if let Some(observations) = &mut observations {
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Unexpected, Duration::ZERO));
|
||||
}
|
||||
slots[index].result = Some(Err(DiskError::Unexpected));
|
||||
}
|
||||
slots[index].result = Some(Err(DiskError::Unexpected));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1149,6 +1263,8 @@ impl SetDisks {
|
||||
let mut final_miss_reason_override = None;
|
||||
let mut non_inline_candidate_eligible = None;
|
||||
let mut single_pending_hedge_deadline = None;
|
||||
let mut multi_pending_hedge_deadline: Option<tokio::time::Instant> = None;
|
||||
let mut post_quorum_straggler_deadline: Option<tokio::time::Instant> = None;
|
||||
let slowtail_fault = get_metadata_slowtail_fault_request(bucket.as_ref(), object.as_ref(), read_data);
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
|
||||
@@ -1167,7 +1283,7 @@ impl SetDisks {
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
#[allow(clippy::redundant_locals)]
|
||||
let diagnostic_context = diagnostic_context;
|
||||
let task = join_set.spawn(async move {
|
||||
let task = join_set.spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
let read = async move {
|
||||
let response_start = stage_metrics_enabled.then(Instant::now);
|
||||
let result = if let Some(disk) = disk {
|
||||
@@ -1203,7 +1319,7 @@ impl SetDisks {
|
||||
.await;
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
read.await
|
||||
});
|
||||
}));
|
||||
task_ids[index] = Some(task.id());
|
||||
};
|
||||
|
||||
@@ -1224,37 +1340,130 @@ impl SetDisks {
|
||||
}
|
||||
}
|
||||
|
||||
if bounded_fanout && next_fanout_index < disks.len() && join_set.len() > 1 {
|
||||
multi_pending_hedge_deadline = Some(tokio::time::Instant::now() + BOUNDED_FANOUT_MULTI_PENDING_HEDGE_DELAY);
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum MetadataWaitTimer {
|
||||
SinglePendingHedge,
|
||||
MultiPendingHedge,
|
||||
PostQuorumStragglerGrace,
|
||||
}
|
||||
|
||||
loop {
|
||||
let mut defer_pending_inline_data_shard = false;
|
||||
let result = if let Some(deadline) = single_pending_hedge_deadline.take() {
|
||||
let active_timer = [
|
||||
single_pending_hedge_deadline.map(|d| (d, MetadataWaitTimer::SinglePendingHedge)),
|
||||
multi_pending_hedge_deadline.map(|d| (d, MetadataWaitTimer::MultiPendingHedge)),
|
||||
post_quorum_straggler_deadline.map(|d| (d, MetadataWaitTimer::PostQuorumStragglerGrace)),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.min_by_key(|(deadline, _)| *deadline);
|
||||
|
||||
let result = if let Some((deadline, timer_kind)) = active_timer {
|
||||
tokio::select! {
|
||||
result = join_set.join_next_with_id() => result,
|
||||
_ = async {
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
#[cfg(test)]
|
||||
rename_fanout_barrier::checkpoint(
|
||||
object.as_ref(),
|
||||
0,
|
||||
rename_fanout_barrier::PHASE_NON_INLINE_HEDGE_TIMER,
|
||||
)
|
||||
.await;
|
||||
if matches!(
|
||||
timer_kind,
|
||||
MetadataWaitTimer::SinglePendingHedge | MetadataWaitTimer::MultiPendingHedge
|
||||
) {
|
||||
rename_fanout_barrier::checkpoint(
|
||||
object.as_ref(),
|
||||
0,
|
||||
rename_fanout_barrier::PHASE_NON_INLINE_HEDGE_TIMER,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
} => {
|
||||
if bounded_fanout
|
||||
&& !force_full_wait
|
||||
&& join_set.len() == 1
|
||||
&& non_inline_candidate_eligible == Some(true)
|
||||
&& !accumulator.candidate_has_read_reserve()
|
||||
&& next_fanout_index < disks.len()
|
||||
{
|
||||
while next_fanout_index < disks.len() {
|
||||
let disk_index = fanout_order[next_fanout_index];
|
||||
next_fanout_index = next_fanout_index.saturating_add(1);
|
||||
if let Some(disk) = disks.get(disk_index).cloned() {
|
||||
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
|
||||
scheduled_count = scheduled_count.saturating_add(1);
|
||||
break;
|
||||
match timer_kind {
|
||||
MetadataWaitTimer::SinglePendingHedge => {
|
||||
single_pending_hedge_deadline = None;
|
||||
if bounded_fanout
|
||||
&& !force_full_wait
|
||||
&& join_set.len() == 1
|
||||
&& non_inline_candidate_eligible == Some(true)
|
||||
&& !accumulator.candidate_has_read_reserve()
|
||||
&& next_fanout_index < disks.len()
|
||||
{
|
||||
while next_fanout_index < disks.len() {
|
||||
let disk_index = fanout_order[next_fanout_index];
|
||||
next_fanout_index = next_fanout_index.saturating_add(1);
|
||||
if let Some(disk) = disks.get(disk_index).cloned() {
|
||||
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
|
||||
scheduled_count = scheduled_count.saturating_add(1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
MetadataWaitTimer::MultiPendingHedge => {
|
||||
multi_pending_hedge_deadline = None;
|
||||
// Multiple initial disks are still unanswered after 100ms
|
||||
// (e.g., a SIGSTOP'd node holding 4 drives in a 3x4 set).
|
||||
// Fan out all remaining spare drives immediately so healthy
|
||||
// parity/data nodes can establish read quorum without paying
|
||||
// the full 5s drive metadata timeout.
|
||||
if bounded_fanout && next_fanout_index < disks.len() && join_set.len() > 1 {
|
||||
while next_fanout_index < disks.len() {
|
||||
let disk_index = fanout_order[next_fanout_index];
|
||||
next_fanout_index = next_fanout_index.saturating_add(1);
|
||||
if let Some(disk) = disks.get(disk_index).cloned() {
|
||||
spawn_read_version(&mut join_set, &mut task_ids, disk_index, disk);
|
||||
scheduled_count = scheduled_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
MetadataWaitTimer::PostQuorumStragglerGrace => {
|
||||
// All disks have been dispatched and a verified, conflict-free
|
||||
// read quorum is already in hand. Abort the hung tail tasks and
|
||||
// return immediately so EC reconstruction can proceed in <500ms.
|
||||
join_set.abort_all();
|
||||
let mut cancelled_count = 0usize;
|
||||
while let Some(join_result) = join_set.join_next_with_id().await {
|
||||
if matches!(join_result, Err(join_error) if join_error.is_cancelled()) {
|
||||
cancelled_count = cancelled_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
let elapsed = fanout_start.map_or(Duration::ZERO, |s| s.elapsed());
|
||||
for slot in &mut slots {
|
||||
if slot.result.is_none() {
|
||||
if let Some(Some(disk)) = disks.get(slot.disk_index)
|
||||
&& let crate::disk::Disk::Remote(remote) = disk.as_ref()
|
||||
{
|
||||
remote.record_straggler_timeout();
|
||||
}
|
||||
observations.push(MetadataFanoutObservation::from_error(&DiskError::Timeout, elapsed));
|
||||
slot.result = Some(Err(DiskError::Timeout));
|
||||
}
|
||||
}
|
||||
rustfs_io_metrics::record_get_object_metadata_early_stop_hit(
|
||||
metrics_path,
|
||||
crate::diagnostics::get::GET_METADATA_EARLY_STOP_REASON_VALID_QUORUM,
|
||||
);
|
||||
rustfs_io_metrics::record_get_object_metadata_early_stop_saved_responses(
|
||||
metrics_path,
|
||||
cancelled_count,
|
||||
);
|
||||
rustfs_io_metrics::record_get_object_metadata_fanout_lifecycle(
|
||||
metrics_path,
|
||||
scheduled_count,
|
||||
scheduled_count.saturating_sub(cancelled_count),
|
||||
cancelled_count,
|
||||
);
|
||||
let diagnostics = MetadataFanoutDiagnostics::new(elapsed, observations);
|
||||
return Ok(MetadataReadResult {
|
||||
slots,
|
||||
diagnostics,
|
||||
condition_stopped: false,
|
||||
verified_inline_body: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -1470,7 +1679,49 @@ impl SetDisks {
|
||||
&& accumulator.can_still_reach_early_stop_with_pending(join_set.len())
|
||||
&& next_fanout_index < disks.len()
|
||||
{
|
||||
single_pending_hedge_deadline = Some(tokio::time::Instant::now() + NON_INLINE_SINGLE_PENDING_HEDGE_DELAY);
|
||||
single_pending_hedge_deadline
|
||||
.get_or_insert_with(|| tokio::time::Instant::now() + NON_INLINE_SINGLE_PENDING_HEDGE_DELAY);
|
||||
} else {
|
||||
single_pending_hedge_deadline = None;
|
||||
}
|
||||
if bounded_fanout && next_fanout_index < disks.len() && join_set.len() > 1 {
|
||||
multi_pending_hedge_deadline
|
||||
.get_or_insert_with(|| tokio::time::Instant::now() + BOUNDED_FANOUT_MULTI_PENDING_HEDGE_DELAY);
|
||||
} else {
|
||||
multi_pending_hedge_deadline = None;
|
||||
}
|
||||
let all_disks_dispatched = !bounded_fanout || next_fanout_index >= disks.len();
|
||||
let valid_quorum_reached = accumulator
|
||||
.early_stop_decision()
|
||||
.or_else(|| accumulator.version_early_stop_decision())
|
||||
.is_some()
|
||||
|| accumulator.candidate.as_ref().is_some_and(|candidate| {
|
||||
candidate.size == 0
|
||||
&& accumulator.not_found_responses == 0
|
||||
&& accumulator.version_not_found_responses == 0
|
||||
&& accumulator.candidate_votes >= accumulator.default_write_quorum()
|
||||
});
|
||||
let not_found_quorum_reached = accumulator.valid_responses == 0
|
||||
&& !accumulator.delete_marker_seen
|
||||
&& accumulator.not_found_responses >= accumulator.missing_response_quorum();
|
||||
let quorum_ready_for_straggler_grace = all_disks_dispatched
|
||||
&& !join_set.is_empty()
|
||||
&& !accumulator.conflicting_metadata
|
||||
&& !accumulator.delete_marker_seen
|
||||
&& accumulator.hard_errors == 0
|
||||
&& ((valid_quorum_reached
|
||||
&& (!read_data
|
||||
|| non_inline_candidate_eligible == Some(true)
|
||||
|| accumulator
|
||||
.candidate
|
||||
.as_ref()
|
||||
.is_some_and(|candidate| accumulator.candidate_votes >= candidate.erasure.data_blocks)))
|
||||
|| not_found_quorum_reached);
|
||||
if quorum_ready_for_straggler_grace {
|
||||
post_quorum_straggler_deadline
|
||||
.get_or_insert_with(|| tokio::time::Instant::now() + METADATA_POST_QUORUM_STRAGGLER_GRACE);
|
||||
} else {
|
||||
post_quorum_straggler_deadline = None;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4434,7 +4434,8 @@ fn record_lock_acquire(bucket: &str, object: &str, lock_type: &str) -> String {
|
||||
return lock_id;
|
||||
}
|
||||
|
||||
let request_id = format!("get-{}-{}", bucket, object);
|
||||
let request_id =
|
||||
crate::cluster::rpc::context_propagation::current_request_id_or_fallback(|| format!("get-{}-{}", bucket, object));
|
||||
let resource = format!("{}/{}", bucket, object);
|
||||
|
||||
// Log with structured fields for analysis
|
||||
@@ -4456,7 +4457,8 @@ fn record_lock_release(bucket: &str, object: &str, lock_id: &str, lock_type: &st
|
||||
return;
|
||||
}
|
||||
|
||||
let request_id = format!("get-{}-{}", bucket, object);
|
||||
let request_id =
|
||||
crate::cluster::rpc::context_propagation::current_request_id_or_fallback(|| format!("get-{}-{}", bucket, object));
|
||||
|
||||
debug!(
|
||||
request_id = %request_id,
|
||||
|
||||
@@ -114,31 +114,62 @@ impl SetDisks {
|
||||
pub(crate) async fn stat_bucket_with_quorum(&self, bucket: &str, quorum: BucketInfoQuorum) -> Result<BucketInfo> {
|
||||
let disks = self.disk_inventory().await;
|
||||
let disk_count = disks.len();
|
||||
let probes = disks.into_iter().map(|disk| stat_bucket_volume(disk, bucket));
|
||||
let results = join_all(probes).await;
|
||||
let required = match quorum {
|
||||
// Bucket mutations use a majority regardless of object storage
|
||||
// class. A namespace read must intersect that majority; object
|
||||
// readers still enforce the persisted layout's data-shard quorum.
|
||||
BucketInfoQuorum::Read => disk_count.div_ceil(2).max(1),
|
||||
BucketInfoQuorum::Write | BucketInfoQuorum::HealCandidates => disk_count / 2 + 1,
|
||||
};
|
||||
let strict_majority = disk_count / 2 + 1;
|
||||
let mut probes = disks
|
||||
.into_iter()
|
||||
.map(|disk| stat_bucket_volume(disk, bucket))
|
||||
.collect::<FuturesUnordered<_>>();
|
||||
let mut first_info = None;
|
||||
let mut errs = Vec::with_capacity(results.len());
|
||||
for result in results {
|
||||
let mut errs = Vec::with_capacity(disk_count);
|
||||
let mut successes = 0usize;
|
||||
let mut not_found = 0usize;
|
||||
let mut remaining = disk_count;
|
||||
while let Some(result) = probes.next().await {
|
||||
remaining = remaining.saturating_sub(1);
|
||||
match result {
|
||||
Ok(info) => {
|
||||
successes += 1;
|
||||
if first_info.is_none() {
|
||||
first_info = Some(info);
|
||||
}
|
||||
errs.push(None);
|
||||
// Once enough disks confirm the bucket exists, remaining hung
|
||||
// peers (e.g. SIGSTOP grey failure) cannot overturn quorum.
|
||||
if successes >= required {
|
||||
return first_info
|
||||
.map(|info| BucketInfo {
|
||||
name: info.name,
|
||||
created: info.created,
|
||||
..Default::default()
|
||||
})
|
||||
.ok_or(Error::VolumeNotFound);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
if matches!(err, DiskError::VolumeNotFound) {
|
||||
not_found += 1;
|
||||
}
|
||||
errs.push(Some(err));
|
||||
// If a strict majority reports VolumeNotFound and remaining
|
||||
// disks can no longer reach success quorum, absence is decisive.
|
||||
if not_found >= strict_majority && successes + remaining < required {
|
||||
return Err(Error::VolumeNotFound);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let error = match quorum {
|
||||
// Bucket mutations use a majority regardless of object storage
|
||||
// class. A namespace read must intersect that majority; object
|
||||
// readers still enforce the persisted layout's data-shard quorum.
|
||||
BucketInfoQuorum::Read => reduce_read_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, disk_count.div_ceil(2).max(1)),
|
||||
BucketInfoQuorum::Read => reduce_read_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, required),
|
||||
BucketInfoQuorum::Write | BucketInfoQuorum::HealCandidates => {
|
||||
reduce_write_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, disk_count / 2 + 1)
|
||||
reduce_write_quorum_errs(&errs, BUCKET_OP_IGNORED_ERRS, required)
|
||||
}
|
||||
};
|
||||
if let Some(err) = error {
|
||||
|
||||
@@ -3769,15 +3769,12 @@ impl SetDisks {
|
||||
proof: AbsenceProofRequest<'_>,
|
||||
) -> Result<(HealResultItem, Option<Error>)> {
|
||||
*absence = None;
|
||||
if opts.read_repair
|
||||
&& !opts.no_lock
|
||||
&& !opts.dry_run
|
||||
&& !opts.remove
|
||||
&& !has_suffix(object, SLASH_SEPARATOR)
|
||||
&& !crate::bucket::utils::is_meta_bucketname(bucket)
|
||||
{
|
||||
// Read repair may stage under a shared lock, but must not perform
|
||||
// destructive cleanup or produce an authoritative absence proof.
|
||||
if opts.read_repair && !opts.no_lock && !opts.dry_run && !opts.remove && !has_suffix(object, SLASH_SEPARATOR) {
|
||||
// Read repair may stage under a shared lock (including `.rustfs.sys`
|
||||
// metadata like `.bucket-incarnation` and `config.json` so a hung
|
||||
// peer cannot hold an exclusive write lock across read-repair timeouts
|
||||
// and stall foreground bucket reads), without performing destructive
|
||||
// cleanup or producing an authoritative absence proof.
|
||||
let can_commit = || proof.retirement.is_none_or(|context| !context.lifecycle_guard.is_lock_lost());
|
||||
let mut read_opts = *opts;
|
||||
loop {
|
||||
@@ -5981,6 +5978,127 @@ mod heal_result_report_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deep_heal_restores_part_flip_tail_truncation_and_xl_meta_byte_for_byte() {
|
||||
let (temp_dirs, disks, set) = hermetic_set_disks_isolated(4).await;
|
||||
let bucket = "deep-heal-triple-bitrot";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
|
||||
// Write 3 non-inline objects so we can independently inject:
|
||||
// (1) byte-0 flip on part.1, (2) 1-byte tail truncation on part.1,
|
||||
// and (3) 4-byte mid-file corruption (\xde\xad\xbe\xef) on xl.meta,
|
||||
// matching Jepsen `inject-bitrot-on-node!` on disk 0.
|
||||
let mut payloads = Vec::new();
|
||||
let mut target_paths = Vec::new();
|
||||
let mut original_bytes = Vec::new();
|
||||
for (idx, object) in ["obj-flip.bin", "obj-trunc.bin", "obj-meta.bin"].iter().enumerate() {
|
||||
let mut payload = vec![0u8; 512 * 1024];
|
||||
for (pos, byte) in payload.iter_mut().enumerate() {
|
||||
*byte = ((pos.wrapping_mul(31) + idx * 17) & 0xff) as u8;
|
||||
}
|
||||
let mut user_defined = std::collections::HashMap::new();
|
||||
user_defined.insert("x-amz-meta-z".to_string(), "zeta".to_string());
|
||||
user_defined.insert("x-amz-meta-a".to_string(), "alpha".to_string());
|
||||
user_defined.insert("x-amz-meta-m".to_string(), "mid".to_string());
|
||||
set.put_object(
|
||||
bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(payload.clone()),
|
||||
&ObjectOptions {
|
||||
no_lock: true,
|
||||
user_defined,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("source object should be written");
|
||||
let source = disks[2]
|
||||
.read_version("", bucket, object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("source metadata should be readable");
|
||||
let data_dir = source.data_dir.expect("non-inline object should have data_dir");
|
||||
let path = if idx == 2 {
|
||||
temp_dirs[0].path().join(bucket).join(object).join("xl.meta")
|
||||
} else {
|
||||
temp_dirs[0]
|
||||
.path()
|
||||
.join(bucket)
|
||||
.join(object)
|
||||
.join(data_dir.to_string())
|
||||
.join("part.1")
|
||||
};
|
||||
let bytes = tokio::fs::read(&path).await.expect("original on-disk file should exist");
|
||||
payloads.push((*object, payload));
|
||||
target_paths.push(path);
|
||||
original_bytes.push(bytes);
|
||||
}
|
||||
|
||||
// Fault 1: flip byte 0 of obj-flip/part.1 to 0xff (or xor if already 0xff)
|
||||
{
|
||||
let mut corrupted = original_bytes[0].clone();
|
||||
corrupted[0] = if corrupted[0] == 0xff { 0x00 } else { 0xff };
|
||||
tokio::fs::write(&target_paths[0], &corrupted)
|
||||
.await
|
||||
.expect("write byte-0 flip");
|
||||
}
|
||||
// Fault 2: 1-byte tail truncation on obj-trunc/part.1
|
||||
{
|
||||
let file = tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&target_paths[1])
|
||||
.await
|
||||
.expect("open part for truncation");
|
||||
file.set_len((original_bytes[1].len() - 1) as u64)
|
||||
.await
|
||||
.expect("truncate 1 byte from tail");
|
||||
}
|
||||
// Fault 3: 4-byte mid-file corruption (\xde\xad\xbe\xef) on obj-meta/xl.meta
|
||||
{
|
||||
let mut corrupted = original_bytes[2].clone();
|
||||
let mid = corrupted.len() / 2;
|
||||
corrupted[mid..mid + 4].copy_from_slice(&[0xde, 0xad, 0xbe, 0xef]);
|
||||
tokio::fs::write(&target_paths[2], &corrupted)
|
||||
.await
|
||||
.expect("corrupt xl.meta mid-file");
|
||||
}
|
||||
|
||||
for (idx, (object, expected_payload)) in payloads.iter().enumerate() {
|
||||
let (result, error) = set
|
||||
.heal_object(
|
||||
bucket,
|
||||
object,
|
||||
"",
|
||||
&HealOpts {
|
||||
no_lock: true,
|
||||
scan_mode: HealScanMode::Deep,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("deep heal should complete");
|
||||
assert!(error.is_none(), "deep heal failed for {object}: {error:?}");
|
||||
assert_eq!(result.drives_healed(), Some(1), "expected 1 drive healed for {object}");
|
||||
|
||||
let restored = tokio::fs::read(&target_paths[idx])
|
||||
.await
|
||||
.expect("healed file should exist on disk");
|
||||
assert_eq!(
|
||||
restored, original_bytes[idx],
|
||||
"on-disk file for {object} (including xl.meta) must be restored byte-for-byte"
|
||||
);
|
||||
|
||||
let mut reader = set
|
||||
.get_object_reader(bucket, object, None, Default::default(), &ObjectOptions::default())
|
||||
.await
|
||||
.expect("GET after deep heal must succeed");
|
||||
let mut got = Vec::new();
|
||||
tokio::io::copy(&mut reader, &mut got).await.expect("read healed payload");
|
||||
assert_eq!(&got, expected_payload, "GET payload mismatch after deep heal for {object}");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FailedIntegrityReadTransport {
|
||||
error: DiskError,
|
||||
|
||||
@@ -1054,6 +1054,23 @@ impl Drop for NewMultipartUploadCommitObservation {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "dst")]
|
||||
fn should_dst_crash_multipart(
|
||||
disks: &[Option<DiskStore>],
|
||||
point: rustfs_dst_faults::crash::CrashPoint,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
) -> bool {
|
||||
let full_key = format!("{bucket}/{object}");
|
||||
disks.iter().flatten().any(|disk| match disk.as_ref() {
|
||||
crate::disk::Disk::Sim(sim) => {
|
||||
let registry = sim.crash_registry();
|
||||
registry.take_if_armed(point, object) || registry.take_if_armed(point, &full_key)
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn observe_new_multipart_upload_commit(bucket: &str, object: &str) {
|
||||
let state = NEW_MULTIPART_UPLOAD_COMMIT_OBSERVATION
|
||||
@@ -5776,6 +5793,15 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if crash_inject::should_crash_at(CrashPoint::MultipartBeforeCommitRename, &commit_object) {
|
||||
return Err(StorageError::Unexpected);
|
||||
}
|
||||
#[cfg(feature = "dst")]
|
||||
if should_dst_crash_multipart(
|
||||
&commit_disks,
|
||||
rustfs_dst_faults::crash::CrashPoint::MultipartBeforeCommitRename,
|
||||
&commit_bucket,
|
||||
&commit_object,
|
||||
) {
|
||||
return Err(StorageError::Unexpected);
|
||||
}
|
||||
quota_reservation.mark_commit_started().await?;
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pause_multipart_commit(&commit_bucket, &commit_object, MultipartCommitPause::BeforeQuotaRename).await;
|
||||
@@ -5978,6 +6004,15 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if crash_inject::should_crash_at(CrashPoint::MultipartAfterCommitBeforePartsCleanup, &commit_object) {
|
||||
return Err(StorageError::Unexpected);
|
||||
}
|
||||
#[cfg(feature = "dst")]
|
||||
if should_dst_crash_multipart(
|
||||
&commit_disks,
|
||||
rustfs_dst_faults::crash::CrashPoint::MultipartAfterCommitBeforeCleanup,
|
||||
&commit_bucket,
|
||||
&commit_object,
|
||||
) {
|
||||
return Err(StorageError::Unexpected);
|
||||
}
|
||||
|
||||
fi = committed_file_info;
|
||||
let committed_dir = fi.data_dir.unwrap_or_default().to_string();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1926,7 +1926,7 @@ impl SetDisks {
|
||||
);
|
||||
}
|
||||
}
|
||||
let (reader_setup, reader_setup_elapsed) = match setup_result {
|
||||
let (mut reader_setup, mut reader_setup_elapsed) = match setup_result {
|
||||
Some(result) => result,
|
||||
None => {
|
||||
setup_multipart_part_readers(
|
||||
@@ -1934,7 +1934,7 @@ impl SetDisks {
|
||||
&disks,
|
||||
bucket,
|
||||
object,
|
||||
sync_spec,
|
||||
sync_spec.clone(),
|
||||
erasure.shard_size(),
|
||||
erasure.data_shards,
|
||||
erasure.parity_shards,
|
||||
@@ -1949,6 +1949,55 @@ impl SetDisks {
|
||||
}
|
||||
};
|
||||
|
||||
// If read quorum is about to fail because some remote disks are still in `Returning`
|
||||
// or `Offline` (e.g. immediately after a peer restarted in a rolling upgrade/rollback),
|
||||
// probe those faulty drives on demand once before failing with 503.
|
||||
if reader_setup.available_shards() < erasure.data_shards {
|
||||
let faulty_disks: Vec<DiskStore> = reader_setup
|
||||
.errors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, err)| {
|
||||
if matches!(err, Some(DiskError::FaultyDisk | DiskError::FaultyRemoteDisk)) {
|
||||
disks.get(idx).and_then(|d| d.as_ref()).filter(|d| d.is_faulty()).cloned()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if !faulty_disks.is_empty() {
|
||||
let mut probes: FuturesUnordered<_> = faulty_disks
|
||||
.into_iter()
|
||||
.map(|disk| async move { disk.probe_quorum_recovery_if_faulty().await })
|
||||
.collect();
|
||||
let mut recovered_any = false;
|
||||
while let Some(recovered) = probes.next().await {
|
||||
recovered_any |= recovered;
|
||||
}
|
||||
if recovered_any {
|
||||
let (retried_setup, retried_elapsed) = setup_multipart_part_readers(
|
||||
&files,
|
||||
&disks,
|
||||
bucket,
|
||||
object,
|
||||
sync_spec,
|
||||
erasure.shard_size(),
|
||||
erasure.data_shards,
|
||||
erasure.parity_shards,
|
||||
skip_verify_bitrot,
|
||||
use_mmap_read,
|
||||
prefer_data_blocks_first_reader_setup,
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
)
|
||||
.await;
|
||||
reader_setup = retried_setup;
|
||||
reader_setup_elapsed = reader_setup_elapsed.saturating_add(retried_elapsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Kick off the next part's reader setup before decoding this one
|
||||
// so the disk opens overlap with decode + client writeback
|
||||
// (backlog#870).
|
||||
@@ -1973,7 +2022,7 @@ impl SetDisks {
|
||||
let shard_size = erasure.shard_size();
|
||||
let data_shards = erasure.data_shards;
|
||||
let parity_shards = erasure.parity_shards;
|
||||
let handle = tokio::task::spawn(async move {
|
||||
let handle = tokio::task::spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
setup_multipart_part_readers(
|
||||
&files,
|
||||
&disks,
|
||||
@@ -1991,7 +2040,7 @@ impl SetDisks {
|
||||
metrics_size_bucket,
|
||||
)
|
||||
.await
|
||||
});
|
||||
}));
|
||||
prefetched = Some((next_part, PrefetchedReaderSetup::new(handle)));
|
||||
}
|
||||
rustfs_io_metrics::record_get_object_shard_reader_setup_duration(reader_setup_elapsed.as_secs_f64());
|
||||
@@ -2003,13 +2052,17 @@ impl SetDisks {
|
||||
reader_setup_elapsed.as_secs_f64(),
|
||||
);
|
||||
let setup_available_readers = reader_setup.available_shards();
|
||||
let request_id = crate::cluster::rpc::context_propagation::propagated_request_id();
|
||||
let version_id = fi.version_id.map(|v| v.to_string()).unwrap_or_default();
|
||||
if reader_setup_elapsed >= SLOW_OBJECT_READ_LOG_THRESHOLD {
|
||||
warn!(
|
||||
event = EVENT_SET_DISK_READ,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_SET_DISK,
|
||||
request_id = %request_id,
|
||||
bucket,
|
||||
object,
|
||||
version_id = %version_id,
|
||||
part_index = current_part,
|
||||
part_number,
|
||||
read_offset,
|
||||
@@ -2037,8 +2090,10 @@ impl SetDisks {
|
||||
event = EVENT_SET_DISK_READ,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_SET_DISK,
|
||||
request_id = %request_id,
|
||||
bucket,
|
||||
object,
|
||||
version_id = %version_id,
|
||||
part_index = current_part,
|
||||
part_number,
|
||||
part_offset,
|
||||
@@ -2065,8 +2120,10 @@ impl SetDisks {
|
||||
event = EVENT_SET_DISK_READ,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_SET_DISK,
|
||||
request_id = %request_id,
|
||||
bucket,
|
||||
object,
|
||||
version_id = %version_id,
|
||||
part_index = current_part,
|
||||
part_number,
|
||||
part_offset,
|
||||
@@ -2864,7 +2921,7 @@ impl SetDisks {
|
||||
let builder: LazyPartBuilder = Box::new(move |remaining_index| {
|
||||
let ctx = Arc::clone(&ctx);
|
||||
let (part_number, part_size) = remaining_parts[remaining_index];
|
||||
tokio::task::spawn(async move {
|
||||
tokio::task::spawn(crate::cluster::rpc::with_captured_request_id(async move {
|
||||
SetDisks::build_codec_streaming_part_reader(
|
||||
&ctx.bucket,
|
||||
&ctx.object,
|
||||
@@ -2892,7 +2949,7 @@ impl SetDisks {
|
||||
ctx.metrics_path,
|
||||
)
|
||||
.await
|
||||
})
|
||||
}))
|
||||
});
|
||||
|
||||
Ok(GetCodecStreamingReaderBuildOutcome::Reader(Box::new(
|
||||
@@ -3210,6 +3267,7 @@ impl AsyncRead for RepairReportingReader {
|
||||
}
|
||||
|
||||
/// Per-part parameters for a multipart bitrot reader setup.
|
||||
#[derive(Clone)]
|
||||
struct PartReaderSetupSpec {
|
||||
integrity: Option<rustfs_filemeta::shard_integrity::PartIntegrity>,
|
||||
part_number: usize,
|
||||
|
||||
@@ -326,7 +326,18 @@ impl ECStore {
|
||||
));
|
||||
}
|
||||
// Lock order: bucket lifecycle, then bucket/object and capacity locks used by healing.
|
||||
let fence = self.acquire_bucket_incarnation_fence(bucket, expected).await?;
|
||||
// DeleteBucket publishes a durable retirement record before removing `.bucket-incarnation`,
|
||||
// so a retired expected generation classifies as BucketNotFound rather than corrupt metadata.
|
||||
let fence = match self.acquire_bucket_incarnation_fence(bucket, expected).await {
|
||||
Ok(fence) => fence,
|
||||
Err(err @ StorageError::BucketNotFound(_)) => return Err(err),
|
||||
Err(err) => {
|
||||
if matches!(self.is_bucket_incarnation_retired(bucket, expected).await, Ok(true)) {
|
||||
return Err(StorageError::BucketNotFound(bucket.to_owned()));
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let scope = Arc::new(BucketHealScope {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: expected,
|
||||
|
||||
@@ -29,10 +29,10 @@ use http::HeaderMap;
|
||||
use rustfs_filemeta::FileMeta;
|
||||
use sha2::{Digest, Sha256};
|
||||
use storage_api::dst_production_ecstore::{
|
||||
BLOCK_SIZE_V2, BucketOperations, CHECK_PART_FILE_CORRUPT, CHECK_PART_SUCCESS, CrashPoint, CrashSemantics, DiskAPI,
|
||||
DstSimSetFixture, EcstoreResult, Error as EcstoreError, HealOperations, HealOpts, HealScanMode, MakeBucketOptions, ObjectIO,
|
||||
ObjectOperations, ObjectOptions, PutObjReader, ReadOptions, RngSource, STORAGE_FORMAT_FILE, SimDiskIoTrait, SimRng,
|
||||
dst_object_options, is_err_object_not_found, load_format_erasure, make_dst_sim_set_disks,
|
||||
BLOCK_SIZE_V2, BucketOperations, CHECK_PART_FILE_CORRUPT, CHECK_PART_SUCCESS, CompletePart, CrashPoint, CrashSemantics,
|
||||
DiskAPI, DstSimSetFixture, EcstoreResult, Error as EcstoreError, HealOperations, HealOpts, HealScanMode, MakeBucketOptions,
|
||||
MultipartOperations, ObjectIO, ObjectOperations, ObjectOptions, PutObjReader, ReadOptions, RngSource, STORAGE_FORMAT_FILE,
|
||||
SimDiskIoTrait, SimRng, dst_object_options, is_err_object_not_found, load_format_erasure, make_dst_sim_set_disks,
|
||||
};
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
@@ -742,3 +742,284 @@ async fn dst_prod_test4_deterministic_multiseed_concurrent_chaos_and_replay_equi
|
||||
assert_eq!(digest_run1, digest_run2, "deterministic replay invariant violated for seed {seed:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Test 5: Real ECStore multipart commit crash cutpoints (backlog#3390 P0-5):
|
||||
// - `fault.multipart_crashed_before_commit_rename`
|
||||
// (`CrashPoint::MultipartBeforeCommitRename`)
|
||||
// - `fault.multipart_crashed_before_cleanup`
|
||||
// (`CrashPoint::MultipartAfterCommitBeforeCleanup`)
|
||||
// ============================================================================
|
||||
#[tokio::test]
|
||||
async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_before_cleanup() {
|
||||
let opts = ObjectOptions::default();
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Cutpoint A: `fault.multipart_crashed_before_commit_rename` (4 seeds)
|
||||
// Pre-commit crash after parts are staged/locked, before rename_data commit:
|
||||
// 1. Real cutpoint fires and consumes its one-shot arm.
|
||||
// 2. After ALICE power-loss reboot, prior object v1 stays 100% intact
|
||||
// (and a brand-new key remains absent — zero partial visibility).
|
||||
// 3. Retrying `complete_multipart_upload` commits cleanly and reads back
|
||||
// 100% bit-exact concatenated multipart bytes.
|
||||
// ------------------------------------------------------------------------
|
||||
let mut before_rename_hits = 0usize;
|
||||
for &seed in &[0x4D50_0001_u64, 0x4D50_0002_u64, 0x4D50_0003_u64, 0x4D50_0004_u64] {
|
||||
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
|
||||
.await
|
||||
.expect("dst sim SetDisks for multipart pre-rename cutpoint");
|
||||
for sim in &fixture.sim_disks {
|
||||
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
|
||||
}
|
||||
let bucket = "dst-mp-before-rename";
|
||||
fixture
|
||||
.set_disks
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("make_bucket");
|
||||
|
||||
let overwrite_key = format!("mp/overwrite-before-rename-{seed:x}.bin");
|
||||
let fresh_key = format!("mp/fresh-before-rename-{seed:x}.bin");
|
||||
let v1_payload = deterministic_payload(seed, "mp-v1", BLOCK_SIZE_V2 + 12_288);
|
||||
put_bytes(&fixture, bucket, &overwrite_key, &v1_payload)
|
||||
.await
|
||||
.expect("commit baseline v1");
|
||||
|
||||
for (key, prior) in [(&overwrite_key, Some(&v1_payload)), (&fresh_key, None)] {
|
||||
let part1 = deterministic_payload(seed ^ 0x11, key, 5 * 1024 * 1024);
|
||||
let part2 = deterministic_payload(seed ^ 0x22, key, 65_536);
|
||||
let mut expected = Vec::with_capacity(part1.len() + part2.len());
|
||||
expected.extend_from_slice(&part1);
|
||||
expected.extend_from_slice(&part2);
|
||||
|
||||
let upload = fixture
|
||||
.set_disks
|
||||
.new_multipart_upload(bucket, key, &opts)
|
||||
.await
|
||||
.expect("new_multipart_upload");
|
||||
let mut r1 = PutObjReader::from_vec(part1);
|
||||
let p1 = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, key, &upload.upload_id, 1, &mut r1, &opts)
|
||||
.await
|
||||
.expect("put part 1");
|
||||
let mut r2 = PutObjReader::from_vec(part2);
|
||||
let p2 = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, key, &upload.upload_id, 2, &mut r2, &opts)
|
||||
.await
|
||||
.expect("put part 2");
|
||||
let parts = vec![
|
||||
CompletePart {
|
||||
part_num: 1,
|
||||
etag: p1.etag,
|
||||
..Default::default()
|
||||
},
|
||||
CompletePart {
|
||||
part_num: 2,
|
||||
etag: p2.etag,
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
|
||||
// Arm REAL ECStore cutpoint `MultipartBeforeCommitRename`.
|
||||
fixture.crash_registry.arm(CrashPoint::MultipartBeforeCommitRename, key);
|
||||
let crashed = fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, key, &upload.upload_id, parts.clone(), &opts)
|
||||
.await;
|
||||
assert!(
|
||||
crashed.is_err(),
|
||||
"seed={seed:#x} key={key}: MultipartBeforeCommitRename must abort complete_multipart_upload"
|
||||
);
|
||||
assert!(
|
||||
!fixture
|
||||
.crash_registry
|
||||
.take_if_armed(CrashPoint::MultipartBeforeCommitRename, key),
|
||||
"seed={seed:#x} key={key}: real ECStore MultipartBeforeCommitRename cutpoint must have fired"
|
||||
);
|
||||
before_rename_hits += 1;
|
||||
|
||||
// Simulate abrupt ALICE power loss right at the cutpoint.
|
||||
fixture.crash_and_reboot_all();
|
||||
|
||||
// Verify zero corrupt xl.meta and zero partial visibility.
|
||||
for (slot, sim_disk) in fixture.sim_disks.iter().enumerate() {
|
||||
let xl_rel = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}");
|
||||
if let Ok(raw) = SimDiskIoTrait::read_file(sim_disk.sim(), &xl_rel).await {
|
||||
assert!(
|
||||
FileMeta::load(&raw).is_ok(),
|
||||
"corrupt xl.meta on drive {slot} after MultipartBeforeCommitRename"
|
||||
);
|
||||
}
|
||||
}
|
||||
match prior {
|
||||
Some(v1) => {
|
||||
assert_eq!(
|
||||
get_bytes(&fixture, bucket, key).await.expect("prior v1 must remain intact"),
|
||||
*v1,
|
||||
"pre-rename crash must leave prior object v1 bit-exact"
|
||||
);
|
||||
}
|
||||
None => {
|
||||
let res = get_bytes(&fixture, bucket, key).await;
|
||||
assert!(
|
||||
res.is_err() && is_err_object_not_found(res.as_ref().unwrap_err()),
|
||||
"pre-rename crash on fresh key must not expose partial object: {res:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Retrying completion after reboot must succeed cleanly and commit full multipart payload!
|
||||
fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, key, &upload.upload_id, parts, &opts)
|
||||
.await
|
||||
.expect("retry complete_multipart_upload after pre-rename crash must succeed");
|
||||
assert_eq!(
|
||||
get_bytes(&fixture, bucket, key).await.expect("read retried multipart object"),
|
||||
expected,
|
||||
"retried multipart object bytes must match part1 || part2"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
before_rename_hits, 8,
|
||||
"fault.multipart_crashed_before_commit_rename must hit across all 4 seeds (overwrite + fresh)"
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Cutpoint B: `fault.multipart_crashed_before_cleanup` (4 seeds)
|
||||
// Post-commit crash after authoritative `rename_data` commit succeeds,
|
||||
// before stale part staging cleanup:
|
||||
// 1. Real cutpoint fires and consumes its one-shot arm.
|
||||
// 2. After ALICE power-loss reboot, newly committed multipart payload is
|
||||
// 100% durably readable (zero data loss!).
|
||||
// 3. All 4 drives have valid xl.meta and pass HighwayHash256S `verify_file`
|
||||
// after post-crash heal.
|
||||
// ------------------------------------------------------------------------
|
||||
let mut before_cleanup_hits = 0usize;
|
||||
for &seed in &[0x4D50_0101_u64, 0x4D50_0102_u64, 0x4D50_0103_u64, 0x4D50_0104_u64] {
|
||||
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
|
||||
.await
|
||||
.expect("dst sim SetDisks for multipart pre-cleanup cutpoint");
|
||||
for sim in &fixture.sim_disks {
|
||||
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
|
||||
}
|
||||
let bucket = "dst-mp-before-cleanup";
|
||||
fixture
|
||||
.set_disks
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("make_bucket");
|
||||
|
||||
let key = format!("mp/committed-before-cleanup-{seed:x}.bin");
|
||||
let part1 = deterministic_payload(seed ^ 0x33, &key, 5 * 1024 * 1024);
|
||||
let part2 = deterministic_payload(seed ^ 0x44, &key, 98_304);
|
||||
let mut expected = Vec::with_capacity(part1.len() + part2.len());
|
||||
expected.extend_from_slice(&part1);
|
||||
expected.extend_from_slice(&part2);
|
||||
|
||||
let upload = fixture
|
||||
.set_disks
|
||||
.new_multipart_upload(bucket, &key, &opts)
|
||||
.await
|
||||
.expect("new_multipart_upload");
|
||||
let mut r1 = PutObjReader::from_vec(part1);
|
||||
let p1 = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, &key, &upload.upload_id, 1, &mut r1, &opts)
|
||||
.await
|
||||
.expect("put part 1");
|
||||
let mut r2 = PutObjReader::from_vec(part2);
|
||||
let p2 = fixture
|
||||
.set_disks
|
||||
.put_object_part(bucket, &key, &upload.upload_id, 2, &mut r2, &opts)
|
||||
.await
|
||||
.expect("put part 2");
|
||||
let parts = vec![
|
||||
CompletePart {
|
||||
part_num: 1,
|
||||
etag: p1.etag,
|
||||
..Default::default()
|
||||
},
|
||||
CompletePart {
|
||||
part_num: 2,
|
||||
etag: p2.etag,
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
|
||||
// Arm REAL ECStore cutpoint `MultipartAfterCommitBeforeCleanup`.
|
||||
fixture
|
||||
.crash_registry
|
||||
.arm(CrashPoint::MultipartAfterCommitBeforeCleanup, &key);
|
||||
let crashed = fixture
|
||||
.set_disks
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
|
||||
.await;
|
||||
assert!(
|
||||
crashed.is_err(),
|
||||
"seed={seed:#x}: MultipartAfterCommitBeforeCleanup must interrupt complete_multipart_upload"
|
||||
);
|
||||
assert!(
|
||||
!fixture
|
||||
.crash_registry
|
||||
.take_if_armed(CrashPoint::MultipartAfterCommitBeforeCleanup, &key),
|
||||
"seed={seed:#x}: real ECStore MultipartAfterCommitBeforeCleanup cutpoint must have fired"
|
||||
);
|
||||
before_cleanup_hits += 1;
|
||||
|
||||
// Simulate abrupt ALICE power loss right after commit before cleanup.
|
||||
fixture.crash_and_reboot_all();
|
||||
|
||||
// Newly committed multipart object MUST survive power loss 100% bit-exact!
|
||||
assert_eq!(
|
||||
get_bytes(&fixture, bucket, &key)
|
||||
.await
|
||||
.expect("committed multipart object must survive pre-cleanup power loss"),
|
||||
expected,
|
||||
"seed={seed:#x}: committed multipart payload must be bit-exact after pre-cleanup crash"
|
||||
);
|
||||
|
||||
// Post-crash heal converges cleanly and every drive verifies both parts!
|
||||
let (_heal_item, heal_err) = fixture
|
||||
.set_disks
|
||||
.heal_object(
|
||||
bucket,
|
||||
&key,
|
||||
"",
|
||||
&HealOpts {
|
||||
scan_mode: HealScanMode::Deep,
|
||||
remove: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("post-crash heal_object");
|
||||
assert!(heal_err.is_none(), "post-crash heal error: {heal_err:?}");
|
||||
|
||||
for (slot, disk) in fixture.disks.iter().enumerate() {
|
||||
let fi = disk
|
||||
.read_version("", bucket, &key, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("xl.meta readable on all drives after pre-cleanup crash");
|
||||
let check = disk
|
||||
.verify_file(bucket, &key, &fi)
|
||||
.await
|
||||
.expect("verify_file on committed multipart object");
|
||||
assert_eq!(
|
||||
check.results,
|
||||
vec![CHECK_PART_SUCCESS, CHECK_PART_SUCCESS],
|
||||
"drive {slot} must pass HighwayHash256S verification for both parts"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
before_cleanup_hits, 4,
|
||||
"fault.multipart_crashed_before_cleanup must hit across all 4 seeds"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -106,7 +106,9 @@ pub(crate) mod local_drive_retirement {
|
||||
|
||||
#[cfg(feature = "dst")]
|
||||
pub(crate) mod dst_production_ecstore {
|
||||
pub(crate) use super::storage_contracts::{BucketOperations, HealOperations, MakeBucketOptions, ObjectIO, ObjectOperations};
|
||||
pub(crate) use super::storage_contracts::{
|
||||
BucketOperations, CompletePart, HealOperations, MakeBucketOptions, MultipartOperations, ObjectIO, ObjectOperations,
|
||||
};
|
||||
pub(crate) use super::{DiskAPI, Error, ObjectOptions, PutObjReader, STORAGE_FORMAT_FILE};
|
||||
pub(crate) use rustfs_ecstore::api::{
|
||||
disk::ReadOptions,
|
||||
|
||||
@@ -2275,7 +2275,9 @@ impl MetaObjectV1 {
|
||||
|
||||
rmp::encode::write_str(wr, "Meta")?;
|
||||
rmp::encode::write_map_len(wr, self.meta.len() as u32)?;
|
||||
for (k, v) in &self.meta {
|
||||
let mut sorted_meta: Vec<(&String, &String)> = self.meta.iter().collect();
|
||||
sorted_meta.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_meta {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -2590,7 +2592,9 @@ impl MetaObjectV1Part {
|
||||
if let Some(ref checksums) = self.checksums {
|
||||
rmp::encode::write_str(wr, "crc")?;
|
||||
rmp::encode::write_map_len(wr, checksums.len() as u32)?;
|
||||
for (k, v) in checksums {
|
||||
let mut sorted_checksums: Vec<(&String, &String)> = checksums.iter().collect();
|
||||
sorted_checksums.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_checksums {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -2801,25 +2805,29 @@ impl MetaObject {
|
||||
let nanos = self.mod_time.unwrap_or(OffsetDateTime::UNIX_EPOCH).unix_timestamp_nanos();
|
||||
rmp::encode::write_sint(wr, nanos as i64)?;
|
||||
|
||||
// MetaSys (write nil when empty)
|
||||
// MetaSys (write nil when empty; sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
rmp::encode::write_str(wr, "MetaSys")?;
|
||||
if !include_maps || self.meta_sys.is_empty() {
|
||||
rmp::encode::write_nil(wr)?;
|
||||
} else {
|
||||
rmp::encode::write_map_len(wr, self.meta_sys.len() as u32)?;
|
||||
for (k, v) in &self.meta_sys {
|
||||
let mut sorted_meta_sys: Vec<(&String, &Vec<u8>)> = self.meta_sys.iter().collect();
|
||||
sorted_meta_sys.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_meta_sys {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_bin(wr, v)?;
|
||||
}
|
||||
}
|
||||
|
||||
// MetaUsr (write nil when empty)
|
||||
// MetaUsr (write nil when empty; sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
rmp::encode::write_str(wr, "MetaUsr")?;
|
||||
if !include_maps || self.meta_user.is_empty() {
|
||||
rmp::encode::write_nil(wr)?;
|
||||
} else {
|
||||
rmp::encode::write_map_len(wr, self.meta_user.len() as u32)?;
|
||||
for (k, v) in &self.meta_user {
|
||||
let mut sorted_meta_user: Vec<(&String, &String)> = self.meta_user.iter().collect();
|
||||
sorted_meta_user.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_meta_user {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_str(wr, v)?;
|
||||
}
|
||||
@@ -3891,13 +3899,15 @@ impl MetaDeleteMarker {
|
||||
let nanos = self.mod_time.unwrap_or(OffsetDateTime::UNIX_EPOCH).unix_timestamp_nanos();
|
||||
rmp::encode::write_sint(wr, nanos as i64)?;
|
||||
|
||||
// MetaSys
|
||||
// MetaSys (sort keys for deterministic xl.meta bytes across heals/restarts)
|
||||
rmp::encode::write_str(wr, "MetaSys")?;
|
||||
if !include_meta_sys || self.meta_sys.is_empty() {
|
||||
rmp::encode::write_map_len(wr, 0)?;
|
||||
} else {
|
||||
rmp::encode::write_map_len(wr, self.meta_sys.len() as u32)?;
|
||||
for (k, v) in &self.meta_sys {
|
||||
let mut sorted_meta_sys: Vec<(&String, &Vec<u8>)> = self.meta_sys.iter().collect();
|
||||
sorted_meta_sys.sort_unstable_by_key(|(a, _)| *a);
|
||||
for (k, v) in sorted_meta_sys {
|
||||
rmp::encode::write_str(wr, k)?;
|
||||
rmp::encode::write_bin(wr, v)?;
|
||||
}
|
||||
@@ -7049,4 +7059,80 @@ mod read_xl_meta_sync_equivalence_tests {
|
||||
assert_eq!(e, Error::Unexpected, "short read surfaces as Unexpected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xl_meta_encoding_is_deterministic_across_hash_map_orders() {
|
||||
let version_id = Some(Uuid::from_u128(0x11223344_5566_7788_99aa_bbccddeeff00));
|
||||
let mod_time = Some(OffsetDateTime::from_unix_timestamp(1_735_000_000).unwrap());
|
||||
|
||||
let build_obj = |reverse: bool| {
|
||||
let mut meta_sys = HashMap::new();
|
||||
let mut meta_user = HashMap::new();
|
||||
let sys_entries = [
|
||||
("x-rustfs-internal-a", b"alpha".to_vec()),
|
||||
("x-rustfs-internal-z", b"omega".to_vec()),
|
||||
("x-rustfs-internal-m", b"middle".to_vec()),
|
||||
("x-rustfs-internal-c", b"charlie".to_vec()),
|
||||
];
|
||||
let usr_entries = [
|
||||
("content-type", "application/octet-stream"),
|
||||
("etag", "0123456789abcdef0123456789abcdef"),
|
||||
("x-amz-meta-z", "last"),
|
||||
("x-amz-meta-a", "first"),
|
||||
];
|
||||
if reverse {
|
||||
for (k, v) in sys_entries.iter().rev() {
|
||||
meta_sys.insert((*k).to_string(), v.clone());
|
||||
}
|
||||
for (k, v) in usr_entries.iter().rev() {
|
||||
meta_user.insert((*k).to_string(), (*v).to_string());
|
||||
}
|
||||
} else {
|
||||
for (k, v) in sys_entries {
|
||||
meta_sys.insert(k.to_string(), v);
|
||||
}
|
||||
for (k, v) in usr_entries {
|
||||
meta_user.insert(k.to_string(), v.to_string());
|
||||
}
|
||||
}
|
||||
MetaObject {
|
||||
version_id,
|
||||
mod_time,
|
||||
size: 262_144,
|
||||
meta_sys,
|
||||
meta_user,
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
|
||||
let first = build_obj(false).marshal_msg().expect("marshal first");
|
||||
for i in 0..32 {
|
||||
let candidate = build_obj(i % 2 == 1).marshal_msg().expect("marshal candidate");
|
||||
assert_eq!(first, candidate, "xl.meta object bytes must be deterministic on iteration {i}");
|
||||
}
|
||||
|
||||
let build_dm = |reverse: bool| {
|
||||
let mut meta_sys = HashMap::new();
|
||||
let entries = [("k3", b"3".to_vec()), ("k1", b"1".to_vec()), ("k2", b"2".to_vec())];
|
||||
if reverse {
|
||||
for (k, v) in entries.iter().rev() {
|
||||
meta_sys.insert((*k).to_string(), v.clone());
|
||||
}
|
||||
} else {
|
||||
for (k, v) in entries {
|
||||
meta_sys.insert(k.to_string(), v);
|
||||
}
|
||||
}
|
||||
MetaDeleteMarker {
|
||||
version_id,
|
||||
mod_time,
|
||||
meta_sys,
|
||||
}
|
||||
};
|
||||
let dm_first = build_dm(false).marshal_msg().expect("marshal dm first");
|
||||
for i in 0..32 {
|
||||
let dm_candidate = build_dm(i % 2 == 1).marshal_msg().expect("marshal dm candidate");
|
||||
assert_eq!(dm_first, dm_candidate, "xl.meta delete marker bytes must be deterministic");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -539,7 +539,7 @@ impl PriorityHealQueue {
|
||||
|
||||
let chosen_index = first_runnable.filter(|index| {
|
||||
let item = &items[*index];
|
||||
item.priority == HealPriority::Normal
|
||||
matches!(item.priority, HealPriority::Normal | HealPriority::High)
|
||||
&& matches!(item.request.source, HealRequestSource::Mrf | HealRequestSource::Internal)
|
||||
});
|
||||
let best_effort_priority = best_effort_candidates
|
||||
@@ -573,7 +573,7 @@ impl PriorityHealQueue {
|
||||
self.mrf_normal_dispatches_since_best_effort = 0;
|
||||
self.last_best_effort_source = Some(request.source);
|
||||
} else if matches!(request.source, HealRequestSource::Mrf | HealRequestSource::Internal)
|
||||
&& request.priority == HealPriority::Normal
|
||||
&& matches!(request.priority, HealPriority::Normal | HealPriority::High)
|
||||
{
|
||||
self.mrf_normal_dispatches_since_best_effort = self.mrf_normal_dispatches_since_best_effort.saturating_add(1);
|
||||
}
|
||||
|
||||
@@ -274,6 +274,12 @@ impl HealManager {
|
||||
"Heal scheduler task started"
|
||||
);
|
||||
let result = task.execute_owned(parent.clone()).await;
|
||||
crate::heal::mrf_queue::management::record_heal_source_executed(task.source);
|
||||
if task.source == HealRequestSource::Mrf
|
||||
&& matches!(&result, Err(err) if err.to_string().contains("recreate_failed"))
|
||||
{
|
||||
crate::heal::mrf_queue::management::record_mrf_recreate_failed_loop();
|
||||
}
|
||||
let retry_request = retry_request_for_result_with_budget(task.as_ref(), &result).await;
|
||||
record_task_disposition(&disposition_cache_clone, task.as_ref(), &result, retry_request.is_some()).await;
|
||||
match &result {
|
||||
|
||||
@@ -2580,6 +2580,48 @@ fn test_priority_queue_fairness_skips_blocked_best_effort_source() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_priority_queue_fairness_prevents_high_priority_mrf_from_starving_scanner() {
|
||||
let mut queue = PriorityHealQueue::new();
|
||||
for index in 0..8 {
|
||||
assert_eq!(
|
||||
queue.push(bucket_request(&format!("mrf-high-{index}"), HealPriority::High, HealRequestSource::Mrf)),
|
||||
QueuePushOutcome::Accepted
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
queue.push(bucket_request("scanner", HealPriority::Low, HealRequestSource::Scanner)),
|
||||
QueuePushOutcome::Accepted
|
||||
);
|
||||
assert_eq!(
|
||||
queue.push(bucket_request("read-repair", HealPriority::Low, HealRequestSource::ReadRepair)),
|
||||
QueuePushOutcome::Accepted
|
||||
);
|
||||
|
||||
for _ in 0..4 {
|
||||
let (request, _) = queue.pop_runnable_with_fairness(|_| true, |_| None);
|
||||
assert_eq!(request.expect("High MRF quantum should run").source, HealRequestSource::Mrf);
|
||||
}
|
||||
let (request, _) = queue.pop_runnable_with_fairness(|_| true, |_| None);
|
||||
assert_eq!(
|
||||
request
|
||||
.expect("Scanner must not be starved by High-priority MRF burst")
|
||||
.source,
|
||||
HealRequestSource::Scanner
|
||||
);
|
||||
for _ in 0..4 {
|
||||
let (request, _) = queue.pop_runnable_with_fairness(|_| true, |_| None);
|
||||
assert_eq!(request.expect("Next High MRF quantum should run").source, HealRequestSource::Mrf);
|
||||
}
|
||||
let (request, _) = queue.pop_runnable_with_fairness(|_| true, |_| None);
|
||||
assert_eq!(
|
||||
request
|
||||
.expect("ReadRepair must not be starved by High-priority MRF burst")
|
||||
.source,
|
||||
HealRequestSource::ReadRepair
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_priority_queue_fifo_same_priority() {
|
||||
let mut queue = PriorityHealQueue::new();
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//! Bounded runtime observations. These values never authorize lifecycle changes or prove retirement.
|
||||
|
||||
use super::{GLOBAL_MRF_LIFECYCLE_SENDER, MrfLegacyResponsibility, MrfLifecycleCommand, MrfLifecycleControlError, MrfRuntime};
|
||||
use rustfs_heal_contracts::heal_channel::HealRequestSource;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock, RwLock};
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc, oneshot};
|
||||
use uuid::Uuid;
|
||||
@@ -12,6 +14,28 @@ use uuid::Uuid;
|
||||
const READ_CAPACITY: usize = 8;
|
||||
static READ_BUDGET: LazyLock<Arc<Semaphore>> = LazyLock::new(|| Arc::new(Semaphore::new(READ_CAPACITY)));
|
||||
static SUMMARY: RwLock<Option<MrfLifecycleSummary>> = RwLock::new(None);
|
||||
static SCANNER_HEAL_EXECUTED: AtomicU64 = AtomicU64::new(0);
|
||||
static READ_REPAIR_EXECUTED: AtomicU64 = AtomicU64::new(0);
|
||||
static MRF_RECREATE_FAILED_LOOPS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Records lifetime execution of a scheduled heal task by source for MRF
|
||||
/// anti-starvation and discharge telemetry.
|
||||
pub(crate) fn record_heal_source_executed(source: HealRequestSource) {
|
||||
match source {
|
||||
HealRequestSource::Scanner => {
|
||||
SCANNER_HEAL_EXECUTED.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
HealRequestSource::ReadRepair => {
|
||||
READ_REPAIR_EXECUTED.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records an MRF task retry/error caused by an absent-object recreate failure loop.
|
||||
pub(crate) fn record_mrf_recreate_failed_loop() {
|
||||
MRF_RECREATE_FAILED_LOOPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -28,6 +52,12 @@ pub struct MrfLifecycleSummary {
|
||||
pub operator_accepted_count: usize,
|
||||
pub best_effort_queue_depth: usize,
|
||||
pub responsibility_bytes: usize,
|
||||
#[serde(default)]
|
||||
pub scanner_heal_executed: u64,
|
||||
#[serde(default)]
|
||||
pub read_repair_executed: u64,
|
||||
#[serde(default)]
|
||||
pub recreate_failed_loops: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -47,11 +77,15 @@ pub fn lifecycle_summary() -> Result<MrfLifecycleSummary, MrfLifecycleControlErr
|
||||
if GLOBAL_MRF_LIFECYCLE_SENDER.get().is_none_or(mpsc::Sender::is_closed) {
|
||||
return Err(MrfLifecycleControlError::Unavailable);
|
||||
}
|
||||
SUMMARY
|
||||
let mut summary = SUMMARY
|
||||
.read()
|
||||
.map_err(|_| MrfLifecycleControlError::Unavailable)?
|
||||
.clone()
|
||||
.ok_or(MrfLifecycleControlError::Unavailable)
|
||||
.ok_or(MrfLifecycleControlError::Unavailable)?;
|
||||
summary.scanner_heal_executed = SCANNER_HEAL_EXECUTED.load(Ordering::Relaxed);
|
||||
summary.read_repair_executed = READ_REPAIR_EXECUTED.load(Ordering::Relaxed);
|
||||
summary.recreate_failed_loops = MRF_RECREATE_FAILED_LOOPS.load(Ordering::Relaxed);
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
/// Observes one current responsibility, including Active entries excluded from legacy lists.
|
||||
@@ -117,6 +151,9 @@ pub(super) fn publish_summary(runtime: &MrfRuntime, counts: &super::partial_writ
|
||||
operator_accepted_count: counts.operator_accepted_count,
|
||||
best_effort_queue_depth: runtime.queue.depth(),
|
||||
responsibility_bytes: runtime.partial_writes.bytes(),
|
||||
scanner_heal_executed: SCANNER_HEAL_EXECUTED.load(Ordering::Relaxed),
|
||||
read_repair_executed: READ_REPAIR_EXECUTED.load(Ordering::Relaxed),
|
||||
recreate_failed_loops: MRF_RECREATE_FAILED_LOOPS.load(Ordering::Relaxed),
|
||||
};
|
||||
if let Ok(mut published) = SUMMARY.write() {
|
||||
*published = Some(summary);
|
||||
|
||||
@@ -1565,6 +1565,7 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
|
||||
match self.live_ecstore().get_bucket_info(bucket, &Default::default()).await {
|
||||
Ok(info) => Ok(Some(info)),
|
||||
Err(StorageError::VolumeNotFound | StorageError::BucketNotFound(_)) => Ok(None),
|
||||
Err(e) => {
|
||||
error!(
|
||||
target: "rustfs::heal::storage",
|
||||
@@ -1583,13 +1584,8 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
}
|
||||
|
||||
async fn mrf_bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
|
||||
match self.live_ecstore().bucket_incarnation_id(bucket).await {
|
||||
Ok(incarnation) => Ok(Some(incarnation)),
|
||||
// A missing bucket leaves the current identity unresolved. It is
|
||||
// not a retirement receipt for an unknown source generation.
|
||||
Err(StorageError::BucketNotFound(_)) => Ok(None),
|
||||
Err(error) => Err(Error::Storage(error)),
|
||||
}
|
||||
// A missing identity leaves the source generation unresolved for MRF replay.
|
||||
self.bucket_incarnation_id(bucket).await
|
||||
}
|
||||
|
||||
async fn replacement_bucket_incarnation(&self, bucket: &str) -> Result<Option<Uuid>> {
|
||||
@@ -1834,11 +1830,11 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
}
|
||||
|
||||
async fn bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
|
||||
self.live_ecstore()
|
||||
.bucket_incarnation_id(bucket)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(Error::Storage)
|
||||
match self.live_ecstore().bucket_incarnation_id(bucket).await {
|
||||
Ok(id) => Ok(Some(id)),
|
||||
Err(StorageError::BucketNotFound(_)) => Ok(None),
|
||||
Err(error) => Err(Error::Storage(error)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn heal_object(
|
||||
@@ -1899,7 +1895,10 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
self.live_ecstore()
|
||||
.recover_delete_transactions_at_incarnation(bucket, object, expected, opts)
|
||||
.await
|
||||
.map_err(Error::Storage)
|
||||
.map_err(|error| match expected {
|
||||
Some(expected) => incarnation_storage_error(bucket, expected, error),
|
||||
None => Error::Storage(error),
|
||||
})
|
||||
}
|
||||
|
||||
async fn recover_delete_prefix_transactions(
|
||||
@@ -1912,7 +1911,10 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
self.live_ecstore()
|
||||
.recover_delete_prefix_at_incarnation(bucket, prefix, expected, opts)
|
||||
.await
|
||||
.map_err(Error::Storage)
|
||||
.map_err(|error| match expected {
|
||||
Some(expected) => incarnation_storage_error(bucket, expected, error),
|
||||
None => Error::Storage(error),
|
||||
})
|
||||
}
|
||||
|
||||
async fn heal_bucket(&self, bucket: &str, opts: &HealOpts) -> Result<HealResultItem> {
|
||||
|
||||
@@ -461,12 +461,15 @@ impl HealTask {
|
||||
}
|
||||
|
||||
// Step 3: Heal bucket structure
|
||||
// Check control flags before each iteration to ensure timely cancellation.
|
||||
// Non-replacement AutoHeal runs (crash recovery and directory-backed fallback)
|
||||
// operate on a bucket-name snapshot taken earlier. Fence each bucket's repair
|
||||
// by its live incarnation so a concurrently deleted bucket is never recreated.
|
||||
let auto_bucket_fence = self.source == HealRequestSource::AutoHeal && replacement_resume.is_none();
|
||||
let bucket_heal_opts = HealOpts {
|
||||
recursive: false,
|
||||
dry_run: self.options.dry_run,
|
||||
remove: false,
|
||||
recreate: self.options.recreate_missing,
|
||||
recreate: self.options.recreate_missing && !auto_bucket_fence,
|
||||
scan_mode: self.options.scan_mode,
|
||||
update_parity: self.options.update_parity,
|
||||
no_lock: self.options.no_lock,
|
||||
@@ -485,6 +488,11 @@ impl HealTask {
|
||||
}
|
||||
let expected = if let Some((_, manager, _)) = replacement_resume.as_ref() {
|
||||
Some(manager.replacement_bucket_incarnation(bucket).await?)
|
||||
} else if auto_bucket_fence {
|
||||
let Some(incarnation) = self.await_with_control(self.storage.bucket_incarnation_id(bucket)).await? else {
|
||||
continue;
|
||||
};
|
||||
Some(incarnation)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -500,6 +508,7 @@ impl HealTask {
|
||||
Ok(result) => {
|
||||
self.record_result_item(result).await;
|
||||
}
|
||||
Err(Error::StaleBucketIncarnation { .. }) if auto_bucket_fence => continue,
|
||||
Err(err) => {
|
||||
// Cancellation and timeout keep their classification; only
|
||||
// a storage failure may be reclassified as a namespace change.
|
||||
@@ -524,15 +533,20 @@ impl HealTask {
|
||||
}
|
||||
}
|
||||
// Adopt delete proofs only after their publication bucket exists.
|
||||
if let Some(result) = self
|
||||
match self
|
||||
.await_with_control(
|
||||
self.storage
|
||||
.recover_delete_transactions(bucket, None, expected, &bucket_heal_opts),
|
||||
)
|
||||
.await?
|
||||
.await
|
||||
{
|
||||
unresolved_delete_recovery |= result.delete_recovery.is_some_and(|status| status.has_unresolved());
|
||||
self.record_result_item(result).await;
|
||||
Ok(Some(result)) => {
|
||||
unresolved_delete_recovery |= result.delete_recovery.is_some_and(|status| status.has_unresolved());
|
||||
self.record_result_item(result).await;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(Error::StaleBucketIncarnation { .. }) if auto_bucket_fence => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1712,6 +1712,7 @@ struct MockStorage {
|
||||
object_heal_detail: Option<String>,
|
||||
object_heal_item: Option<HealResultItem>,
|
||||
bucket_incarnation_id: Mutex<Option<Uuid>>,
|
||||
bucket_incarnation_by_name: Mutex<HashMap<String, Option<Uuid>>>,
|
||||
bucket_incarnation_after_object_heal: Mutex<Option<Uuid>>,
|
||||
bucket_incarnation_after_listing: Mutex<Option<Uuid>>,
|
||||
bucket_incarnation_unavailable: Mutex<bool>,
|
||||
@@ -2460,10 +2461,13 @@ impl HealStorageAPI for MockStorage {
|
||||
Ok(self.object_exists.lock().unwrap().unwrap_or(true))
|
||||
}
|
||||
|
||||
async fn bucket_incarnation_id(&self, _bucket: &str) -> Result<Option<Uuid>> {
|
||||
async fn bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
|
||||
if *self.bucket_incarnation_unavailable.lock().unwrap() {
|
||||
return Err(Error::Other("bucket incarnation unavailable".to_string()));
|
||||
}
|
||||
if let Some(incarnation) = self.bucket_incarnation_by_name.lock().unwrap().get(bucket).copied() {
|
||||
return Ok(incarnation);
|
||||
}
|
||||
Ok(*self.bucket_incarnation_id.lock().unwrap())
|
||||
}
|
||||
|
||||
@@ -5932,3 +5936,129 @@ async fn replacement_owned_mutation_panic_keeps_manager_join_failed() {
|
||||
assert!(manager.stop().await.is_err(), "actual child panic must fail the manager owner");
|
||||
assert!(manager.stop().await.is_err(), "repeat drain cannot erase the child panic");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn crash_recovery_skips_deleted_bucket_and_fences_live_bucket_without_recreate() {
|
||||
let temp = TempDir::new().expect("temporary resume disk directory should be created");
|
||||
let disk = make_resume_disk(&temp).await;
|
||||
let live_incarnation = Uuid::from_u128(101);
|
||||
let storage = Arc::new(MockStorage {
|
||||
resume_disk: Mutex::new(Some(disk)),
|
||||
bucket_incarnation_by_name: Mutex::new(HashMap::from([
|
||||
("deleted-bucket".to_string(), None),
|
||||
("live-bucket".to_string(), Some(live_incarnation)),
|
||||
])),
|
||||
..Default::default()
|
||||
});
|
||||
let mut request = HealRequest::new(
|
||||
HealType::ErasureSet {
|
||||
buckets: vec!["deleted-bucket".to_string(), "live-bucket".to_string()],
|
||||
set_disk_id: "pool_0_set_0".to_string(),
|
||||
},
|
||||
HealOptions {
|
||||
recreate_missing: true,
|
||||
timeout: None,
|
||||
..Default::default()
|
||||
},
|
||||
HealPriority::Low,
|
||||
);
|
||||
request.source = HealRequestSource::AutoHeal;
|
||||
let task = HealTask::from_request(request, storage.clone());
|
||||
|
||||
task.execute()
|
||||
.await
|
||||
.expect("crash-recovery erasure set heal should skip deleted buckets and complete");
|
||||
|
||||
assert_eq!(
|
||||
storage.bucket_heal_calls.lock().expect("bucket heal calls").as_slice(),
|
||||
&["live-bucket".to_string()],
|
||||
"deleted bucket must not invoke bucket-structure heal"
|
||||
);
|
||||
assert_eq!(
|
||||
storage
|
||||
.delete_recovery_calls
|
||||
.lock()
|
||||
.expect("delete recovery calls")
|
||||
.as_slice(),
|
||||
&["live-bucket".to_string()],
|
||||
"deleted bucket must not invoke delete-transaction recovery"
|
||||
);
|
||||
let opts = storage.bucket_heal_opts.lock().expect("bucket heal opts");
|
||||
assert_eq!(opts.len(), 1);
|
||||
assert!(
|
||||
!opts[0].recreate,
|
||||
"crash-recovery bucket prepass must keep recreate=false so only validated partial loss reconstructs"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn crash_recovery_skips_stale_incarnation_during_bucket_heal_and_delete_recovery() {
|
||||
let temp = TempDir::new().expect("temporary resume disk directory should be created");
|
||||
let disk = make_resume_disk(&temp).await;
|
||||
let stale_prepass = Uuid::from_u128(201);
|
||||
let stale_recovery = Uuid::from_u128(202);
|
||||
let live = Uuid::from_u128(203);
|
||||
let storage = Arc::new(MockStorage {
|
||||
resume_disk: Mutex::new(Some(disk)),
|
||||
bucket_incarnation_by_name: Mutex::new(HashMap::from([
|
||||
("deleted-during-prepass".to_string(), Some(stale_prepass)),
|
||||
("deleted-during-recovery".to_string(), Some(stale_recovery)),
|
||||
("live-bucket".to_string(), Some(live)),
|
||||
])),
|
||||
typed_bucket_heal_errors: Mutex::new(HashMap::from([(
|
||||
"deleted-during-prepass".to_string(),
|
||||
VecDeque::from([Error::StaleBucketIncarnation {
|
||||
bucket: "deleted-during-prepass".to_string(),
|
||||
expected: Some(stale_prepass),
|
||||
}]),
|
||||
)])),
|
||||
delete_recovery_results: Mutex::new(HashMap::from([(
|
||||
"deleted-during-recovery".to_string(),
|
||||
Err(Error::StaleBucketIncarnation {
|
||||
bucket: "deleted-during-recovery".to_string(),
|
||||
expected: Some(stale_recovery),
|
||||
}),
|
||||
)])),
|
||||
..Default::default()
|
||||
});
|
||||
let mut request = HealRequest::new(
|
||||
HealType::ErasureSet {
|
||||
buckets: vec![
|
||||
"deleted-during-prepass".to_string(),
|
||||
"deleted-during-recovery".to_string(),
|
||||
"live-bucket".to_string(),
|
||||
],
|
||||
set_disk_id: "pool_0_set_0".to_string(),
|
||||
},
|
||||
HealOptions {
|
||||
recreate_missing: true,
|
||||
timeout: None,
|
||||
..Default::default()
|
||||
},
|
||||
HealPriority::Low,
|
||||
);
|
||||
request.source = HealRequestSource::AutoHeal;
|
||||
let task = HealTask::from_request(request, storage.clone());
|
||||
|
||||
task.execute()
|
||||
.await
|
||||
.expect("concurrent bucket deletion during prepass or delete recovery must not fail crash recovery");
|
||||
|
||||
assert_eq!(
|
||||
storage.bucket_heal_calls.lock().expect("bucket heal calls").as_slice(),
|
||||
&[
|
||||
"deleted-during-prepass".to_string(),
|
||||
"deleted-during-recovery".to_string(),
|
||||
"live-bucket".to_string(),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
storage
|
||||
.delete_recovery_calls
|
||||
.lock()
|
||||
.expect("delete recovery calls")
|
||||
.as_slice(),
|
||||
&["deleted-during-recovery".to_string(), "live-bucket".to_string()],
|
||||
"prepass StaleBucketIncarnation must skip delete recovery for that bucket while continuing live buckets"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1088,3 +1088,240 @@ async fn bucket_removal_recovers_delete_proofs_before_removing_empty_volumes() {
|
||||
"all empty replicas should be removed after proof settlement"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn crash_recovery_erasure_set_does_not_recreate_deleted_bucket_and_repairs_live_bucket() {
|
||||
const STACK_SIZE: usize = 8 * 1024 * 1024;
|
||||
std::thread::Builder::new()
|
||||
.name("crash-recovery-deleted-bucket".to_owned())
|
||||
.stack_size(STACK_SIZE)
|
||||
.spawn(|| {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(4)
|
||||
.thread_stack_size(STACK_SIZE)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("crash recovery runtime");
|
||||
runtime.block_on(crash_recovery_erasure_set_does_not_recreate_deleted_bucket_and_repairs_live_bucket_case());
|
||||
})
|
||||
.expect("crash recovery test thread")
|
||||
.join()
|
||||
.expect("crash recovery test result");
|
||||
}
|
||||
|
||||
async fn crash_recovery_erasure_set_does_not_recreate_deleted_bucket_and_repairs_live_bucket_case() {
|
||||
use storage_api::integration::EcstoreStorageError;
|
||||
|
||||
let (disk_paths, ecstore, storage) = heal_env(TestECStoreEnvBuilder::default()).await;
|
||||
let deleted_bucket = "crash-recovery-deleted";
|
||||
let live_bucket = "crash-recovery-live";
|
||||
let payload = non_inline_test_data();
|
||||
|
||||
create_test_bucket(&ecstore, deleted_bucket).await;
|
||||
create_test_bucket(&ecstore, live_bucket).await;
|
||||
upload_test_object(&ecstore, deleted_bucket, "temp.bin", &payload).await;
|
||||
upload_test_object(&ecstore, live_bucket, "keep.bin", &payload).await;
|
||||
wait_for_object_copies(&disk_paths, deleted_bucket, "temp.bin").await;
|
||||
wait_for_object_copies(&disk_paths, live_bucket, "keep.bin").await;
|
||||
|
||||
// Mirror `HealManager::process_unclean_shutdown`: snapshot existing buckets at startup
|
||||
// with default `recreate_missing: true` and empty `heal_endpoints`.
|
||||
let mut request = HealRequest::new(
|
||||
HealType::ErasureSet {
|
||||
buckets: vec![deleted_bucket.to_owned(), live_bucket.to_owned()],
|
||||
set_disk_id: "pool_0_set_0".to_owned(),
|
||||
},
|
||||
HealOptions {
|
||||
timeout: None,
|
||||
..HealOptions::default()
|
||||
},
|
||||
HealPriority::Low,
|
||||
);
|
||||
request.source = HealRequestSource::AutoHeal;
|
||||
|
||||
// Client deletes all objects and deletes the bucket before the queued heal runs.
|
||||
ecstore
|
||||
.delete_object(deleted_bucket, "temp.bin", ObjectOptions::default())
|
||||
.await
|
||||
.expect("delete object before DeleteBucket");
|
||||
ecstore
|
||||
.delete_bucket(deleted_bucket, &Default::default())
|
||||
.await
|
||||
.expect("DeleteBucket should succeed");
|
||||
assert!(
|
||||
disk_paths.iter().all(|path| !path.join(deleted_bucket).exists()),
|
||||
"DeleteBucket must remove the deleted bucket directory from every drive"
|
||||
);
|
||||
|
||||
// Simulate a live bucket missing its directory on one drive so the same crash-recovery
|
||||
// run also proves partial directory loss is still repaired.
|
||||
fs::remove_dir_all(disk_paths[0].join(live_bucket))
|
||||
.await
|
||||
.expect("remove live bucket directory on disk 0");
|
||||
assert!(!disk_paths[0].join(live_bucket).exists());
|
||||
|
||||
HealTask::from_request(request, storage.clone())
|
||||
.execute()
|
||||
.await
|
||||
.expect("crash-recovery erasure set heal must complete without recreating deleted bucket");
|
||||
|
||||
assert!(
|
||||
disk_paths.iter().all(|path| !path.join(deleted_bucket).exists()),
|
||||
"deleted bucket directory must stay absent on every drive after crash-recovery heal"
|
||||
);
|
||||
let listed = ecstore
|
||||
.list_bucket(&Default::default())
|
||||
.await
|
||||
.expect("list buckets after crash-recovery heal");
|
||||
assert!(
|
||||
!listed.iter().any(|bucket| bucket.name == deleted_bucket),
|
||||
"deleted bucket must not reappear in ListBuckets"
|
||||
);
|
||||
assert!(listed.iter().any(|bucket| bucket.name == live_bucket), "live bucket must remain listed");
|
||||
|
||||
let mut reader = PutObjReader::from_vec(b"should-fail".to_vec());
|
||||
let put_err = ecstore
|
||||
.put_object(deleted_bucket, "after-delete.bin", &mut reader, &ObjectOptions::default())
|
||||
.await
|
||||
.expect_err("PUT to a deleted bucket must fail after crash-recovery heal");
|
||||
assert!(
|
||||
matches!(put_err, EcstoreStorageError::BucketNotFound(_) | EcstoreStorageError::VolumeNotFound),
|
||||
"expected missing-bucket error for deleted bucket PUT, got: {put_err:?}"
|
||||
);
|
||||
|
||||
assert!(
|
||||
disk_paths[0].join(live_bucket).is_dir(),
|
||||
"crash-recovery heal must still reconstruct a missing directory for a live bucket"
|
||||
);
|
||||
assert!(
|
||||
disk_paths[0].join(live_bucket).join("keep.bin").join("xl.meta").exists(),
|
||||
"crash-recovery heal must repair missing object shards on the live bucket"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn fenced_bucket_heal_and_delete_recovery_classify_retired_bucket_as_stale() {
|
||||
const STACK_SIZE: usize = 8 * 1024 * 1024;
|
||||
std::thread::Builder::new()
|
||||
.name("fenced-retired-bucket-heal".to_owned())
|
||||
.stack_size(STACK_SIZE)
|
||||
.spawn(|| {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(4)
|
||||
.thread_stack_size(STACK_SIZE)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("fenced retired bucket runtime");
|
||||
runtime.block_on(fenced_bucket_heal_and_delete_recovery_classify_retired_bucket_as_stale_case());
|
||||
})
|
||||
.expect("fenced retired bucket test thread")
|
||||
.join()
|
||||
.expect("fenced retired bucket test result");
|
||||
}
|
||||
|
||||
async fn fenced_bucket_heal_and_delete_recovery_classify_retired_bucket_as_stale_case() {
|
||||
use rustfs_heal::Error;
|
||||
|
||||
let (disk_paths, ecstore, storage) = heal_env(TestECStoreEnvBuilder::default()).await;
|
||||
|
||||
// 1. Concurrent DeleteBucket after incarnation lookup (TOCTOU window): retired generation
|
||||
// must classify as StaleBucketIncarnation and must never recreate directories.
|
||||
let retired_bucket = "retired-toctou-bucket";
|
||||
create_test_bucket(&ecstore, retired_bucket).await;
|
||||
let retired_incarnation = storage
|
||||
.bucket_incarnation_id(retired_bucket)
|
||||
.await
|
||||
.expect("lookup live incarnation")
|
||||
.expect("new bucket has an authoritative incarnation");
|
||||
ecstore
|
||||
.delete_bucket(retired_bucket, &Default::default())
|
||||
.await
|
||||
.expect("delete bucket after incarnation snapshot");
|
||||
|
||||
assert_eq!(
|
||||
storage
|
||||
.bucket_incarnation_id(retired_bucket)
|
||||
.await
|
||||
.expect("missing bucket incarnation should return Ok(None)"),
|
||||
None
|
||||
);
|
||||
|
||||
let heal_err = storage
|
||||
.heal_bucket_at_incarnation(
|
||||
retired_bucket,
|
||||
retired_incarnation,
|
||||
&HealOpts {
|
||||
recreate: false,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("fenced bucket heal must reject a retired generation");
|
||||
assert!(
|
||||
matches!(
|
||||
&heal_err,
|
||||
Error::StaleBucketIncarnation { bucket, expected }
|
||||
if bucket == retired_bucket && *expected == Some(retired_incarnation)
|
||||
),
|
||||
"expected StaleBucketIncarnation for retired bucket heal, got: {heal_err:?}"
|
||||
);
|
||||
assert!(
|
||||
disk_paths.iter().all(|path| !path.join(retired_bucket).exists()),
|
||||
"fenced bucket heal must not recreate a retired bucket directory"
|
||||
);
|
||||
|
||||
let recovery_err = storage
|
||||
.recover_delete_transactions(retired_bucket, None, Some(retired_incarnation), &HealOpts::default())
|
||||
.await
|
||||
.expect_err("fenced delete recovery must reject a retired generation");
|
||||
assert!(
|
||||
matches!(
|
||||
&recovery_err,
|
||||
Error::StaleBucketIncarnation { bucket, expected }
|
||||
if bucket == retired_bucket && *expected == Some(retired_incarnation)
|
||||
),
|
||||
"expected StaleBucketIncarnation for retired delete recovery, got: {recovery_err:?}"
|
||||
);
|
||||
|
||||
// 2. Fail-closed negative case: removing `.bucket-incarnation` on a live non-retired bucket
|
||||
// must NOT be misclassified as StaleBucketIncarnation.
|
||||
let corrupt_bucket = "live-missing-incarnation-bucket";
|
||||
create_test_bucket(&ecstore, corrupt_bucket).await;
|
||||
let live_incarnation = storage
|
||||
.bucket_incarnation_id(corrupt_bucket)
|
||||
.await
|
||||
.expect("lookup live incarnation")
|
||||
.expect("live bucket has an authoritative incarnation");
|
||||
ecstore
|
||||
.delete_object(
|
||||
".rustfs.sys",
|
||||
&format!("buckets/{corrupt_bucket}/.bucket-incarnation"),
|
||||
ObjectOptions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("simulate missing incarnation sidecar on a live non-retired bucket");
|
||||
|
||||
let corrupt_err = storage
|
||||
.heal_bucket_at_incarnation(
|
||||
corrupt_bucket,
|
||||
live_incarnation,
|
||||
&HealOpts {
|
||||
recreate: false,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("missing incarnation sidecar on a live non-retired bucket must fail closed");
|
||||
assert!(
|
||||
!matches!(corrupt_err, Error::StaleBucketIncarnation { .. }),
|
||||
"live non-retired bucket with missing incarnation metadata must not be treated as deleted: {corrupt_err:?}"
|
||||
);
|
||||
assert!(
|
||||
corrupt_err
|
||||
.to_string()
|
||||
.contains("bucket incarnation metadata is not authoritative"),
|
||||
"expected authoritative-metadata failure for live corrupted bucket, got: {corrupt_err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
+67
-10
@@ -36,9 +36,10 @@ pub mod devices;
|
||||
mod mem;
|
||||
mod remotes;
|
||||
|
||||
pub use remotes::PeerRole;
|
||||
|
||||
use mem::HostBuffer;
|
||||
use std::collections::VecDeque;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use thiserror::Error;
|
||||
@@ -118,6 +119,8 @@ impl ClientMemory {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RdmaToken {
|
||||
raw: String,
|
||||
role: PeerRole,
|
||||
expected_metadata_sha256: Option<[u8; 32]>,
|
||||
/// The client's agent name.
|
||||
pub agent: String,
|
||||
/// The client's agent metadata when the request carried it.
|
||||
@@ -184,6 +187,8 @@ impl RdmaToken {
|
||||
}
|
||||
Ok(Self {
|
||||
raw: format!("{agent}:{}", buffer.trim()),
|
||||
role: PeerRole::S3Client,
|
||||
expected_metadata_sha256: None,
|
||||
agent: agent.to_owned(),
|
||||
metadata,
|
||||
memory,
|
||||
@@ -193,6 +198,32 @@ impl RdmaToken {
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds an internode peer token bound to a caller-verified SHA-256 metadata digest.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`NixlError::Token`] when `metadata_base64` is empty, invalid
|
||||
/// base64, or when the agent or buffer descriptor is malformed.
|
||||
pub fn for_internode(
|
||||
agent: &str,
|
||||
metadata_base64: &str,
|
||||
verified_metadata_sha256: [u8; 32],
|
||||
buffer: &str,
|
||||
) -> Result<Self, NixlError> {
|
||||
let mut token = Self::from_headers(agent, Some(metadata_base64), buffer)?;
|
||||
if token.metadata.is_none() {
|
||||
return Err(NixlError::Token(format!("agent {agent:?} needs {NIXL_METADATA_HEADER}")));
|
||||
}
|
||||
token.role = PeerRole::Internode;
|
||||
token.expected_metadata_sha256 = Some(verified_metadata_sha256);
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Trust domain of this token (`S3Client` or `Internode`).
|
||||
pub fn role(&self) -> PeerRole {
|
||||
self.role
|
||||
}
|
||||
|
||||
/// Agent name and buffer, for logs.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.raw
|
||||
@@ -286,7 +317,11 @@ pub struct ArenaRanges {
|
||||
|
||||
impl ArenaRanges {
|
||||
pub fn total_len(&self) -> usize {
|
||||
self.ranges.iter().map(|(_, len)| *len).sum()
|
||||
self.ranges.iter().fold(0usize, |total, (_, len)| total.saturating_add(*len))
|
||||
}
|
||||
|
||||
pub fn checked_total_len(&self) -> Option<usize> {
|
||||
self.ranges.iter().try_fold(0usize, |total, (_, len)| total.checked_add(*len))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -515,12 +550,6 @@ impl std::fmt::Debug for NixlServer {
|
||||
}
|
||||
}
|
||||
|
||||
fn metadata_hash(metadata: &[u8]) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
metadata.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
impl NixlServer {
|
||||
fn register_staging<B: nixl_sys::MemoryRegion + nixl_sys::NixlDescriptor>(
|
||||
config: &NixlConfig,
|
||||
@@ -819,13 +848,18 @@ impl NixlServer {
|
||||
if source.ranges.len() > MAX_SG_RANGES {
|
||||
return Err(NixlError::Token("too many scatter-gather ranges".to_owned()));
|
||||
}
|
||||
let total = source.total_len();
|
||||
let total = source
|
||||
.checked_total_len()
|
||||
.ok_or_else(|| NixlError::Token("scatter-gather length overflow".to_owned()))?;
|
||||
if total == 0 {
|
||||
return Ok((0, keep));
|
||||
}
|
||||
let remote_base = Self::client_window(token, remote_offset, total as u64)?;
|
||||
let remote_base =
|
||||
usize::try_from(remote_base).map_err(|_| NixlError::Token("remote address exceeds the platform".to_owned()))?;
|
||||
remote_base
|
||||
.checked_add(total)
|
||||
.ok_or_else(|| NixlError::Token("remote address exceeds the platform".to_owned()))?;
|
||||
let arena_base = source.arena.buffer.addr();
|
||||
for (local_offset, len) in &source.ranges {
|
||||
if local_offset.checked_add(*len).is_none_or(|end| end > source.arena.len) {
|
||||
@@ -903,7 +937,13 @@ impl Engine {
|
||||
}
|
||||
|
||||
fn admit(&self, mut job: Job, pending: &mut Vec<Pending>, remotes: &mut remotes::RemoteCache) {
|
||||
let lease = match remotes.acquire(&self.agent, &job.token.agent, job.token.metadata.as_deref()) {
|
||||
let lease = match remotes.acquire(
|
||||
&self.agent,
|
||||
job.token.role,
|
||||
&job.token.agent,
|
||||
job.token.metadata.as_deref(),
|
||||
job.token.expected_metadata_sha256,
|
||||
) {
|
||||
Ok(lease) => lease,
|
||||
Err(error) => {
|
||||
job.completion.fail(error);
|
||||
@@ -1084,6 +1124,7 @@ mod tests {
|
||||
#[test]
|
||||
fn client_window_checks_the_buffer_bounds() {
|
||||
let token = RdmaToken::from_headers("a", None, "dram:0:1000:100").expect("token");
|
||||
assert_eq!(token.role(), PeerRole::S3Client);
|
||||
assert_eq!(NixlServer::client_window(&token, 40, 60).expect("fits"), 1040);
|
||||
assert!(matches!(
|
||||
NixlServer::client_window(&token, 50, 60),
|
||||
@@ -1093,4 +1134,20 @@ mod tests {
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internode_token_requires_metadata_and_binds_signed_digest() {
|
||||
let raw_md = b"rustfs-peer-1:ib0";
|
||||
let encoded_md = base64_simd::STANDARD.encode_to_string(raw_md);
|
||||
let digest = [0x5a; 32];
|
||||
|
||||
let token =
|
||||
RdmaToken::for_internode("rustfs-peer-1", &encoded_md, digest, "dram:0:0x1000:4096").expect("valid internode token");
|
||||
assert_eq!(token.role(), PeerRole::Internode);
|
||||
assert_eq!(token.expected_metadata_sha256, Some(digest));
|
||||
assert_eq!(token.metadata.as_deref(), Some(&raw_md[..]));
|
||||
|
||||
assert!(RdmaToken::for_internode("rustfs-peer-1", "", digest, "dram:0:0x1000:4096").is_err());
|
||||
assert!(RdmaToken::for_internode("rustfs-peer-1", " ", digest, "dram:0:0x1000:4096").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+88
-20
@@ -1,14 +1,24 @@
|
||||
//! Native peer registrations owned by one NIXL completion thread.
|
||||
|
||||
use super::{Agent, NIXL_METADATA_HEADER, NixlError, metadata_hash, nixl_err};
|
||||
use super::{Agent, NIXL_METADATA_HEADER, NixlError, nixl_err};
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const IDLE_TTL: Duration = Duration::from_secs(300);
|
||||
pub(super) const SWEEP_INTERVAL: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Trust domain of a remote NIXL agent registration.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PeerRole {
|
||||
/// External S3-over-RDMA client (`x-rustfs-nixl-*` headers).
|
||||
S3Client,
|
||||
/// Authenticated cluster peer (`read_file_nixl` / `write_file_nixl`).
|
||||
Internode,
|
||||
}
|
||||
|
||||
pub(super) trait MetadataRegistry {
|
||||
fn load(&self, bytes: &[u8]) -> Result<String, NixlError>;
|
||||
fn unload(&self, name: &str) -> Result<(), NixlError>;
|
||||
@@ -26,7 +36,9 @@ impl MetadataRegistry for Agent {
|
||||
}
|
||||
|
||||
struct Peer {
|
||||
hash: Option<u64>,
|
||||
role: PeerRole,
|
||||
metadata: Option<Arc<[u8]>>,
|
||||
signed_digest: Option<[u8; 32]>,
|
||||
idle_since: Rc<Cell<Instant>>,
|
||||
}
|
||||
|
||||
@@ -35,6 +47,15 @@ impl Peer {
|
||||
Rc::strong_count(&self.idle_since) == 1
|
||||
}
|
||||
|
||||
fn is_fresh(&self) -> bool {
|
||||
self.metadata.is_some()
|
||||
}
|
||||
|
||||
fn clear_fresh(&mut self) {
|
||||
self.metadata = None;
|
||||
self.signed_digest = None;
|
||||
}
|
||||
|
||||
fn acquire(&self) -> RemoteLease {
|
||||
RemoteLease(Rc::clone(&self.idle_since))
|
||||
}
|
||||
@@ -72,32 +93,59 @@ impl RemoteCache {
|
||||
pub(super) fn acquire(
|
||||
&mut self,
|
||||
registry: &impl MetadataRegistry,
|
||||
role: PeerRole,
|
||||
name: &str,
|
||||
metadata: Option<&[u8]>,
|
||||
expected_digest: Option<[u8; 32]>,
|
||||
) -> Result<RemoteLease, NixlError> {
|
||||
let hash = metadata.map(metadata_hash);
|
||||
if role == PeerRole::Internode && expected_digest.is_none() {
|
||||
return Err(NixlError::Token(
|
||||
"internode agent registration requires a signed metadata digest".to_owned(),
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(peer) = self.peers.get(name) {
|
||||
if peer.hash.is_some() && (hash.is_none() || hash == peer.hash) {
|
||||
return Ok(peer.acquire());
|
||||
}
|
||||
if !peer.idle() {
|
||||
if peer.role != role {
|
||||
// An S3 client must never reuse, evict, or collide with a cluster peer.
|
||||
// Conversely, an authenticated internode peer preempts an idle S3 squatter.
|
||||
if role == PeerRole::S3Client {
|
||||
return Err(NixlError::Token(format!("agent {name:?} is reserved for internode transport")));
|
||||
}
|
||||
if !peer.idle() {
|
||||
return Err(NixlError::Token(format!("agent {name:?} has active transfers under another role")));
|
||||
}
|
||||
} else if let Some(cached) = peer.metadata.as_deref() {
|
||||
let expected_matches = role != PeerRole::Internode || peer.signed_digest == expected_digest;
|
||||
if expected_matches && metadata.is_none_or(|incoming| incoming == cached) {
|
||||
return Ok(peer.acquire());
|
||||
}
|
||||
if !expected_matches && metadata.is_none() {
|
||||
return Err(NixlError::Token("agent metadata digest mismatch".to_owned()));
|
||||
}
|
||||
if !peer.idle() {
|
||||
return Err(NixlError::Token("peer metadata changed while transfers are active".to_owned()));
|
||||
}
|
||||
} else if !peer.idle() {
|
||||
return Err(NixlError::Token("peer metadata changed while transfers are active".to_owned()));
|
||||
}
|
||||
self.evict(registry, name)?;
|
||||
}
|
||||
|
||||
let metadata = metadata.ok_or_else(|| NixlError::Token(format!("agent {name:?} needs {NIXL_METADATA_HEADER}")))?;
|
||||
// Retry outstanding cleanup before loading another registration.
|
||||
self.trim(registry, |peer| peer.hash.is_none())?;
|
||||
self.trim_stale(registry)?;
|
||||
let loaded = registry.load(metadata)?;
|
||||
if loaded != name {
|
||||
if let Some(peer) = self.peers.get_mut(&loaded) {
|
||||
// Native loads can merge descriptors into an existing registration.
|
||||
peer.hash = None;
|
||||
peer.clear_fresh();
|
||||
} else if let Err(error) = registry.unload(&loaded) {
|
||||
self.peers.insert(
|
||||
loaded,
|
||||
Peer {
|
||||
hash: None,
|
||||
role,
|
||||
metadata: None,
|
||||
signed_digest: None,
|
||||
idle_since: Rc::new(Cell::new(Instant::now())),
|
||||
},
|
||||
);
|
||||
@@ -106,23 +154,43 @@ impl RemoteCache {
|
||||
return Err(NixlError::Token(format!("metadata belongs to agent {loaded:?}, request names {name:?}")));
|
||||
}
|
||||
let peer = Peer {
|
||||
hash,
|
||||
role,
|
||||
metadata: Some(Arc::from(metadata)),
|
||||
signed_digest: if role == PeerRole::Internode { expected_digest } else { None },
|
||||
idle_since: Rc::new(Cell::new(Instant::now())),
|
||||
};
|
||||
let lease = peer.acquire();
|
||||
self.peers.insert(loaded, peer);
|
||||
// Only a successful registration displaces an idle peer. Failed cleanup
|
||||
// leaves the victim stale for the next admission or periodic sweep.
|
||||
let _ = self.trim(registry, |_| true);
|
||||
// Only a successful registration displaces an idle peer of the same role.
|
||||
// Failed cleanup leaves the victim stale for the next admission or periodic sweep.
|
||||
let _ = self.trim_role(registry, role);
|
||||
Ok(lease)
|
||||
}
|
||||
|
||||
fn trim(&mut self, registry: &impl MetadataRegistry, eligible: impl Fn(&Peer) -> bool) -> Result<(), NixlError> {
|
||||
if self.peers.len() > self.capacity
|
||||
fn trim_stale(&mut self, registry: &impl MetadataRegistry) -> Result<(), NixlError> {
|
||||
if let Some((stale, _)) = self
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|(_, peer)| peer.idle() && !peer.is_fresh())
|
||||
.min_by_key(|(_, peer)| peer.idle_since.get())
|
||||
{
|
||||
let stale = stale.clone();
|
||||
self.evict(registry, &stale)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trim_role(&mut self, registry: &impl MetadataRegistry, role: PeerRole) -> Result<(), NixlError> {
|
||||
let role_count = self
|
||||
.peers
|
||||
.values()
|
||||
.filter(|peer| peer.role == role && peer.is_fresh())
|
||||
.count();
|
||||
if role_count > self.capacity
|
||||
&& let Some((oldest, _)) = self
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|(_, peer)| peer.idle() && eligible(peer))
|
||||
.filter(|(_, peer)| peer.idle() && peer.role == role && peer.is_fresh())
|
||||
.min_by_key(|(_, peer)| peer.idle_since.get())
|
||||
{
|
||||
let oldest = oldest.clone();
|
||||
@@ -142,16 +210,16 @@ impl RemoteCache {
|
||||
|
||||
pub(super) fn mark_stale(&mut self, name: &str) {
|
||||
if let Some(peer) = self.peers.get_mut(name) {
|
||||
peer.hash = None;
|
||||
peer.clear_fresh();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn sweep(&mut self, registry: &impl MetadataRegistry, now: Instant) {
|
||||
self.peers.retain(|name, peer| {
|
||||
if !peer.idle() || (peer.hash.is_some() && now.duration_since(peer.idle_since.get()) < IDLE_TTL) {
|
||||
if !peer.idle() || (peer.is_fresh() && now.duration_since(peer.idle_since.get()) < IDLE_TTL) {
|
||||
return true;
|
||||
}
|
||||
peer.hash = None;
|
||||
peer.clear_fresh();
|
||||
registry.unload(name).is_err()
|
||||
});
|
||||
}
|
||||
|
||||
@@ -35,18 +35,36 @@ impl MetadataRegistry for Registry {
|
||||
fn pressure_and_expiry_skip_live_transfers_and_unload_native_metadata() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(2);
|
||||
let active = cache.acquire(&backend, "a", Some(b"a")).expect("pin a");
|
||||
drop(cache.acquire(&backend, "b", Some(b"b")).expect("cache b"));
|
||||
drop(cache.acquire(&backend, "c", Some(b"c")).expect("evict b"));
|
||||
let active = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("pin a");
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "b", Some(b"b"), None)
|
||||
.expect("cache b"),
|
||||
);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "c", Some(b"c"), None)
|
||||
.expect("evict b"),
|
||||
);
|
||||
assert!(!backend.peers.borrow().contains("b"));
|
||||
assert!(cache.acquire(&backend, "b", None).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "b", None, None).is_err());
|
||||
let later = Instant::now() + IDLE_TTL;
|
||||
cache.sweep(&backend, later);
|
||||
assert_eq!(*backend.peers.borrow(), HashSet::from(["a".to_owned()]));
|
||||
assert!(cache.acquire(&backend, "a", Some(b"a:new")).is_err());
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a:new"), None)
|
||||
.is_err()
|
||||
);
|
||||
drop(active);
|
||||
drop(cache.acquire(&backend, "a", Some(b"a:new")).expect("replace idle generation"));
|
||||
assert!(cache.acquire(&backend, "a", None).is_ok());
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a:new"), None)
|
||||
.expect("replace idle generation"),
|
||||
);
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_ok());
|
||||
cache.sweep(&backend, later + IDLE_TTL);
|
||||
assert!(backend.peers.borrow().is_empty());
|
||||
}
|
||||
@@ -55,13 +73,23 @@ fn pressure_and_expiry_skip_live_transfers_and_unload_native_metadata() {
|
||||
fn a_failed_transfer_requires_fresh_metadata_after_its_siblings_finish() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(2);
|
||||
let active = cache.acquire(&backend, "a", Some(b"a")).expect("in flight");
|
||||
let active = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("in flight");
|
||||
cache.mark_stale("a");
|
||||
assert!(cache.acquire(&backend, "a", None).is_err());
|
||||
assert!(cache.acquire(&backend, "a", Some(b"a")).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None).is_err());
|
||||
drop(active);
|
||||
drop(cache.acquire(&backend, "a", Some(b"a")).expect("reconnect"));
|
||||
assert!(cache.acquire(&backend, "wrong", Some(b"another")).is_err());
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("reconnect"),
|
||||
);
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "wrong", Some(b"another"), None)
|
||||
.is_err()
|
||||
);
|
||||
assert!(!backend.peers.borrow().contains("another"));
|
||||
}
|
||||
|
||||
@@ -69,20 +97,36 @@ fn a_failed_transfer_requires_fresh_metadata_after_its_siblings_finish() {
|
||||
fn failed_eviction_cannot_reuse_a_partially_invalidated_registration() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(1);
|
||||
drop(cache.acquire(&backend, "a", Some(b"a")).expect("initial registration"));
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("initial registration"),
|
||||
);
|
||||
backend.fail_next_unload.set(true);
|
||||
drop(cache.acquire(&backend, "b", Some(b"b")).expect("new registration is usable"));
|
||||
assert!(cache.acquire(&backend, "b", None).is_ok());
|
||||
assert!(cache.acquire(&backend, "a", None).is_err());
|
||||
drop(cache.acquire(&backend, "a", Some(b"a")).expect("reload peer"));
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "b", Some(b"b"), None)
|
||||
.expect("new registration is usable"),
|
||||
);
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "b", None, None).is_ok());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_err());
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("reload peer"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_lifetime_starts_after_the_last_native_request_finishes() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(2);
|
||||
let first = cache.acquire(&backend, "a", Some(b"a")).unwrap();
|
||||
let last = cache.acquire(&backend, "a", None).unwrap();
|
||||
let first = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("first lease");
|
||||
let last = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", None, None)
|
||||
.expect("second lease");
|
||||
// The last idle timestamp predates both transfers.
|
||||
last.0.set(Instant::now() - IDLE_TTL - SWEEP_INTERVAL);
|
||||
drop(first);
|
||||
@@ -90,7 +134,7 @@ fn idle_lifetime_starts_after_the_last_native_request_finishes() {
|
||||
assert!(backend.peers.borrow().contains("a"));
|
||||
drop(last);
|
||||
cache.sweep(&backend, Instant::now() + SWEEP_INTERVAL);
|
||||
assert!(cache.acquire(&backend, "a", None).is_ok());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_ok());
|
||||
cache.sweep(&backend, Instant::now() + IDLE_TTL);
|
||||
assert!(backend.peers.borrow().is_empty());
|
||||
}
|
||||
@@ -99,13 +143,17 @@ fn idle_lifetime_starts_after_the_last_native_request_finishes() {
|
||||
fn unsuccessful_registration_preserves_idle_peers_at_capacity() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(1);
|
||||
drop(cache.acquire(&backend, "a", Some(b"a")).expect("cache a"));
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("cache a"),
|
||||
);
|
||||
|
||||
backend.fail_next_load.set(true);
|
||||
assert!(cache.acquire(&backend, "b", Some(b"b")).is_err());
|
||||
assert!(cache.acquire(&backend, "a", None).is_ok());
|
||||
assert!(cache.acquire(&backend, "b", Some(b"c")).is_err());
|
||||
assert!(cache.acquire(&backend, "a", None).is_ok());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "b", Some(b"b"), None).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_ok());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "b", Some(b"c"), None).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_ok());
|
||||
assert_eq!(*backend.peers.borrow(), HashSet::from(["a".to_owned()]));
|
||||
}
|
||||
|
||||
@@ -113,11 +161,92 @@ fn unsuccessful_registration_preserves_idle_peers_at_capacity() {
|
||||
fn unexpected_loaded_name_requires_a_refresh_after_its_transfers_finish() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(2);
|
||||
let active = cache.acquire(&backend, "a", Some(b"a")).expect("pin a");
|
||||
let active = cache
|
||||
.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None)
|
||||
.expect("pin a");
|
||||
|
||||
assert!(cache.acquire(&backend, "b", Some(b"a:new")).is_err());
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "b", Some(b"a:new"), None)
|
||||
.is_err()
|
||||
);
|
||||
assert!(backend.peers.borrow().contains("a"));
|
||||
assert!(cache.acquire(&backend, "a", None).is_err());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", None, None).is_err());
|
||||
drop(active);
|
||||
assert!(cache.acquire(&backend, "a", Some(b"a")).is_ok());
|
||||
assert!(cache.acquire(&backend, PeerRole::S3Client, "a", Some(b"a"), None).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internode_peers_require_signed_digests_and_resist_s3_client_collisions_or_eviction() {
|
||||
let backend = Registry::default();
|
||||
let mut cache = RemoteCache::new(1);
|
||||
let peer_md = b"rustfs-node1:rail0";
|
||||
let peer_digest = [0x11; 32];
|
||||
let wrong_digest = [0x22; 32];
|
||||
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", Some(peer_md), None)
|
||||
.is_err(),
|
||||
"internode registrations must require a signed digest"
|
||||
);
|
||||
|
||||
// Pre-existing idle S3 squatter is preempted by an authenticated internode peer.
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "rustfs-node1", Some(b"rustfs-node1:squatter"), None)
|
||||
.expect("s3 squatter"),
|
||||
);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", Some(peer_md), Some(peer_digest))
|
||||
.expect("authenticated internode peer preempts idle squatter"),
|
||||
);
|
||||
|
||||
// An S3 client cannot overwrite, reuse, or evict an internode registration.
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "rustfs-node1", Some(b"rustfs-node1:attacker"), None)
|
||||
.is_err(),
|
||||
"s3 client must not overwrite internode peer"
|
||||
);
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "rustfs-node1", None, None)
|
||||
.is_err(),
|
||||
"s3 client must not reuse internode peer"
|
||||
);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "client-1", Some(b"client-1"), None)
|
||||
.expect("s3 client 1"),
|
||||
);
|
||||
drop(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::S3Client, "client-2", Some(b"client-2"), None)
|
||||
.expect("s3 client 2 evicts client-1, not internode peer"),
|
||||
);
|
||||
assert!(backend.peers.borrow().contains("rustfs-node1"));
|
||||
assert!(!backend.peers.borrow().contains("client-1"));
|
||||
|
||||
// Cached internode lookup enforces the signed digest without evicting the valid peer.
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", None, Some(wrong_digest))
|
||||
.is_err(),
|
||||
"cached internode lookup must reject mismatched digest"
|
||||
);
|
||||
assert!(backend.peers.borrow().contains("rustfs-node1"));
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", None, Some(peer_digest))
|
||||
.is_ok(),
|
||||
"cached internode lookup with matching digest succeeds"
|
||||
);
|
||||
assert!(
|
||||
cache
|
||||
.acquire(&backend, PeerRole::Internode, "rustfs-node1", Some(peer_md), Some(peer_digest))
|
||||
.is_ok(),
|
||||
"cached internode lookup with matching metadata and digest reuses registration"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -96,4 +96,7 @@ pub use system_process::{
|
||||
ProcessAttributeError, ProcessAttributes, ProcessStats, ProcessStatusType, collect_process_attributes,
|
||||
collect_process_metrics,
|
||||
};
|
||||
pub use tier::{TierRequestStats, collect_tier_request_metrics};
|
||||
pub use tier::{
|
||||
TierInventoryEntry, TierRequestStats, TierTransitionLast24hEntry, TierUsageSnapshot, collect_tier_request_metrics,
|
||||
collect_tier_usage_metrics,
|
||||
};
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Remote tier request metrics collector.
|
||||
//! Remote tier request, inventory, and rolling transition metrics collectors.
|
||||
|
||||
use crate::metrics::report::PrometheusMetric;
|
||||
use crate::metrics::schema::tier::*;
|
||||
@@ -25,6 +25,38 @@ pub struct TierRequestStats {
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
/// Cluster-wide stored inventory counters for one configured remote tier.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TierInventoryEntry {
|
||||
pub tier: String,
|
||||
pub tier_type: String,
|
||||
pub total_bytes: u64,
|
||||
pub objects_count: u64,
|
||||
pub versions_count: u64,
|
||||
}
|
||||
|
||||
/// Node-local rolling 24-hour transition counters for one configured remote tier.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TierTransitionLast24hEntry {
|
||||
pub tier: String,
|
||||
pub tier_type: String,
|
||||
pub total_bytes: u64,
|
||||
pub objects_count: u64,
|
||||
}
|
||||
|
||||
/// Snapshot of configured remote-tier inventory and rolling 24-hour transition activity.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct TierUsageSnapshot {
|
||||
/// Whether the persisted usage snapshot carries per-tier accounting.
|
||||
///
|
||||
/// When `false` (`not-accounted` or `unavailable`), per-tier inventory
|
||||
/// gauges are omitted so callers never mistake an unaccounted tier for an
|
||||
/// empty tier.
|
||||
pub inventory_accounted: bool,
|
||||
pub inventory: Vec<TierInventoryEntry>,
|
||||
pub transitions_last24h: Vec<TierTransitionLast24hEntry>,
|
||||
}
|
||||
|
||||
/// Split the fixed operation/outcome cells over the success and failure
|
||||
/// counters.
|
||||
///
|
||||
@@ -47,6 +79,62 @@ pub fn collect_tier_request_metrics(stats: &[TierRequestStats]) -> Vec<Prometheu
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Collect configured remote-tier inventory and node-local rolling 24-hour
|
||||
/// transition gauges.
|
||||
///
|
||||
/// Inventory gauges are emitted only when `snapshot.inventory_accounted` is
|
||||
/// `true`; an unaccounted or unavailable usage snapshot emits
|
||||
/// `rustfs_tier_inventory_accounted = 0` and omits per-tier inventory series
|
||||
/// rather than fabricating zeros.
|
||||
pub fn collect_tier_usage_metrics(snapshot: &TierUsageSnapshot) -> Vec<PrometheusMetric> {
|
||||
let inventory_len = if snapshot.inventory_accounted {
|
||||
snapshot.inventory.len() * 3
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut metrics = Vec::with_capacity(1 + inventory_len + snapshot.transitions_last24h.len() * 2);
|
||||
|
||||
metrics.push(PrometheusMetric::from_descriptor(
|
||||
&TIER_INVENTORY_ACCOUNTED_MD,
|
||||
if snapshot.inventory_accounted { 1.0 } else { 0.0 },
|
||||
));
|
||||
|
||||
if snapshot.inventory_accounted {
|
||||
for entry in &snapshot.inventory {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_BYTES_MD, entry.total_bytes as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_OBJECTS_COUNT_MD, entry.objects_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_INVENTORY_VERSIONS_COUNT_MD, entry.versions_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for entry in &snapshot.transitions_last24h {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_TRANSITIONS_LAST24H_BYTES_MD, entry.total_bytes as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&TIER_TRANSITIONS_LAST24H_OBJECTS_COUNT_MD, entry.objects_count as f64)
|
||||
.with_label(TIER_LABEL, entry.tier.clone())
|
||||
.with_label(TIER_TYPE_LABEL, entry.tier_type.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
metrics
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -93,4 +181,114 @@ mod tests {
|
||||
"the failure counter must keep the outcome that produced it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_metrics_emit_all_six_gauges_when_inventory_is_accounted() {
|
||||
let snapshot = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 12,
|
||||
versions_count: 15,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 3,
|
||||
}],
|
||||
};
|
||||
|
||||
let metrics = collect_tier_usage_metrics(&snapshot);
|
||||
assert_eq!(metrics.len(), 6);
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.all(|metric| metric.metric_type == crate::metrics::schema::MetricType::Gauge),
|
||||
"tier usage metrics must be gauges"
|
||||
);
|
||||
|
||||
let accounted = metrics
|
||||
.iter()
|
||||
.find(|metric| metric.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted status gauge must be emitted");
|
||||
assert_eq!(accounted.value, 1.0);
|
||||
assert!(accounted.labels.is_empty(), "accounted gauge is snapshot-level without tier label");
|
||||
|
||||
for (name, expected) in [
|
||||
("rustfs_tier_inventory_bytes", 4096.0),
|
||||
("rustfs_tier_inventory_objects_count", 12.0),
|
||||
("rustfs_tier_inventory_versions_count", 15.0),
|
||||
("rustfs_tier_transitions_last24h_bytes", 1024.0),
|
||||
("rustfs_tier_transitions_last24h_objects_count", 3.0),
|
||||
] {
|
||||
let metric = metrics
|
||||
.iter()
|
||||
.find(|m| m.name == name)
|
||||
.unwrap_or_else(|| panic!("expected metric {name} to be emitted"));
|
||||
assert_eq!(metric.value, expected, "unexpected value for {name}");
|
||||
assert!(
|
||||
metric.labels.iter().any(|(k, v)| *k == TIER_LABEL && v.as_ref() == "COLD"),
|
||||
"{name} must carry tier label"
|
||||
);
|
||||
assert!(
|
||||
metric.labels.iter().any(|(k, v)| *k == TIER_TYPE_LABEL && v.as_ref() == "s3"),
|
||||
"{name} must carry tier_type label"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_metrics_omit_inventory_gauges_when_unaccounted() {
|
||||
let snapshot = TierUsageSnapshot {
|
||||
inventory_accounted: false,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 12,
|
||||
versions_count: 15,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 512,
|
||||
objects_count: 2,
|
||||
}],
|
||||
};
|
||||
|
||||
let metrics = collect_tier_usage_metrics(&snapshot);
|
||||
|
||||
let accounted = metrics
|
||||
.iter()
|
||||
.find(|metric| metric.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted status gauge must be emitted when unaccounted");
|
||||
assert_eq!(accounted.value, 0.0);
|
||||
|
||||
for forbidden in [
|
||||
"rustfs_tier_inventory_bytes",
|
||||
"rustfs_tier_inventory_objects_count",
|
||||
"rustfs_tier_inventory_versions_count",
|
||||
] {
|
||||
assert!(
|
||||
metrics.iter().all(|metric| metric.name != forbidden),
|
||||
"{forbidden} must not be emitted when inventory_accounted is false"
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.any(|metric| metric.name == "rustfs_tier_transitions_last24h_bytes" && metric.value == 512.0),
|
||||
"node-local 24h transition bytes must remain populated when inventory is unaccounted"
|
||||
);
|
||||
assert!(
|
||||
metrics
|
||||
.iter()
|
||||
.any(|metric| metric.name == "rustfs_tier_transitions_last24h_objects_count" && metric.value == 2.0),
|
||||
"node-local 24h transition object count must remain populated when inventory is unaccounted"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,9 +33,10 @@ pub use scheduler::{
|
||||
};
|
||||
pub(crate) use storage_api::metrics::{
|
||||
BucketOperations, BucketOptions, ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore,
|
||||
StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_expiry_state_handle, obs_get_global_bucket_monitor,
|
||||
obs_get_quota_config, obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled,
|
||||
obs_load_compression_total_from_memory, obs_load_data_usage_from_backend, obs_on_demand_migration_backfill_snapshot,
|
||||
ObsTierCounter, StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
|
||||
obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity,
|
||||
obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
obs_transition_state_handle,
|
||||
};
|
||||
|
||||
@@ -78,6 +78,7 @@ use crate::metrics::collectors::{
|
||||
collect_resource_metrics,
|
||||
collect_scanner_runtime_metrics,
|
||||
collect_tier_request_metrics,
|
||||
collect_tier_usage_metrics,
|
||||
};
|
||||
use crate::metrics::config::{
|
||||
DEFAULT_AUDIT_METRICS_INTERVAL, DEFAULT_BUCKET_METRICS_INTERVAL, DEFAULT_BUCKET_REPLICATION_BANDWIDTH_METRICS_INTERVAL,
|
||||
@@ -140,10 +141,10 @@ use crate::metrics::schema::system_process::{PROCESS_EXECUTABLE_NAME_LABEL, PROC
|
||||
use crate::metrics::stats_collector::{
|
||||
ProcessMetricBundle, collect_api_request_stats, collect_bucket_replication_bandwidth_stats,
|
||||
collect_bucket_replication_stats_bundle, collect_bucket_stats, collect_cluster_config_stats,
|
||||
collect_cluster_storage_snapshot, collect_cluster_usage_metric_stats, collect_compression_cluster_stats,
|
||||
collect_disk_and_system_drive_runtime_stats, collect_host_network_stats, collect_iam_stats, collect_ilm_runtime_metric_stats,
|
||||
collect_internode_network_stats, collect_on_demand_migration_backfill_stats, collect_on_demand_migration_stats,
|
||||
collect_process_metric_bundle_with, collect_replication_stats, collect_scanner_runtime_metric_stats,
|
||||
collect_cluster_storage_snapshot, collect_compression_cluster_stats, collect_disk_and_system_drive_runtime_stats,
|
||||
collect_host_network_stats, collect_iam_stats, collect_ilm_runtime_metric_stats, collect_internode_network_stats,
|
||||
collect_on_demand_migration_backfill_stats, collect_on_demand_migration_stats, collect_process_metric_bundle_with,
|
||||
collect_replication_stats, collect_scanner_runtime_metric_stats, collect_supplementary_usage_metric_stats,
|
||||
collect_system_cpu_and_memory_stats_with, collect_tier_request_metric_stats,
|
||||
};
|
||||
use crate::metrics::storage_snapshot::StorageSnapshotMetrics;
|
||||
@@ -1614,6 +1615,7 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
let tombstone_cycles = config.replication_bandwidth_zero_tombstone_cycles;
|
||||
let mut has_seen_bucket_usage_snapshot = false;
|
||||
let mut bucket_usage_snapshot = bucket_metrics_snapshot(cluster_interval);
|
||||
let mut tier_usage_snapshot = bucket_metrics_snapshot(cluster_interval);
|
||||
let mut prev_bucket_usage_keys: HashSet<BucketKey> = HashSet::new();
|
||||
let mut bucket_usage_zero_tombstones: HashMap<BucketKey, u8> = HashMap::new();
|
||||
let mut prev_bucket_usage_object_size_keys: HashSet<BucketRangeKey> = HashSet::new();
|
||||
@@ -1640,7 +1642,8 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
}
|
||||
|
||||
let usage_collection_started = std::time::Instant::now();
|
||||
if let Some((cluster_usage, bucket_usage)) = collect_cluster_usage_metric_stats().await {
|
||||
let (cluster_bucket_usage, tier_usage) = collect_supplementary_usage_metric_stats().await;
|
||||
if let Some((cluster_usage, bucket_usage)) = cluster_bucket_usage {
|
||||
let mut usage_metrics = collect_cluster_usage_metrics(&cluster_usage);
|
||||
usage_metrics.extend(collect_bucket_usage_metrics(&bucket_usage));
|
||||
update_series_zero_tombstones(
|
||||
@@ -1681,6 +1684,11 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_bucket_snapshot", error = %error, "bucket usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
let tier_metrics = tier_usage.as_ref().map(collect_tier_usage_metrics).unwrap_or_default();
|
||||
if let Err(error) = tier_usage_snapshot.replace_collected(tier_metrics, usage_collection_started) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_tier_snapshot", error = %error, "tier usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
if !metrics.is_empty() {
|
||||
report_metrics(&metrics);
|
||||
}
|
||||
|
||||
@@ -135,9 +135,15 @@ pub enum MetricName {
|
||||
TransitionedObjects,
|
||||
TransitionedVersions,
|
||||
|
||||
//Tier request metrics
|
||||
// Tier metrics
|
||||
TierRequestsSuccess,
|
||||
TierRequestsFailure,
|
||||
TierInventoryBytes,
|
||||
TierInventoryObjectsCount,
|
||||
TierInventoryVersionsCount,
|
||||
TierInventoryAccounted,
|
||||
TierTransitionsLast24hBytes,
|
||||
TierTransitionsLast24hObjectsCount,
|
||||
|
||||
// KMS metrics
|
||||
KmsOnline,
|
||||
@@ -560,6 +566,12 @@ impl MetricName {
|
||||
|
||||
Self::TierRequestsSuccess => "requests_success",
|
||||
Self::TierRequestsFailure => "requests_failure",
|
||||
Self::TierInventoryBytes => "inventory_bytes",
|
||||
Self::TierInventoryObjectsCount => "inventory_objects_count",
|
||||
Self::TierInventoryVersionsCount => "inventory_versions_count",
|
||||
Self::TierInventoryAccounted => "inventory_accounted",
|
||||
Self::TierTransitionsLast24hBytes => "transitions_last24h_bytes",
|
||||
Self::TierTransitionsLast24hObjectsCount => "transitions_last24h_objects_count",
|
||||
|
||||
Self::KmsOnline => "online",
|
||||
Self::KmsRequestsSuccess => "request_success",
|
||||
|
||||
@@ -12,17 +12,23 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Remote tier request metric descriptors.
|
||||
//! Remote tier metric descriptors.
|
||||
//!
|
||||
//! The label set is fixed by the operation and outcome enums the recording
|
||||
//! site uses, so the series count is bounded by construction and cannot grow
|
||||
//! with tier names, endpoints or object keys.
|
||||
//! Request counters (`rustfs_tier_requests_*`) keep a closed label set fixed by
|
||||
//! the operation and outcome enums so request hot paths never depend on tier
|
||||
//! names, endpoints, or object keys.
|
||||
//!
|
||||
//! Inventory and rolling 24-hour transition gauges are published from periodic
|
||||
//! snapshots and carry configured remote tier identity (`tier`, `tier_type`),
|
||||
//! never endpoints, credentials, or object keys.
|
||||
|
||||
use crate::{MetricDescriptor, MetricName, new_counter_md, subsystems};
|
||||
use crate::{MetricDescriptor, MetricName, new_counter_md, new_gauge_md, subsystems};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
pub const OPERATION_LABEL: &str = "operation";
|
||||
pub const OUTCOME_LABEL: &str = "outcome";
|
||||
pub const TIER_LABEL: &str = "tier";
|
||||
pub const TIER_TYPE_LABEL: &str = "tier_type";
|
||||
|
||||
pub static TIER_REQUESTS_SUCCESS_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_counter_md(
|
||||
@@ -41,3 +47,57 @@ pub static TIER_REQUESTS_FAILURE_MD: LazyLock<MetricDescriptor> = LazyLock::new(
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_BYTES_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryBytes,
|
||||
"Cluster-wide logical bytes currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_OBJECTS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryObjectsCount,
|
||||
"Cluster-wide object count currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_VERSIONS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryVersionsCount,
|
||||
"Cluster-wide object version count currently stored in a configured remote tier from the scanner usage snapshot",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_INVENTORY_ACCOUNTED_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierInventoryAccounted,
|
||||
"Whether the persisted usage snapshot includes per-tier inventory accounting (1 = accounted, 0 = not-accounted or unavailable)",
|
||||
&[],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_TRANSITIONS_LAST24H_BYTES_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierTransitionsLast24hBytes,
|
||||
"Node-local logical bytes committed into a configured remote tier during the rolling 24-hour window",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
pub static TIER_TRANSITIONS_LAST24H_OBJECTS_COUNT_MD: LazyLock<MetricDescriptor> = LazyLock::new(|| {
|
||||
new_gauge_md(
|
||||
MetricName::TierTransitionsLast24hObjectsCount,
|
||||
"Node-local objects committed into a configured remote tier during the rolling 24-hour window",
|
||||
&[TIER_LABEL, TIER_TYPE_LABEL],
|
||||
subsystems::TIER,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -28,15 +28,16 @@ use crate::metrics::collectors::{
|
||||
DriveDetailedStats, DriveRuntimeDetailedStats, ErasureSetStats, HostNetworkStats, IamStats, IlmActionTaskStats,
|
||||
IlmBackpressureStats, IlmQueueTaskStats, IlmRuntimeStats, IlmStats, IlmTaskEventStats, MemoryStats, NetworkStats,
|
||||
OdmBackfillRuntimeStats, OnDemandMigrationBucketStats, ProcessStats, ProcessStatusType, ReplicationMetricsSnapshot,
|
||||
ResourceStats, ScannerRuntimeStats, ScannerStats, TierRequestStats,
|
||||
ResourceStats, ScannerRuntimeStats, ScannerStats, TierInventoryEntry, TierRequestStats, TierTransitionLast24hEntry,
|
||||
TierUsageSnapshot,
|
||||
};
|
||||
use crate::metrics::runtime_sources::{ObsIlmRuntimeSnapshot, bucket_monitor_handle, iam_metrics_snapshot, ilm_runtime_snapshot};
|
||||
use crate::metrics::{
|
||||
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, StorageAdminApi,
|
||||
obs_bucket_replication_stats_snapshot, obs_get_quota_config, obs_get_total_usable_capacity,
|
||||
obs_get_total_usable_capacity_free, obs_load_compression_total_from_memory, obs_load_data_usage_from_backend,
|
||||
obs_on_demand_migration_backfill_snapshot, obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot,
|
||||
obs_resolve_object_store_handle,
|
||||
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
|
||||
StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_get_quota_config,
|
||||
obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
};
|
||||
use crate::node_identity::current_local_node_identity;
|
||||
use jiff::Timestamp;
|
||||
@@ -76,6 +77,7 @@ struct ObsDataUsageInfo {
|
||||
delete_markers_total_count: u64,
|
||||
objects_total_size: u64,
|
||||
buckets_usage: HashMap<String, ObsBucketUsageInfo>,
|
||||
tier_stats: Option<HashMap<String, ObsTierCounter>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -130,6 +132,22 @@ async fn load_obs_data_usage_from_backend(store: Arc<ObsStore>) -> ObsEcstoreRes
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
tier_stats: data_usage.tier_stats.map(|all_tiers| {
|
||||
all_tiers
|
||||
.tiers
|
||||
.into_iter()
|
||||
.map(|(tier, stats)| {
|
||||
(
|
||||
tier,
|
||||
ObsTierCounter {
|
||||
total_size: stats.total_size,
|
||||
num_objects: stats.num_objects,
|
||||
num_versions: stats.num_versions,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1251,6 +1269,109 @@ pub async fn collect_cluster_usage_metric_stats() -> Option<(ClusterUsageStats,
|
||||
collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await
|
||||
}
|
||||
|
||||
/// Collect cluster/bucket usage and configured remote-tier usage from one
|
||||
/// shared backend data-usage snapshot read.
|
||||
///
|
||||
/// Remote-tier inventory is extracted before the bucket-namespace completeness
|
||||
/// check so OTLP tier metrics match `GET /rustfs/admin/v3/tier-stats`, and a
|
||||
/// backend usage read failure still yields `inventory_accounted = false` plus
|
||||
/// node-local 24-hour transition counters when remote tiers are configured.
|
||||
pub(crate) async fn collect_supplementary_usage_metric_stats()
|
||||
-> (Option<(ClusterUsageStats, Vec<BucketUsageStats>)>, Option<TierUsageSnapshot>) {
|
||||
let configured_tiers = obs_configured_remote_tier_types().await;
|
||||
let store = resolve_obs_object_store_handle();
|
||||
let data_usage = match store.as_ref() {
|
||||
Some(store) => load_obs_data_usage_from_backend(store.clone()).await.ok(),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let tier_usage = if configured_tiers.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let local_daily_stats = obs_local_tier_daily_stats();
|
||||
tier_usage_snapshot_from_parts(
|
||||
&configured_tiers,
|
||||
data_usage.as_ref().and_then(|usage| usage.tier_stats.as_ref()),
|
||||
&local_daily_stats,
|
||||
)
|
||||
};
|
||||
|
||||
let cluster_bucket_usage = match (store, data_usage) {
|
||||
(Some(store), Some(data_usage)) => {
|
||||
let bucket_namespace = store
|
||||
.list_bucket(&BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.map(|buckets| {
|
||||
buckets
|
||||
.into_iter()
|
||||
.filter(|bucket| !bucket.name.starts_with('.'))
|
||||
.map(|bucket| bucket.name)
|
||||
.collect::<HashSet<_>>()
|
||||
});
|
||||
match bucket_namespace {
|
||||
Some(bucket_namespace) => collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await,
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
(cluster_bucket_usage, tier_usage)
|
||||
}
|
||||
|
||||
fn tier_usage_snapshot_from_parts(
|
||||
configured_tiers: &HashMap<String, String>,
|
||||
data_usage_tier_stats: Option<&HashMap<String, ObsTierCounter>>,
|
||||
local_daily_stats: &HashMap<String, ObsTierCounter>,
|
||||
) -> Option<TierUsageSnapshot> {
|
||||
if configured_tiers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut tiers: Vec<(&str, &str)> = configured_tiers
|
||||
.iter()
|
||||
.map(|(name, tier_type)| (name.as_str(), tier_type.as_str()))
|
||||
.collect();
|
||||
tiers.sort_unstable_by(|a, b| a.0.cmp(b.0));
|
||||
|
||||
let inventory_accounted = data_usage_tier_stats.is_some();
|
||||
let mut inventory = Vec::new();
|
||||
let mut transitions_last24h = Vec::with_capacity(tiers.len());
|
||||
|
||||
for (tier, tier_type) in tiers {
|
||||
if let Some(inv_map) = data_usage_tier_stats
|
||||
&& let Some(stats) = inv_map.get(tier)
|
||||
{
|
||||
inventory.push(TierInventoryEntry {
|
||||
tier: tier.to_string(),
|
||||
tier_type: tier_type.to_string(),
|
||||
total_bytes: stats.total_size,
|
||||
objects_count: stats.num_objects,
|
||||
versions_count: stats.num_versions,
|
||||
});
|
||||
}
|
||||
|
||||
let daily = local_daily_stats.get(tier).copied().unwrap_or_default();
|
||||
transitions_last24h.push(TierTransitionLast24hEntry {
|
||||
tier: tier.to_string(),
|
||||
tier_type: tier_type.to_string(),
|
||||
total_bytes: daily.total_size,
|
||||
objects_count: daily.num_objects,
|
||||
});
|
||||
}
|
||||
|
||||
Some(TierUsageSnapshot {
|
||||
inventory_accounted,
|
||||
inventory,
|
||||
transitions_last24h,
|
||||
})
|
||||
}
|
||||
|
||||
async fn collect_cluster_usage_metric_stats_from_data_usage(
|
||||
data_usage: ObsDataUsageInfo,
|
||||
bucket_namespace: &HashSet<String>,
|
||||
@@ -1946,6 +2067,136 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_returns_none_when_no_remote_tiers_configured() {
|
||||
let configured = HashMap::new();
|
||||
let data_usage_tiers = HashMap::from([(
|
||||
"STANDARD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 4096,
|
||||
num_objects: 2,
|
||||
num_versions: 2,
|
||||
},
|
||||
)]);
|
||||
let daily = HashMap::new();
|
||||
|
||||
assert!(tier_usage_snapshot_from_parts(&configured, Some(&data_usage_tiers), &daily).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_excludes_local_classes_unconfigured_tiers_and_unscanned_zeros() {
|
||||
let configured = HashMap::from([
|
||||
("COLD".to_string(), "rustfs".to_string()),
|
||||
("ARCHIVE".to_string(), "s3".to_string()),
|
||||
]);
|
||||
let data_usage_tiers = HashMap::from([
|
||||
(
|
||||
"STANDARD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 99_999,
|
||||
num_objects: 99,
|
||||
num_versions: 120,
|
||||
},
|
||||
),
|
||||
(
|
||||
"REMOVED_TIER".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 8_192,
|
||||
num_objects: 4,
|
||||
num_versions: 4,
|
||||
},
|
||||
),
|
||||
(
|
||||
"ARCHIVE".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 2048,
|
||||
num_objects: 5,
|
||||
num_versions: 7,
|
||||
},
|
||||
),
|
||||
]);
|
||||
let daily = HashMap::from([
|
||||
(
|
||||
"ARCHIVE".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 512,
|
||||
num_objects: 1,
|
||||
num_versions: 1,
|
||||
},
|
||||
),
|
||||
(
|
||||
"REMOVED_TIER".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 128,
|
||||
num_objects: 1,
|
||||
num_versions: 1,
|
||||
},
|
||||
),
|
||||
]);
|
||||
|
||||
let snapshot = tier_usage_snapshot_from_parts(&configured, Some(&data_usage_tiers), &daily)
|
||||
.expect("configured remote tiers should yield a tier usage snapshot");
|
||||
|
||||
assert!(snapshot.inventory_accounted);
|
||||
assert_eq!(
|
||||
snapshot.inventory,
|
||||
vec![TierInventoryEntry {
|
||||
tier: "ARCHIVE".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 2048,
|
||||
objects_count: 5,
|
||||
versions_count: 7,
|
||||
}],
|
||||
"only accounted configured remote tiers must appear in inventory; local classes, removed tiers, and unscanned tiers must not"
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.transitions_last24h,
|
||||
vec![
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 512,
|
||||
objects_count: 1,
|
||||
},
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "rustfs".to_string(),
|
||||
total_bytes: 0,
|
||||
objects_count: 0,
|
||||
},
|
||||
],
|
||||
"all configured remote tiers should report deterministic sorted node-local 24h transitions"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tier_usage_snapshot_preserves_local_transitions_when_inventory_is_not_accounted() {
|
||||
let configured = HashMap::from([("COLD".to_string(), "s3".to_string())]);
|
||||
let daily = HashMap::from([(
|
||||
"COLD".to_string(),
|
||||
ObsTierCounter {
|
||||
total_size: 1024,
|
||||
num_objects: 2,
|
||||
num_versions: 3,
|
||||
},
|
||||
)]);
|
||||
|
||||
let snapshot = tier_usage_snapshot_from_parts(&configured, None, &daily)
|
||||
.expect("configured remote tier should still emit snapshot when usage is unaccounted");
|
||||
|
||||
assert!(!snapshot.inventory_accounted);
|
||||
assert!(snapshot.inventory.is_empty());
|
||||
assert_eq!(
|
||||
snapshot.transitions_last24h,
|
||||
vec![TierTransitionLast24hEntry {
|
||||
tier: "COLD".to_string(),
|
||||
tier_type: "s3".to_string(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 2,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cluster_config_stats_accept_homogeneous_backend_parities() {
|
||||
let stats = cluster_config_stats_from_backend_parities(Some(1), Some(2))
|
||||
|
||||
@@ -16,6 +16,7 @@ use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) use rustfs_ecstore::api::bucket::bandwidth::monitor::Monitor as ObsBucketBandwidthMonitor;
|
||||
use rustfs_ecstore::api::bucket::lifecycle::tier_last_day_stats::LastDayTierStats as ObsLastDayTierStats;
|
||||
pub(crate) use rustfs_ecstore::api::bucket::metadata_sys::get_quota_config as obs_get_quota_config;
|
||||
use rustfs_ecstore::api::bucket::replication::{
|
||||
BucketReplicationStats as SourceBucketReplicationStats, DurableMrfBucketBacklog, DurableMrfTargetBacklog,
|
||||
@@ -32,7 +33,8 @@ pub(crate) use rustfs_ecstore::api::data_usage::load_compression_total_from_memo
|
||||
pub(crate) use rustfs_ecstore::api::error::Result as ObsEcstoreResult;
|
||||
pub(crate) use rustfs_ecstore::api::runtime::{
|
||||
bucket_monitor as obs_get_global_bucket_monitor, expiry_state_handle as obs_expiry_state_handle,
|
||||
object_store_handle as obs_resolve_object_store_handle, transition_state_handle as obs_transition_state_handle,
|
||||
global_tier_config_mgr as obs_global_tier_config_mgr, object_store_handle as obs_resolve_object_store_handle,
|
||||
transition_state_handle as obs_transition_state_handle,
|
||||
};
|
||||
pub(crate) use rustfs_ecstore::api::storage::ECStore as ObsStore;
|
||||
use rustfs_storage_api as storage_contracts;
|
||||
@@ -534,6 +536,54 @@ pub(crate) async fn obs_replication_site_stats_snapshot(current_data_transfer_ra
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal counter tuple bridged from `ecstore` tier snapshots.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(crate) struct ObsTierCounter {
|
||||
pub(crate) total_size: u64,
|
||||
pub(crate) num_objects: u64,
|
||||
pub(crate) num_versions: u64,
|
||||
}
|
||||
|
||||
/// Snapshot configured remote tiers (`name -> lowercase tier_type`) without
|
||||
/// holding the tier config read lock across downstream work.
|
||||
pub(crate) async fn obs_configured_remote_tier_types() -> HashMap<String, String> {
|
||||
let tier_config_mgr = obs_global_tier_config_mgr();
|
||||
let guard = tier_config_mgr.read().await;
|
||||
guard
|
||||
.list_tiers()
|
||||
.into_iter()
|
||||
.map(|tier| (tier.name, tier.tier_type.as_lowercase()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Snapshot this node's rolling 24-hour tier transition counters, aged forward
|
||||
/// to the current UTC hour so expired bins drop out even when no new
|
||||
/// transitions have committed recently.
|
||||
pub(crate) fn obs_local_tier_daily_stats() -> HashMap<String, ObsTierCounter> {
|
||||
let now_ring = ObsLastDayTierStats::default();
|
||||
age_local_tier_daily_stats(obs_transition_state_handle().get_daily_all_tier_stats(), &now_ring)
|
||||
}
|
||||
|
||||
fn age_local_tier_daily_stats(
|
||||
stats: HashMap<String, ObsLastDayTierStats>,
|
||||
now_ring: &ObsLastDayTierStats,
|
||||
) -> HashMap<String, ObsTierCounter> {
|
||||
stats
|
||||
.into_iter()
|
||||
.map(|(tier, ring)| {
|
||||
let total = ring.merge(now_ring.clone()).total();
|
||||
(
|
||||
tier,
|
||||
ObsTierCounter {
|
||||
total_size: total.total_size,
|
||||
num_objects: total.num_objects,
|
||||
num_versions: total.num_versions,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -774,17 +824,72 @@ mod tests {
|
||||
assert_eq!(snapshot.durable_mrf_backlog_count, 0);
|
||||
assert_eq!(snapshot.durable_mrf_backlog_bytes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn age_local_tier_daily_stats_expires_bins_older_than_24_hours() {
|
||||
use rustfs_ecstore::api::bucket::lifecycle::tier_last_day_stats::TierDailyStatsWire;
|
||||
|
||||
let now_unix = 1_700_100_000_i64;
|
||||
let empty_bins = ObsLastDayTierStats::default().to_wire().bins;
|
||||
let now_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: empty_bins.clone(),
|
||||
updated_at_unix_secs: now_unix,
|
||||
})
|
||||
.expect("current reference ring should decode");
|
||||
|
||||
let mut stale_bins = empty_bins.clone();
|
||||
stale_bins[0].total_size = 4096;
|
||||
stale_bins[0].num_versions = 3;
|
||||
stale_bins[0].num_objects = 2;
|
||||
let stale_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: stale_bins,
|
||||
updated_at_unix_secs: now_unix - 25 * 3600,
|
||||
})
|
||||
.expect("stale ring should decode");
|
||||
|
||||
let fresh_updated = now_unix - 2 * 3600;
|
||||
let fresh_hour = usize::try_from((fresh_updated / 3600).rem_euclid(24)).expect("hour fits in usize");
|
||||
let mut fresh_bins = empty_bins;
|
||||
fresh_bins[fresh_hour].total_size = 2048;
|
||||
fresh_bins[fresh_hour].num_versions = 2;
|
||||
fresh_bins[fresh_hour].num_objects = 1;
|
||||
let fresh_ring = ObsLastDayTierStats::from_wire(TierDailyStatsWire {
|
||||
bins: fresh_bins,
|
||||
updated_at_unix_secs: fresh_updated,
|
||||
})
|
||||
.expect("fresh ring should decode");
|
||||
|
||||
let aged = age_local_tier_daily_stats(
|
||||
HashMap::from([("STALE".to_string(), stale_ring), ("FRESH".to_string(), fresh_ring)]),
|
||||
&now_ring,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
aged.get("STALE"),
|
||||
Some(&ObsTierCounter::default()),
|
||||
"bins older than 24h must age to zero"
|
||||
);
|
||||
assert_eq!(
|
||||
aged.get("FRESH"),
|
||||
Some(&ObsTierCounter {
|
||||
total_size: 2048,
|
||||
num_objects: 1,
|
||||
num_versions: 2,
|
||||
}),
|
||||
"recent bins still inside the 24h window must be preserved"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod metrics {
|
||||
pub(crate) use super::storage_contracts::{BucketOperations, BucketOptions, StorageAdminApi};
|
||||
|
||||
pub(crate) use super::{
|
||||
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore,
|
||||
obs_bucket_replication_stats_snapshot, obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_quota_config,
|
||||
obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled,
|
||||
obs_load_compression_total_from_memory, obs_load_data_usage_from_backend, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
obs_transition_state_handle,
|
||||
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
|
||||
obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_expiry_state_handle,
|
||||
obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity, obs_get_total_usable_capacity_free,
|
||||
obs_is_disk_compression_enabled, obs_load_compression_total_from_memory, obs_load_data_usage_from_backend,
|
||||
obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot, obs_on_demand_migration_snapshot,
|
||||
obs_replication_site_stats_snapshot, obs_resolve_object_store_handle, obs_transition_state_handle,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -471,6 +471,187 @@ mod tests {
|
||||
provider.shutdown().expect("shut down bucket usage test provider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_sdk_exports_tier_inventory_and_transitions_without_fabricating_zeros() {
|
||||
use crate::metrics::collectors::{
|
||||
TierInventoryEntry, TierTransitionLast24hEntry, TierUsageSnapshot, collect_tier_usage_metrics,
|
||||
};
|
||||
|
||||
let (provider, exporter, mut snapshot) = setup_unscoped();
|
||||
|
||||
let extract_tier_points = |points: &[ExportedPoint], metric_name: &str| {
|
||||
let mut entries = points
|
||||
.iter()
|
||||
.filter(|point| point.name == metric_name)
|
||||
.map(|point| {
|
||||
let tier = point
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|attr| attr.key.as_str() == "tier")
|
||||
.expect("tier metric must carry tier attribute")
|
||||
.value
|
||||
.to_string();
|
||||
let tier_type = point
|
||||
.attributes
|
||||
.iter()
|
||||
.find(|attr| attr.key.as_str() == "tier_type")
|
||||
.expect("tier metric must carry tier_type attribute")
|
||||
.value
|
||||
.to_string();
|
||||
(tier, tier_type, point.value)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
entries
|
||||
};
|
||||
|
||||
// 1. Accounted snapshot with two configured remote tiers.
|
||||
let initial = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![
|
||||
TierInventoryEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 8192,
|
||||
objects_count: 4,
|
||||
versions_count: 6,
|
||||
},
|
||||
TierInventoryEntry {
|
||||
tier: "COLD".into(),
|
||||
tier_type: "rustfs".into(),
|
||||
total_bytes: 4096,
|
||||
objects_count: 2,
|
||||
versions_count: 3,
|
||||
},
|
||||
],
|
||||
transitions_last24h: vec![
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 2048,
|
||||
objects_count: 1,
|
||||
},
|
||||
TierTransitionLast24hEntry {
|
||||
tier: "COLD".into(),
|
||||
tier_type: "rustfs".into(),
|
||||
total_bytes: 0,
|
||||
objects_count: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&initial))
|
||||
.expect("publish initial tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
points
|
||||
.iter()
|
||||
.find(|point| point.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted gauge must be exported")
|
||||
.value,
|
||||
1.0
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_bytes"),
|
||||
vec![
|
||||
("ARCHIVE".into(), "s3".into(), 8192.0),
|
||||
("COLD".into(), "rustfs".into(), 4096.0),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_objects_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 4.0), ("COLD".into(), "rustfs".into(), 2.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_versions_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 6.0), ("COLD".into(), "rustfs".into(), 3.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 2048.0), ("COLD".into(), "rustfs".into(), 0.0),]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_objects_count"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1.0), ("COLD".into(), "rustfs".into(), 0.0),]
|
||||
);
|
||||
|
||||
// 2. Removing COLD and decreasing ARCHIVE inventory stops exporting COLD immediately.
|
||||
let decreased = TierUsageSnapshot {
|
||||
inventory_accounted: true,
|
||||
inventory: vec![TierInventoryEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 1,
|
||||
versions_count: 1,
|
||||
}],
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 1024,
|
||||
objects_count: 1,
|
||||
}],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&decreased))
|
||||
.expect("publish decreased tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_inventory_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1024.0)]
|
||||
);
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 1024.0)]
|
||||
);
|
||||
|
||||
// 3. Becoming unaccounted flips accounted to 0 and withdraws inventory gauges without emitting zeros.
|
||||
let unaccounted = TierUsageSnapshot {
|
||||
inventory_accounted: false,
|
||||
inventory: Vec::new(),
|
||||
transitions_last24h: vec![TierTransitionLast24hEntry {
|
||||
tier: "ARCHIVE".into(),
|
||||
tier_type: "s3".into(),
|
||||
total_bytes: 512,
|
||||
objects_count: 1,
|
||||
}],
|
||||
};
|
||||
snapshot
|
||||
.replace(collect_tier_usage_metrics(&unaccounted))
|
||||
.expect("publish unaccounted tier snapshot");
|
||||
let points = flush(&provider, &exporter);
|
||||
assert_eq!(
|
||||
points
|
||||
.iter()
|
||||
.find(|point| point.name == "rustfs_tier_inventory_accounted")
|
||||
.expect("accounted gauge must stay exported with value 0")
|
||||
.value,
|
||||
0.0
|
||||
);
|
||||
for metric_name in [
|
||||
"rustfs_tier_inventory_bytes",
|
||||
"rustfs_tier_inventory_objects_count",
|
||||
"rustfs_tier_inventory_versions_count",
|
||||
] {
|
||||
assert!(
|
||||
extract_tier_points(&points, metric_name).is_empty(),
|
||||
"{metric_name} must be withdrawn when inventory is unaccounted"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
extract_tier_points(&points, "rustfs_tier_transitions_last24h_bytes"),
|
||||
vec![("ARCHIVE".into(), "s3".into(), 512.0)]
|
||||
);
|
||||
|
||||
// 4. Removing the last configured tier withdraws all tier gauges cleanly.
|
||||
snapshot
|
||||
.replace(Vec::new())
|
||||
.expect("clear tier snapshot when no remote tiers remain");
|
||||
assert!(flush(&provider, &exporter).is_empty());
|
||||
|
||||
provider.shutdown().expect("shut down tier usage test provider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_or_stalled_collection_cannot_refresh_last_success_or_export_old_points() {
|
||||
let (provider, exporter, mut snapshot) = setup();
|
||||
|
||||
@@ -1025,6 +1025,7 @@ pub struct Metrics {
|
||||
current_scan_cycle_replication_checks_start: AtomicU64,
|
||||
current_scan_cycle_usage_saves_start: AtomicU64,
|
||||
scanner_set_scan_concurrency_limit: AtomicU64,
|
||||
last_scan_cycle_set_scan_concurrency_limit: AtomicU64,
|
||||
scanner_set_scans_queued: AtomicU64,
|
||||
scanner_set_scans_active: AtomicU64,
|
||||
scanner_disk_bucket_scan_states: Mutex<HashMap<ScannerDiskBucketScanKey, ScannerDiskBucketScanState>>,
|
||||
@@ -1560,6 +1561,8 @@ pub struct ScannerMetricsReport {
|
||||
#[serde(default)]
|
||||
pub current_set_scan_concurrency_limit: u64,
|
||||
#[serde(default)]
|
||||
pub last_cycle_set_scan_concurrency_limit: u64,
|
||||
#[serde(default)]
|
||||
pub current_set_scans_queued: u64,
|
||||
#[serde(default)]
|
||||
pub current_set_scans_active: u64,
|
||||
@@ -2246,6 +2249,7 @@ impl Metrics {
|
||||
current_scan_cycle_replication_checks_start: AtomicU64::new(0),
|
||||
current_scan_cycle_usage_saves_start: AtomicU64::new(0),
|
||||
scanner_set_scan_concurrency_limit: AtomicU64::new(0),
|
||||
last_scan_cycle_set_scan_concurrency_limit: AtomicU64::new(0),
|
||||
scanner_set_scans_queued: AtomicU64::new(0),
|
||||
scanner_set_scans_active: AtomicU64::new(0),
|
||||
scanner_disk_bucket_scan_states: Mutex::new(HashMap::new()),
|
||||
@@ -3039,6 +3043,10 @@ impl Metrics {
|
||||
if let Some(concurrency_limit) = concurrency_limit {
|
||||
self.scanner_set_scan_concurrency_limit
|
||||
.store(concurrency_limit as u64, Ordering::Relaxed);
|
||||
if concurrency_limit > 0 {
|
||||
self.last_scan_cycle_set_scan_concurrency_limit
|
||||
.store(concurrency_limit as u64, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
if let Some(queued) = queued {
|
||||
self.scanner_set_scans_queued.store(queued as u64, Ordering::Relaxed);
|
||||
@@ -3938,6 +3946,7 @@ impl Metrics {
|
||||
m.leader_lock_last_update_unix_secs = self.scanner_leader_lock_last_update_unix_secs.load(Ordering::Relaxed);
|
||||
m.last_cycle_end_unix_secs = self.last_scan_cycle_end_unix_secs.load(Ordering::Relaxed);
|
||||
m.current_set_scan_concurrency_limit = self.scanner_set_scan_concurrency_limit.load(Ordering::Relaxed);
|
||||
m.last_cycle_set_scan_concurrency_limit = self.last_scan_cycle_set_scan_concurrency_limit.load(Ordering::Relaxed);
|
||||
m.current_set_scans_queued = self.scanner_set_scans_queued.load(Ordering::Relaxed);
|
||||
m.current_set_scans_active = self.scanner_set_scans_active.load(Ordering::Relaxed);
|
||||
let disk_bucket_scan_states = self.scanner_disk_bucket_scan_state_snapshots();
|
||||
@@ -4483,6 +4492,7 @@ mod tests {
|
||||
let report = metrics.report().await;
|
||||
|
||||
assert_eq!(report.current_set_scan_concurrency_limit, 3);
|
||||
assert_eq!(report.last_cycle_set_scan_concurrency_limit, 3);
|
||||
assert_eq!(report.current_set_scans_queued, 5);
|
||||
assert_eq!(report.current_set_scans_active, 2);
|
||||
assert_eq!(report.current_disk_scan_concurrency_limit, 6);
|
||||
@@ -4493,6 +4503,7 @@ mod tests {
|
||||
let report = metrics.report().await;
|
||||
|
||||
assert_eq!(report.current_set_scan_concurrency_limit, 0);
|
||||
assert_eq!(report.last_cycle_set_scan_concurrency_limit, 3);
|
||||
assert_eq!(report.current_set_scans_queued, 0);
|
||||
assert_eq!(report.current_set_scans_active, 0);
|
||||
assert_eq!(report.current_disk_scan_concurrency_limit, 0);
|
||||
|
||||
@@ -3257,6 +3257,7 @@ where
|
||||
let mut superseded_backoff = ScannerRetryBackoff::default();
|
||||
let mut deferred_backoff = ScannerRetryBackoff::default();
|
||||
let mut scope_fallback_backoff = ScannerRetryBackoff::default();
|
||||
let mut pending_maintenance_backoff = ScannerRetryBackoff::default();
|
||||
let scope_fallback_slot = Arc::new(ScannerScopeFallbackSlot::default());
|
||||
let initial_runtime_config = resolve_scanner_runtime_config();
|
||||
if clean_idle_topology_supported && maintenance_generation_seen.is_none() {
|
||||
@@ -3689,8 +3690,11 @@ where
|
||||
let superseded_retry_interval = scanner_superseded_retry_interval(superseded_backoff, &runtime_config);
|
||||
let deferred_retry_interval = deferred_backoff.retry_interval(runtime_config.cycle_interval);
|
||||
let scope_fallback_retry_interval = scanner_scope_fallback_retry_interval(scope_fallback_backoff, &runtime_config);
|
||||
let pending_maintenance_retry_interval =
|
||||
scanner_pending_maintenance_retry_interval(pending_maintenance_backoff, &runtime_config);
|
||||
let mut convergence_retry_interval = superseded_retry_interval
|
||||
.or(scope_fallback_retry_interval)
|
||||
.or(pending_maintenance_retry_interval)
|
||||
.or(deferred_retry_interval);
|
||||
if let Some(retry_interval) = convergence_retry_interval {
|
||||
wait_plan.effective_interval = retry_interval;
|
||||
@@ -3953,6 +3957,7 @@ where
|
||||
) && dirty_usage_buckets_pending()
|
||||
});
|
||||
scope_fallback_backoff.record_retryable_cycle(scope_fallback.is_some());
|
||||
pending_maintenance_backoff.record_retryable_cycle(outcome == ScannerCycleOutcome::CompletedWithPendingMaintenance);
|
||||
dirty_usage_generation_seen = dirty_generation_before_cycle;
|
||||
if guard.is_lock_lost() {
|
||||
record_scanner_leader_lock_lost("Scanner leader lock lost during a scanner cycle").await;
|
||||
|
||||
@@ -225,6 +225,21 @@ pub(super) fn scanner_scope_fallback_retry_interval(
|
||||
Some(retry_interval)
|
||||
}
|
||||
|
||||
/// Prompt convergence pacing when a completed cycle still left remote dirty
|
||||
/// usage or maintenance work pending acknowledgement. Retries start at 1s and
|
||||
/// back off exponentially up to the configured cycle interval so peer dirty
|
||||
/// buckets clear quickly after bursts or restarts without spinning indefinitely.
|
||||
pub(super) fn scanner_pending_maintenance_retry_interval(
|
||||
backoff: ScannerRetryBackoff,
|
||||
runtime_config: &ScannerRuntimeConfig,
|
||||
) -> Option<Duration> {
|
||||
let exponent = backoff.consecutive_cycles.checked_sub(1)?.min(31);
|
||||
let multiplier = 1u32.checked_shl(exponent).unwrap_or(u32::MAX);
|
||||
let cycle_interval = runtime_config.cycle_interval.max(Duration::from_secs(1));
|
||||
let retry_interval = Duration::from_secs(1).saturating_mul(multiplier).min(cycle_interval);
|
||||
Some(retry_interval)
|
||||
}
|
||||
|
||||
const SCANNER_PUBLICATION_PROOF_RETRY_MAX_INTERVAL: Duration = Duration::from_secs(30);
|
||||
|
||||
pub(crate) fn scanner_publication_proof_retry_delay(consecutive_failures: u32) -> Duration {
|
||||
|
||||
@@ -9351,6 +9351,25 @@ fn superseded_retry_caps_at_the_default_cycle_and_resets_after_convergence() {
|
||||
assert_eq!(scanner_superseded_retry_interval(backoff, &config), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_maintenance_retry_converges_promptly_and_caps_at_cycle_interval() {
|
||||
let config = ScannerRuntimeConfig {
|
||||
cycle_interval: Duration::from_secs(60),
|
||||
..Default::default()
|
||||
};
|
||||
let mut backoff = ScannerRetryBackoff::default();
|
||||
assert_eq!(scanner_pending_maintenance_retry_interval(backoff, &config), None);
|
||||
for expected in [1, 2, 4, 8, 16, 32, 60, 60] {
|
||||
backoff.record_retryable_cycle(true);
|
||||
assert_eq!(
|
||||
scanner_pending_maintenance_retry_interval(backoff, &config),
|
||||
Some(Duration::from_secs(expected))
|
||||
);
|
||||
}
|
||||
backoff.record_retryable_cycle(false);
|
||||
assert_eq!(scanner_pending_maintenance_retry_interval(backoff, &config), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn superseded_retry_caps_fast_cycles_without_changing_the_generic_retry_cap() {
|
||||
let mut backoff = ScannerRetryBackoff::default();
|
||||
|
||||
+2
-1
@@ -16,7 +16,8 @@ collection:
|
||||
- [Read-only BTF declaration inspection](operations/btf-prototype-inspection.md) — bounded prototypes and scalar member layouts, explicit void handling, and independent native references.
|
||||
|
||||
- [Internode HTTP streaming transport](operations/internode-http-transport.md) — protocol selection, pooled connection isolation, and distributed read validation.
|
||||
- [cuObject S3-over-RDMA GET](operations/cuobject-s3-over-rdma.md) — optional `cuobject` feature: GET straight into client GPU/host memory via `x-amz-rdma-token`; build, settings, wire contract.
|
||||
- [S3-over-RDMA on NIXL/UCX](operations/nixl-s3-over-rdma.md) — optional `nixl` feature: GET, PUT, UploadPart, and internode shard traffic over NIXL/UCX into client GPU or host memory; build, settings, wire contract, and large-PUT tuning.
|
||||
- [cuObject S3-over-RDMA](operations/cuobject-s3-over-rdma.md) — optional `cuobject` feature: GET, PUT, and UploadPart straight into client GPU/host memory via `x-amz-rdma-token` and GDS `cufile.json`; build, settings, wire contract.
|
||||
- [Erasure shard size](operations/erasure-shard-size.md) — `RUSTFS_ERASURE_SHARD_BYTES`: larger, aligned shards for new objects; rules and memory cost.
|
||||
- [Object data cache fill on PUT](operations/object-data-cache-fill-on-put.md) — `RUSTFS_OBJECT_DATA_CACHE_FILL_ON_PUT`: insert plain streaming PUT bodies so the first GET hits.
|
||||
|
||||
|
||||
@@ -21,7 +21,8 @@ This document describes the design and the invariants of RustFS's S3-over-RDMA d
|
||||
|---|---|---|
|
||||
| Client last hop, cuObject | `rustfs/src/app/object/cuobject.rs`, `crates/cuobject`, `crates/cuobject-sys` | The `cuobject` feature enables `x-amz-rdma-token` transfers. `rustfs-cuobject` manages registered buffers and transfers. `rustfs-cuobject-sys` builds the C++ bridge and links the NVIDIA server SDK. |
|
||||
| Client last hop, NIXL | `crates/nixl/src/lib.rs` (`RdmaToken::from_headers`), `crates/nixl/src/remotes.rs`, `crates/nixl/src/mem.rs` | NIXL/UCX transport selected by the `nixl` feature. The client names a registered `dram` or `vram` buffer; the server WRITEs (GET) or READs (PUT) it. |
|
||||
| Shared pipeline | `rustfs/src/app/object/cuobject.rs` | Segment fan-out of large GETs, staging chunks, shard arena, completion handling. The same pipeline serves both transports; only the transfer layer differs. |
|
||||
| Passive NIXL client SDK | `crates/nixl/src/client.rs` (`RegisteredClientWindow`, `ClientWindowHttp`) | Optional `client-http` feature on `rustfs-nixl`: exclusively owned passive host windows that sign and verify one-shot S3 RDMA control exchanges and quarantine memory on indeterminate outcomes. |
|
||||
| Shared pipeline | `rustfs/src/app/object/cuobject.rs` | Segment fan-out of large plain GETs, staging chunks, shard arena, completion handling. The same pipeline serves both transports; compressed and encrypted objects bypass segmented zero-copy emit and stream sequentially over RDMA. |
|
||||
| Device health | `crates/nixl/src/devices.rs` | Startup check that leaves out RDMA devices that are down, slow or flapping. |
|
||||
| Internode, NIXL | `crates/ecstore/src/cluster/rpc/nixl_internode.rs`, `rustfs/src/storage/rpc/nixl_read.rs` | `RUSTFS_INTERNODE_DATA_TRANSPORT=nixl`: signed control request over HTTP, data over NIXL, for shard reads and writes. |
|
||||
| Transport selection | `crates/ecstore/src/cluster/rpc/internode_data_transport.rs` | `tcp-http`, `tcp` or `nixl`. Internode RDMA runs over NIXL. |
|
||||
@@ -33,7 +34,7 @@ This document describes the design and the invariants of RustFS's S3-over-RDMA d
|
||||
## Design decisions
|
||||
|
||||
- **Signed S3 request, RDMA payload.** The client sends a normal signed S3 request whose body is empty. Three headers name its NIXL agent, its agent metadata and one registered buffer. The reply comes back only after the last transfer completed, so the client may use its buffer as soon as the response arrives. Clients sign with `UNSIGNED-PAYLOAD`, because the payload never crosses HTTP.
|
||||
- **NIXL/UCX replaced cuObject as the default.** UCX addresses devices by GID, LID and queue-pair numbers carried in the agent metadata. That works on the GPU-side InfiniBand rails without IPoIB or a subnet manager, and on RoCE without `rdma_cm`. cuObject stays as a compile-time alternative.
|
||||
- **NIXL/UCX is the preferred compile-time RDMA backend.** Neither `nixl` nor `cuobject` is enabled in default builds; when both features are compiled together, `nixl` takes precedence. UCX addresses devices by GID, LID and queue-pair numbers carried in the agent metadata, which works on GPU-side InfiniBand rails without IPoIB or a subnet manager and on RoCE without `rdma_cm`. cuObject remains a compile-time alternative for NVIDIA GPUDirect Storage `x-amz-rdma-token` clients.
|
||||
- **GPU or host memory.** A `vram:<gpu>:<addr>:<len>` buffer works when the client's NIC can reach GPU memory (GPUDirect over dma-buf with the open NVIDIA driver; `nvidia_peermem` is not needed). The server does not need to know which kind it is writing into.
|
||||
- **Ranges are first class.** A ranged GET lands at offset 0 of the named buffer. Clients split large objects into ranged requests spread over servers to raise parallelism.
|
||||
- **Internode traffic on the same rails.** With `nixl` internode transport, every shard read and write between servers also moves over NIXL. The control request stays on the internode HTTP connection and binds the transfer with a signed metadata digest (and a one-time nonce for writes), so a replayed request cannot redirect a transfer.
|
||||
@@ -51,7 +52,7 @@ This document describes the design and the invariants of RustFS's S3-over-RDMA d
|
||||
|
||||
## Clients
|
||||
|
||||
Clients live outside this repository. Two LLM-serving clients were built against this path and shaped its requirements:
|
||||
`crates/nixl` (`client-http` feature, `RegisteredClientWindow`) provides the passive host-window primitive consumed by external Rust clients such as `rustfs/cli`, quarantining registered pages until process exit whenever a transfer lacks a verified completion receipt or pre-DMA conditional rejection. Higher-level LLM-serving clients live outside this repository and shaped this data path's requirements:
|
||||
|
||||
- **Model weight loading into GPU memory.** The loader plans a checkpoint into whole-tensor units, fetches each unit with several ranged NIXL GETs spread over the servers straight into GPU memory, and shares it with the other ranks over NCCL. No checkpoint byte touches disk or host memory, so ranged GETs into `vram` buffers and many concurrent requests per client are the hot path.
|
||||
- **KV-cache offload.** A hierarchical-cache backend writes groups of KV pages (tens of MB each) once per prefill and reads them back from any node. It needs cheap existence checks, PUTs that return only after the bytes are durable enough for the bucket's durability setting, and ETags that do not cost an MD5 per object, hence per-bucket XXH3 ETags and relaxed durability.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Tier Stats Contract
|
||||
|
||||
**Use this when:** changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request.
|
||||
**Source of truth:** `rustfs/src/admin/handlers/tier.rs` (`GetTierInfo`, `tier_stats_body`), `crates/ecstore/src/services/notification_sys.rs` (`ClusterTierDailyStats`), `crates/ecstore/src/bucket/lifecycle/tier_last_day_stats.rs` (`LastDayTierStats`), `crates/ecstore/src/services/tier/warm_backend.rs` (`MeteredWarmBackend`), `crates/obs/src/metrics/schema/tier.rs`.
|
||||
**Use this when:** changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request, inventory snapshot, or rolling transition counter.
|
||||
**Source of truth:** `rustfs/src/admin/handlers/tier.rs` (`GetTierInfo`, `tier_stats_body`), `crates/ecstore/src/services/notification_sys.rs` (`ClusterTierDailyStats`), `crates/ecstore/src/bucket/lifecycle/tier_last_day_stats.rs` (`LastDayTierStats`), `crates/ecstore/src/services/tier/warm_backend.rs` (`MeteredWarmBackend`), `crates/obs/src/metrics/schema/tier.rs`, `crates/obs/src/metrics/collectors/tier.rs`, `crates/obs/src/metrics/stats_collector.rs`, `crates/obs/src/metrics/scheduler.rs`.
|
||||
|
||||
## Two quantities, never one
|
||||
|
||||
@@ -41,3 +41,15 @@ The label set is closed by two enums in `crates/scanner-metrics/src/metrics.rs`:
|
||||
`timeout` and `cancelled` are recognised from `std::io::ErrorKind`, never from an error message, so a message that mentions an endpoint cannot reach a label. Until the transition client grows bounded deadlines (rustfs/backlog#2204), few failures actually carry `TimedOut`, so most land in `backend_error`; the classification is the seam that work extends, not a claim that timeouts are already distinguishable.
|
||||
|
||||
The outcome classifies the request only. A transition whose remote PUT succeeded and whose local commit then failed is a `success` here: the remote service did perform the request, and recording it as a tier failure would hide a leaked remote object behind an apparent backend outage. Local commit failure is observable through the ILM task-event metrics instead.
|
||||
|
||||
## Tier inventory and transition metrics
|
||||
|
||||
Periodic OTLP gauges in `crates/obs/src/metrics/schema/tier.rs` expose the same two quantities as `GET /rustfs/admin/v3/tier-stats` whenever at least one remote tier is configured:
|
||||
|
||||
- **Cluster-wide stored inventory** — `rustfs_tier_inventory_bytes`, `rustfs_tier_inventory_objects_count`, and `rustfs_tier_inventory_versions_count` carry `tier` and `tier_type` labels for configured remote tiers present in `DataUsageInfo::tier_stats`. Local storage classes (`STANDARD`, `REDUCED_REDUNDANCY`) and unconfigured tiers are excluded so summing cold-tier inventory does not include hot local data.
|
||||
- **Inventory accounting status** — `rustfs_tier_inventory_accounted` (unlabeled, snapshot-wide) reports `1` when the persisted usage snapshot carries `tier_stats` and `0` when it is `not-accounted` or `unavailable`. Whenever status is `0` or a configured tier is absent from `DataUsageInfo::tier_stats`, per-tier inventory gauges are omitted and never fabricated as `0`.
|
||||
- **Node-local rolling 24h activity** — `rustfs_tier_transitions_last24h_bytes` and `rustfs_tier_transitions_last24h_objects_count` carry `tier` and `tier_type` labels and export each node's local `LastDayTierStats` ring aged forward to the current UTC hour (`merge(LastDayTierStats::default())`). Exporting node-local values avoids periodic all-to-all internode RPCs during metric scrapes; Prometheus/OTLP consumers sum across reporting nodes (`sum by (rustfs_cluster_id, tier, tier_type)`).
|
||||
|
||||
Unlike hot-path request counters (`rustfs_tier_requests_*`), these periodic snapshot gauges carry configured remote tier names (`tier`) and lowercase provider types (`tier_type`), matching the bounded cardinality of configured tiers. Endpoints, credentials, and object keys remain strictly forbidden as labels.
|
||||
|
||||
Inventory and transition gauges are published through an unscoped `StorageSnapshotMetrics` instance without zero tombstones: removing a tier or losing inventory accounting withdraws the series immediately rather than emitting synthetic zeros. See [bucket usage metrics](../operations/bucket-usage-metrics.md#remote-tier-inventory-and-transition-metrics) for query examples and the relationship to `rustfs_cluster_usage_buckets_total_bytes`.
|
||||
|
||||
@@ -104,6 +104,47 @@ usage snapshot. A shorter scrape interval cannot repair an incomplete scanner
|
||||
snapshot. The scanner publication and cache path is shared with the Console's
|
||||
usage display.
|
||||
|
||||
## Remote tier inventory and transition metrics
|
||||
|
||||
When at least one remote tier is configured, RustFS exports six OpenTelemetry gauges aligned with `GET /rustfs/admin/v3/tier-stats` (see [tier stats contract](../architecture/tier-stats-contract.md)) from the same cached scanner usage snapshot and local 24-hour transition ring:
|
||||
|
||||
| Metric | Labels | Scope | Admin API mapping (`GET /rustfs/admin/v3/tier-stats`) |
|
||||
|---|---|---|---|
|
||||
| `rustfs_tier_inventory_bytes` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.totalSize` |
|
||||
| `rustfs_tier_inventory_objects_count` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.numObjects` |
|
||||
| `rustfs_tier_inventory_versions_count` | `tier`, `tier_type` | Cluster-wide snapshot | `tiers[].inventory.numVersions` |
|
||||
| `rustfs_tier_inventory_accounted` | *(none)* | Cluster-wide snapshot | `1` when `inventory.status == "accounted"`, else `0` |
|
||||
| `rustfs_tier_transitions_last24h_bytes` | `tier`, `tier_type` | Node-local rolling 24h | Node contribution to `tiers[].transitionsLast24h.totalSize` |
|
||||
| `rustfs_tier_transitions_last24h_objects_count` | `tier`, `tier_type` | Node-local rolling 24h | Node contribution to `tiers[].transitionsLast24h.numObjects` |
|
||||
|
||||
### How bucket usage, local disk capacity, and cold-tier inventory relate
|
||||
|
||||
- **Bucket logical usage** (`rustfs_cluster_usage_buckets_total_bytes`) counts logical bytes across retained versions in the bucket, including versions transitioned to remote tiers (excluding delete markers and erasure-coding overhead).
|
||||
- **Remote tier inventory** (`rustfs_tier_inventory_bytes`) is the subset of logical bytes currently accounted on a configured remote tier. It excludes local storage classes (`STANDARD`, `REDUCED_REDUNDANCY`) and does not reconcile the entire remote bucket's physical billing total outside RustFS accounting.
|
||||
- **Local physical or usable disk capacity** reflects data stored on local cluster drives (including erasure-coding parity and compression) and excludes object payloads already transitioned to remote tiers.
|
||||
|
||||
### Querying remote tier gauges
|
||||
|
||||
Because every node exports the same cluster-wide inventory snapshot, deduplicate reporting nodes instead of summing them, and guard queries with `rustfs_tier_inventory_accounted == 1`:
|
||||
|
||||
```promql
|
||||
max by (rustfs_cluster_id, tier, tier_type) (
|
||||
rustfs_tier_inventory_bytes{rustfs_cluster_id="production-a"}
|
||||
) and on (rustfs_cluster_id) (
|
||||
max by (rustfs_cluster_id) (rustfs_tier_inventory_accounted{rustfs_cluster_id="production-a"}) == 1
|
||||
)
|
||||
```
|
||||
|
||||
Because each node exports only its own committed transitions from the rolling 24-hour ring (aged forward to the current UTC hour), sum across reporting nodes for the cluster total:
|
||||
|
||||
```promql
|
||||
sum by (rustfs_cluster_id, tier, tier_type) (
|
||||
rustfs_tier_transitions_last24h_bytes{rustfs_cluster_id="production-a"}
|
||||
)
|
||||
```
|
||||
|
||||
When `inventory.status` is `not-accounted` or `unavailable`, or when a newly configured tier has not yet appeared in the scanner snapshot, RustFS omits `rustfs_tier_inventory_{bytes,objects_count,versions_count}` rather than publishing `0`. When no remote tiers are configured, none of these six gauges are exported.
|
||||
|
||||
## Regression checks
|
||||
|
||||
The SDK test uses the production bucket collector and an actual OpenTelemetry
|
||||
@@ -114,6 +155,12 @@ usage, and removal from subsequent exports:
|
||||
RUSTUP_TOOLCHAIN=stable cargo test -p rustfs-obs actual_sdk_exports_bucket_size_and_object_count_as_current_gauges --lib
|
||||
```
|
||||
|
||||
The tier SDK regression test verifies accounted remote-tier inventory, decreasing values, tier removal, and withdrawal of inventory gauges when the snapshot becomes unaccounted:
|
||||
|
||||
```bash
|
||||
RUSTUP_TOOLCHAIN=stable cargo test -p rustfs-obs actual_sdk_exports_tier_inventory_and_transitions_without_fabricating_zeros --lib
|
||||
```
|
||||
|
||||
The PromQL fixture checks same-name buckets in separate clusters and multiple
|
||||
reporting nodes. Run it from `.docker/observability/tests`:
|
||||
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
# cuObject S3-over-RDMA GET (last hop into client memory)
|
||||
# cuObject S3-over-RDMA (GPUDirect Storage object transport)
|
||||
|
||||
RustFS can serve `GetObject` over NVIDIA's cuObject protocol: the client
|
||||
(for example the NIXL `OBJ` plugin used by the SGLang `--load-format rdma`
|
||||
loader) registers its GPU or host buffer with the cuObject client library,
|
||||
puts the resulting RDMA token in the `x-amz-rdma-token` request header, and
|
||||
RustFS writes the object bytes straight into that buffer with one-sided RDMA
|
||||
writes. The HTTP response carries no body.
|
||||
RustFS can serve `GetObject`, `PutObject`, and `UploadPart` over NVIDIA's GPUDirect Storage (GDS) cuObject protocol: the client (for example the NIXL `OBJ` plugin used by the SGLang `--load-format rdma` loader, or `rc --rdma-backend cuobject`) registers its GPU (`VRAM`) or host buffer with the cuObject client library, puts the resulting RDMA descriptor in the `x-amz-rdma-token` request header, and RustFS moves the object bytes directly to or from that buffer with one-sided RDMA operations. The HTTP message carries no payload body.
|
||||
|
||||
This is the Phase 1 "last hop" of the S3-over-RDMA plan. It is independent of
|
||||
the internode shard transport selected by `RUSTFS_INTERNODE_DATA_TRANSPORT`;
|
||||
@@ -22,9 +17,7 @@ architecture. A default build does not require the NVIDIA SDK.
|
||||
CUOBJSERVER_ROOT=/usr cargo build --release -p rustfs --features cuobject
|
||||
```
|
||||
|
||||
The binary dynamically links `libcuobjserver.so.2`; keep it on the library
|
||||
path at run time. Without the feature every setting below is ignored and
|
||||
tokens are left untouched, so the client falls back to a normal HTTP GET.
|
||||
The binary dynamically links `libcuobjserver.so.2`; keep it on the library path at run time and raise the locked-memory limit (`ulimit -l unlimited` or systemd `LimitMEMLOCK=infinity`) so the server can pin `RUSTFS_CUOBJECT_POOL_BYTES` and any shard arena. Without the feature (or when both `nixl` and `cuobject` features are compiled together, in which case `nixl` takes precedence) every `cuobject` setting below is ignored and `x-amz-rdma-token` is left untouched.
|
||||
|
||||
## Settings
|
||||
|
||||
@@ -33,8 +26,13 @@ tokens are left untouched, so the client falls back to a normal HTTP GET.
|
||||
| `RUSTFS_CUOBJECT_ENABLE` | `false` | Start the cuObject servers and honour `x-amz-rdma-token`. |
|
||||
| `RUSTFS_CUOBJECT_ADDRS` | local endpoint hosts | Comma-separated RDMA (RoCE/IB) IPs to serve from; one cuObject server per address. |
|
||||
| `RUSTFS_CUOBJECT_PORT` | `18515` | cuObject control port; the client never dials it directly with the DC transport. |
|
||||
| `RUSTFS_CUOBJECT_CHUNK_BYTES` | `16 MiB` | Staging chunk: the object is streamed into registered host memory in chunks of this size and each chunk is written to the client with one RDMA operation. Max 1 GiB. |
|
||||
| `RUSTFS_CUOBJECT_CHUNK_BYTES` | `16 MiB` | Staging chunk: the object is streamed into registered host memory in chunks of this size and each chunk is moved with one RDMA operation. Max 1 GiB. |
|
||||
| `RUSTFS_CUOBJECT_INFLIGHT_WRITES` | `3` | Staging chunks per GET: while one chunk is being RDMA-written the decoder keeps filling the next ones, so the stripe loop never waits for a write. Each costs one chunk of the pool; a busy pool degrades to fewer chunks rather than failing the GET. |
|
||||
| `RUSTFS_CUOBJECT_PUT_READ_AHEAD` | `4` | Staging chunks RDMA-read ahead of the consumer per PUT or UploadPart; each holds one chunk of the pool. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT` | `8` | Concurrent erasure-block-aligned segments one plain GET can split into on the server (`1` disables fan-out). Compressed and encrypted objects stream sequentially over RDMA. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES` | `192 MiB` | Smallest segment size (in bytes, rounded up to whole erasure blocks) eligible for its own segment producer. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT_BUDGET` | `16` | Total extra segment producers shared across concurrent RDMA GETs on the node. |
|
||||
| `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES` | `0` | Registered host memory (in bytes, `0` disables; otherwise at least `RUSTFS_ERASURE_SHARD_BYTES`, default `4 MiB`) for zero-copy erasure shard emission. Registered on the first configured cuObject server; requests routed to additional `RUSTFS_CUOBJECT_ADDRS` fall back to staging chunks. |
|
||||
| `RUSTFS_CUOBJECT_POOL_BYTES` | `1 GiB` | Registered staging pool per server; bounds concurrent RDMA GETs to about `pool / (chunk x inflight)`. |
|
||||
| `RUSTFS_CUOBJECT_NUM_DCIS` | `128` | DC initiators the server library opens. |
|
||||
| `RUSTFS_CUOBJECT_ASYNC_TRANSFERS` | `true` | Complete transfers through the library's asynchronous mode: the write is submitted with a handle and the task waits on the channel's completion descriptor, so no blocking thread is held per transfer. `false` keeps one blocking library call per transfer. |
|
||||
@@ -45,9 +43,7 @@ state=skipped` and serves plain HTTP.
|
||||
|
||||
## Wire contract
|
||||
|
||||
Request: a normal SigV4-signed `GET` with `x-amz-content-sha256:
|
||||
UNSIGNED-PAYLOAD`, a `Range` header covering the client buffer, and
|
||||
`x-amz-rdma-token: <addr>:<size>:<rkey>:<lid>:<dctn>:<gidpresent>:<gid>`.
|
||||
Request: a normal SigV4-signed `GET` with `x-amz-content-sha256: UNSIGNED-PAYLOAD`, an optional `Range` header, and `x-amz-rdma-token: <addr>:<size>:<rkey>:<lid>:<dctn>:<gidpresent>[:<gid>][:<gidpresent2>[:<gid2>]]` (colon-separated hex fields without `0x` prefixes, positive `size`, and a 32-hex-digit GID whenever `gidpresent` is `1`).
|
||||
|
||||
Response: the usual `GetObject` headers (ETag included) with an empty body
|
||||
and `Content-Length: 0`, plus:
|
||||
@@ -91,14 +87,29 @@ keeps its retained bytes independently of the staging pool.
|
||||
|
||||
## Validation
|
||||
|
||||
1. `RUSTFS_CUOBJECT_ENABLE=true RUSTFS_CUOBJECT_ADDRS=<roce ip>` on each node
|
||||
and confirm `cuobject_service_state state=started` in the log.
|
||||
2. On the client, point `CUFILE_ENV_PATH_JSON` at a `cufile.json` whose
|
||||
`rdma_dev_addr_list` names the client's RDMA IP.
|
||||
3. Run the SGLang loader with `--load-format rdma` and
|
||||
`"accelerated": true` in `--model-loader-extra-config`; the NIXL `OBJ`
|
||||
backend then advertises `VRAM_SEG` and every tensor arrives in GPU memory
|
||||
without an HTTP body.
|
||||
1. Set `RUSTFS_CUOBJECT_ENABLE=true` and `RUSTFS_CUOBJECT_ADDRS=<roce ip>` on each node and confirm `cuobject_service_state state=started` in the log.
|
||||
2. On the client, write a GDS `cufile.json` naming the client's RDMA IP(s) and GPUDirect peer mode, then export `CUFILE_ENV_PATH_JSON` (and `CUOBJ_ENV_PATH_JSON` for direct `libcuobjclient` consumers such as `rc --rdma-backend cuobject`):
|
||||
|
||||
```json
|
||||
{
|
||||
"execution": {
|
||||
"parallel_io": false
|
||||
},
|
||||
"properties": {
|
||||
"allow_compat_mode": true,
|
||||
"use_pci_p2pdma": true,
|
||||
"rdma_peer_type": "dmabuf",
|
||||
"rdma_dev_addr_list": ["10.0.1.20"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
export CUFILE_ENV_PATH_JSON=/etc/cufile.json
|
||||
export CUOBJ_ENV_PATH_JSON=/etc/cufile.json
|
||||
```
|
||||
|
||||
3. Run the SGLang loader with `--load-format rdma` and `"accelerated": true` in `--model-loader-extra-config` (or `rc --data-transport rdma --rdma-backend cuobject` from `rustfs/cli`); the NIXL `OBJ` backend then advertises `VRAM_SEG` and every tensor arrives in GPU memory without an HTTP body.
|
||||
|
||||
The generic `x-amz-rdma-token` client lives in NIXL 1.6.0 (git `2ff2509f`,
|
||||
2026-11-02) or newer. The published `nixl-cu13` 1.5.2 wheel ships only the
|
||||
|
||||
@@ -19,17 +19,15 @@ also enabled.
|
||||
|
||||
## Build
|
||||
|
||||
- Cargo feature `nixl` on the `rustfs` crate (`--features rdma,nixl`); the
|
||||
`rustfs-nixl` crate depends on the `nixl-sys` binding from the NIXL
|
||||
repository at tag `v1.5.2`.
|
||||
- `NIXL_PREFIX` points at a prefix with `include/` (the NIXL C++ headers of
|
||||
that tag) and `lib/` holding `libnixl.so`, `libnixl_build.so`,
|
||||
`libnixl_common.so`, `libserdes.so`, `libstream.so` and
|
||||
`lib/plugins/libplugin_UCX.so`. The `nixl-cu13` wheel ships the libraries
|
||||
(under `site-packages/.nixl_cu13.mesonpy.libs/`); the headers come from the
|
||||
repository. `bindgen` needs `libclang` at build time.
|
||||
- At run time the server needs `LD_LIBRARY_PATH` on that `lib/` and
|
||||
`NIXL_PLUGIN_DIR` on `lib/plugins`.
|
||||
- Enable the Linux `nixl` Cargo feature on the `rustfs` crate (`cargo build --release -p rustfs --features nixl`). Neither `nixl` nor `cuobject` is enabled in default builds; if both features are passed together, `nixl` takes precedence.
|
||||
- `rustfs-nixl` compiles against the workspace `nixl-sys` binding (NIXL `1.5.2` C++ API). Set `NIXL_PREFIX` to an installation prefix containing `include/` and `lib/` (`libnixl.so`, `libnixl_build.so`, `libnixl_common.so`, `libserdes.so`, `libstream.so`, and `lib/plugins/libplugin_UCX.so`, or the multiarch `lib/<triplet>/` layout on Debian/Ubuntu). `bindgen` requires `g++` (C++20) and `libclang` at build time.
|
||||
- Set `NIXL_NO_STUBS_FALLBACK=1` for production builds so missing NIXL headers or libraries fail compilation instead of falling back to `nixl-sys`'s `dlopen` stub.
|
||||
- At run time, include the NIXL library directory on `LD_LIBRARY_PATH`, point `NIXL_PLUGIN_DIR` at the `plugins` directory containing `libplugin_UCX.so`, and raise the locked-memory limit (`ulimit -l unlimited` or systemd `LimitMEMLOCK=infinity`) so UCX can pin `RUSTFS_NIXL_POOL_BYTES` and `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES`.
|
||||
|
||||
```bash
|
||||
NIXL_PREFIX=/opt/nvidia/nvda_nixl NIXL_NO_STUBS_FALLBACK=1 \
|
||||
cargo build --release -p rustfs --features nixl
|
||||
```
|
||||
|
||||
## Settings
|
||||
|
||||
@@ -37,7 +35,7 @@ also enabled.
|
||||
|---|---|---|
|
||||
| `RUSTFS_NIXL_ENABLE` | `false` | Serve requests that carry the NIXL headers over NIXL. |
|
||||
| `RUSTFS_NIXL_AGENT_NAME` | `rustfs-<first local endpoint host>` | This node's agent name; must be unique in the cluster. |
|
||||
| `RUSTFS_NIXL_UCX_DEVICES` | all devices | Comma-separated UCX device names (`mlx5_9,mlx5_10`; NIXL adds the port); pin the agent to the rails that reach the clients. With `UCX_MAX_RMA_RAILS=2` in the server's environment, UCX stripes every write across two of these ports and the client must have registered its buffer on both of them, or the transfer fails and the GET is declined. |
|
||||
| `RUSTFS_NIXL_UCX_DEVICES` | all devices | Comma-separated UCX device names (`mlx5_9,mlx5_10`; NIXL adds the port); pin the agent to the rails that reach the clients. With `UCX_MAX_RMA_RAILS=2` in the server's environment, UCX stripes every write across two of these ports and the client must have registered its buffer on both of them, or the native transfer fails (`InternalError`). |
|
||||
| `RUSTFS_NIXL_NUM_WORKERS` | `1` | UCX progress workers of the agent. |
|
||||
| `RUSTFS_NIXL_CHUNK_BYTES` | `16 MiB` | Staging chunk, one transfer descriptor at most. |
|
||||
| `RUSTFS_NIXL_POOL_BYTES` | `1 GiB` | Registered staging memory. |
|
||||
@@ -46,14 +44,21 @@ also enabled.
|
||||
| `RUSTFS_NIXL_DEVICE_CHECK` | `true` | Check the devices at startup and leave out unhealthy ones (see below). |
|
||||
| `RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS` | `16` | Leave out a device whose link dropped this many times more since boot than the quietest device of its link layer; `0` skips this test. |
|
||||
| `RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS` | `3000` | How long the startup check watches the link counters; `0` skips the watch. |
|
||||
| `RUSTFS_INTERNODE_DATA_TRANSPORT` | `tcp-http` | `nixl` moves internode shard reads over NIXL too (see below). |
|
||||
| `RUSTFS_INTERNODE_DATA_TRANSPORT` | `tcp-http` | `nixl` moves internode shard reads and writes over NIXL (requires the node's NIXL agent; see below). |
|
||||
| `RUSTFS_NIXL_INTERNODE_DEPTH` | `4` | Internode chunk requests in flight per remote shard stream. |
|
||||
| `RUSTFS_CUOBJECT_PUT_READ_AHEAD` | `4` | Staging chunks read from the client's buffer ahead of the PUT body's consumer; each holds one chunk of the pool. |
|
||||
|
||||
The pipeline settings `RUSTFS_CUOBJECT_GET_FANOUT`,
|
||||
`RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES`, `RUSTFS_CUOBJECT_GET_FANOUT_BUDGET`,
|
||||
`RUSTFS_CUOBJECT_INFLIGHT_WRITES` and `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES`
|
||||
apply unchanged.
|
||||
### Shared pipeline settings
|
||||
|
||||
These variables govern the S3-over-RDMA object pipeline for both `nixl` and `cuobject`:
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `RUSTFS_CUOBJECT_INFLIGHT_WRITES` | `3` | Staging chunks kept in flight per GET so decoding overlaps RDMA writes. |
|
||||
| `RUSTFS_CUOBJECT_PUT_READ_AHEAD` | `4` | Staging chunks read from the client's buffer ahead of the PUT or UploadPart consumer; each holds one chunk of the pool. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT` | `8` | Concurrent erasure-block-aligned segments one plain GET can split into on the server (`1` disables fan-out). Compressed and encrypted objects bypass the segmented sink and stream sequentially over RDMA. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES` | `192 MiB` | Smallest segment size (in bytes, rounded up to whole erasure blocks) eligible for its own segment producer. |
|
||||
| `RUSTFS_CUOBJECT_GET_FANOUT_BUDGET` | `16` | Total extra segment producers shared fairly across concurrent RDMA GETs on the node (`budget / active_gets`, clamped to `1..=fanout`). |
|
||||
| `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES` | `0` | Registered host memory (in bytes, `0` disables; otherwise at least `RUSTFS_ERASURE_SHARD_BYTES`, default `4 MiB`) that the erasure decoder reads shards into so plain data shards are RDMA-written in place without a staging copy. |
|
||||
|
||||
### Large-object PUT tuning
|
||||
|
||||
@@ -63,7 +68,7 @@ Several settings outside the NIXL variables decide PUT throughput on large hosts
|
||||
- `MIMALLOC_ALLOW_THP=0`: with transparent huge pages in `madvise` mode, the allocator's huge-page requests for the per-stripe buffers send the kernel into direct compaction, which took about a third of the CPU during PUTs.
|
||||
- `MIMALLOC_PURGE_DELAY=-1`: the allocator keeps freed memory for reuse instead of returning it to the kernel. Every PUT allocates and frees tens of megabytes of stripe and staging buffers, and returning them made the kernel fault in and zero fresh pages, shoot down TLBs and compact memory under its zone lock. Keeping them raised a 4-client PUT of 57 MB objects from about 14 to about 18 GB/s on two servers. The process's resident memory then stays at its peak.
|
||||
- `RUSTFS_OBJECT_DATA_CACHE_FILL_ON_PUT=false` for write-heavy buckets such as an LLM KV cache: fill-on-put copies every PUT body that fits the cache entry limit into the object data cache, which cost about 30-40 ms per 57 MB object. Without it, an RDMA PutObject body also stays in the staging chunks it was read into (no copy).
|
||||
- `RUSTFS_OBJECT_ETAG_MD5_OFFLOAD_MIN_BYTES` (default 8 MiB, `0` turns it off): bodies at least this large compute their ETag MD5 on a blocking-pool thread while the body streams into the erasure encoder, instead of inline before it. The ETag and the Content-MD5 check are unchanged; the PUT fails before commit on a mismatch.
|
||||
- `RUSTFS_OBJECT_ETAG_MD5_OFFLOAD_MIN_BYTES` (default `0`, disabled; set `8388608` for an 8 MiB threshold): when non-zero, bodies at least this large compute their ETag MD5 on a blocking-pool thread while the body streams into the erasure encoder, instead of inline on the request worker. Each offloaded upload holds one blocking-pool thread until its body finishes, so size the threshold against concurrent upload admission. The ETag and Content-MD5 check are unchanged; the PUT fails before commit on a mismatch.
|
||||
- `RUSTFS_OBJECT_DIRECT_IO_WRITE_ENABLE=true`: shard files are written with O_DIRECT instead of through the page cache, which otherwise costs a copy into freshly allocated, zeroed cache pages, zone-lock contention and compaction on every write. With four PUT clients on two servers (57 MB objects) it more than doubled the aggregate (7 to 16-21 GB/s) while reads of the just-written objects, now served by the drives, stayed within about 10%. The NIXL internode shard writes finish every file with a writer shutdown, which the direct writer needs to write its trailing sub-alignment bytes.
|
||||
- A per-bucket XXH3 ETag for buckets whose clients never treat the ETag as an MD5, such as an LLM KV cache: objects written to the bucket without Content-MD5 get an XXH3-128 ETag in the same 32-hex-digit form, an order of magnitude cheaper to compute. It halved the single-stream PUT of 57 MB objects (105 to 55 ms) but did not raise the saturated aggregate. Other buckets keep MD5 ETags, so ordinary S3 clients (rclone checksums, SDKs that verify an upload against the returned ETag) are unaffected. See "Per-bucket ETag algorithm" below.
|
||||
|
||||
@@ -97,13 +102,14 @@ Request headers (GET, PUT, UploadPart):
|
||||
|---|---|
|
||||
| `x-rustfs-nixl-agent` | The client's agent name (printable ASCII, up to 128 bytes). |
|
||||
| `x-rustfs-nixl-metadata` | The client's agent metadata (`get_local_md`), base64. Send on each request for reliable reuse across nodes and cache eviction. The server can accept an omitted value while the registration is cached. In-flight requests pin the registration, including timed-out transfers until native completion. The five-minute idle period starts when the last native request finishes. The server checks once a minute and may reclaim idle registrations sooner under cache pressure. |
|
||||
| `x-rustfs-nixl-buffer` | `<dram|vram>:<device>:<address>:<length>`: the registered buffer the object (or the requested range) lands in from offset 0, or is read from for a PUT. Address and length are decimal or `0x` hex. |
|
||||
| `x-rustfs-nixl-buffer` | `<dram|vram>:<device>:<address>:<length>` (case-insensitive; `host` and `gpu` are accepted aliases): the registered buffer the object (or requested range) lands in from offset 0, or is read from for a PUT or UploadPart. Address and positive length are decimal or `0x` hex. |
|
||||
|
||||
Reply headers: `x-amz-rdma-reply` (`200`, `206` for a range, `501` when the
|
||||
transfer could not run), `x-amz-rdma-bytes-transferred`. The HTTP body is
|
||||
empty; the reply is sent after the last transfer completed, so the client may
|
||||
read its buffer as soon as the response arrives. The server never needs the
|
||||
client to load the server's metadata.
|
||||
Reply headers on a completed RDMA transfer: `x-amz-rdma-reply` (`200` for a full object or upload, `206` for a ranged GET) and `x-amz-rdma-bytes-transferred` (omitted on a 0-byte GET). The HTTP response body is empty (`Content-Length: 0`) and is sent only after the last native transfer completed, so the client may read or reuse its buffer as soon as the response arrives. The server never needs the client to load the server's metadata.
|
||||
|
||||
Zero-length and fallback rules:
|
||||
- Zero-length buffer descriptors (`length = 0`) are rejected as malformed. To issue an RDMA GET of a 0-byte object, advertise at least a 1-byte registered window; the response carries `x-amz-rdma-reply` with `Content-Length: 0` and omits `x-amz-rdma-bytes-transferred`. Upload 0-byte objects with a normal HTTP PUT without RDMA headers.
|
||||
- When the service is disabled or a request carries malformed RDMA headers, `x-amz-rdma-reply` is omitted: a GET falls back to streaming the normal HTTP body, while an empty-body `PutObject` or `UploadPart` is processed as an ordinary 0-byte HTTP write. Clients that probe unknown endpoints or must avoid overwriting an existing key with 0 bytes on a declined request should stage writes through multipart `UploadPart` and call `CompleteMultipartUpload` only after verifying `x-amz-rdma-reply: 200` and `x-amz-rdma-bytes-transferred` on every part (the strategy used by `rc --data-transport auto|rdma`).
|
||||
- A GET whose resolved object or range length exceeds the advertised buffer length fails with `InvalidRange` (HTTP 416); native transfer failures surface as `InternalError` (HTTP 500).
|
||||
|
||||
## Device health check
|
||||
|
||||
@@ -203,9 +209,8 @@ across them; GPU clients register only their GPU's rail.
|
||||
reports its transfer complete, and the target verifies every word against
|
||||
its offset.
|
||||
|
||||
## Validation
|
||||
## Validation and observability
|
||||
|
||||
Check a transport change with a client that fetches an object into a
|
||||
zero-filled GPU or host buffer through this contract and compares it with a
|
||||
plain HTTP GET of the same object. Verify with a single round: later rounds
|
||||
rewrite the same bytes and mask a transfer that completed early.
|
||||
- Check a transport change with a client that fetches an object into a zero-filled GPU (`vram`) or host (`dram`) buffer through this contract and compares it byte-for-byte with a plain HTTP GET of the same object. Verify with a single round: repeated rounds into the same buffer can mask a transfer that completed early. For GPU buffers, GPUDirect RDMA works over kernel `dma-buf` with the open NVIDIA kernel modules (or `nvidia_peermem` on proprietary drivers) without requiring GPUs on the RustFS storage nodes.
|
||||
- From the companion `rustfs/cli` repository (`./scripts/build-rdma.sh --release`), validate end-to-end uploads, downloads, and `auto` fallback with `rc --data-transport rdma --rdma-backend nixl cp <src> <alias>/<bucket>/<key>` (or set `UCX_TLS=tcp,self` with `RUSTFS_NIXL_DEVICE_CHECK=false` for software loopback checks without RDMA hardware).
|
||||
- Structured log events report lifecycle and refusals under `cuobject_service_state` (`started`, `skipped`, `device_check`), `cuobject_get_rejected` (`token_malformed`), and `nixl_internode_read` (`refused`). Stage summaries record `s3_handler/rdma_transfer`, `cuobject_emit/write_zero_copy`, `cuobject_emit/write_staging`, `cuobject_emit/write_bytes`, `rdma_put_body_wait`, and `nixl_write_file_*`.
|
||||
|
||||
@@ -77,7 +77,7 @@
|
||||
|
||||
rustfs = rustPlatform.buildRustPackage {
|
||||
pname = "rustfs";
|
||||
version = "1.0.5";
|
||||
version = "1.0.8";
|
||||
|
||||
src = ./.;
|
||||
|
||||
|
||||
Generated
+37
-37
@@ -6247,7 +6247,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-checksums"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -6261,7 +6261,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-common"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"metrics",
|
||||
@@ -6275,7 +6275,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-concurrency"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"rustfs-io-core",
|
||||
"serde",
|
||||
@@ -6285,7 +6285,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-config"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"const-str",
|
||||
"serde",
|
||||
@@ -6294,7 +6294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-credentials"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"hmac 0.13.0",
|
||||
@@ -6307,7 +6307,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-crypto"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"argon2",
|
||||
@@ -6325,7 +6325,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-data-usage"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"hotpath",
|
||||
"rmp-serde",
|
||||
@@ -6335,7 +6335,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-ecstore"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-channel",
|
||||
@@ -6455,7 +6455,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-extension-schema"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"thiserror",
|
||||
@@ -6463,7 +6463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-filemeta"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"base64-simd",
|
||||
@@ -6561,7 +6561,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-heal-contracts"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"tokio",
|
||||
@@ -6570,7 +6570,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-io-core"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"rustfs-io-metrics",
|
||||
@@ -6581,7 +6581,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-io-metrics"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"metrics",
|
||||
"num_cpus",
|
||||
@@ -6642,7 +6642,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-kms"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"arc-swap",
|
||||
@@ -6680,7 +6680,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-lifecycle"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"hotpath",
|
||||
@@ -6697,7 +6697,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-lock"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"compact_str",
|
||||
@@ -6721,7 +6721,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-madmin"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"http",
|
||||
"humantime",
|
||||
@@ -6737,7 +6737,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-notify"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -6768,7 +6768,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-object-capacity"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"hotpath",
|
||||
@@ -6784,14 +6784,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-object-data-cache"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"sysinfo",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-policy"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64-simd",
|
||||
@@ -6816,7 +6816,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-protos"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"flatbuffers",
|
||||
"hyper-util",
|
||||
@@ -6839,7 +6839,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-replication"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"bytes",
|
||||
@@ -6856,7 +6856,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-rio"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"arc-swap",
|
||||
@@ -6890,7 +6890,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-client"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -6935,14 +6935,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-ops"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"rustfs-s3-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3-types"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
@@ -6956,7 +6956,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3select-api"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-compression",
|
||||
@@ -6997,7 +6997,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-s3select-query"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
@@ -7016,7 +7016,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-scanner-metrics"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"jiff 1.0.3",
|
||||
"metrics",
|
||||
@@ -7028,14 +7028,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-security-governance"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-signer"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"bytes",
|
||||
@@ -7051,7 +7051,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-sse"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
@@ -7071,7 +7071,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-storage-api"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"hotpath",
|
||||
@@ -7083,7 +7083,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-targets"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-nats",
|
||||
@@ -7132,7 +7132,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-tls-runtime"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"metrics",
|
||||
@@ -7161,7 +7161,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustfs-utils"
|
||||
version = "1.0.5"
|
||||
version = "1.0.8"
|
||||
dependencies = [
|
||||
"base64-simd",
|
||||
"blake2",
|
||||
|
||||
@@ -2,8 +2,8 @@ apiVersion: v2
|
||||
name: rustfs
|
||||
description: RustFS helm chart to deploy RustFS on kubernetes cluster.
|
||||
type: application
|
||||
version: "1.0.5"
|
||||
appVersion: "1.0.5"
|
||||
version: "1.0.8"
|
||||
appVersion: "1.0.8"
|
||||
home: https://rustfs.com
|
||||
icon: https://media.sys.truenas.net/apps/rustfs/icons/icon.svg
|
||||
maintainers:
|
||||
|
||||
+4
-1
@@ -1,7 +1,7 @@
|
||||
%global _enable_debug_packages 0
|
||||
%global _empty_manifest_terminate_build 0
|
||||
Name: rustfs
|
||||
Version: 1.0.5
|
||||
Version: 1.0.8
|
||||
Release: 1
|
||||
Summary: High-performance distributed object storage for MinIO alternative
|
||||
|
||||
@@ -57,6 +57,9 @@ install %_builddir/%{name}-%{version}/target/%_arch/%_arch-unknown-linux-gnu/rel
|
||||
%_bindir/rustfs
|
||||
|
||||
%changelog
|
||||
* Mon Nov 30 2026 RustFS Team <dev@rustfs.com>
|
||||
- Update RPM package to RustFS 1.0.8
|
||||
|
||||
* Wed Nov 11 2026 overtrue <anzhengchao@gmail.com>
|
||||
- Update RPM package to RustFS 1.0.5
|
||||
|
||||
|
||||
@@ -133,11 +133,42 @@ struct Observation {
|
||||
expected_nodes: usize,
|
||||
/// Completeness is only for this response. Pages are not a frozen cluster snapshot.
|
||||
page_complete: bool,
|
||||
#[serde(rename = "pending_count", skip_serializing_if = "Option::is_none")]
|
||||
pending_count: Option<usize>,
|
||||
#[serde(rename = "total_pending", skip_serializing_if = "Option::is_none")]
|
||||
total_pending: Option<usize>,
|
||||
#[serde(rename = "recreate_failed_loops", skip_serializing_if = "Option::is_none")]
|
||||
recreate_failed_loops: Option<u64>,
|
||||
#[serde(rename = "scanner_heal_executed", skip_serializing_if = "Option::is_none")]
|
||||
scanner_heal_executed: Option<u64>,
|
||||
#[serde(rename = "read_repair_executed", skip_serializing_if = "Option::is_none")]
|
||||
read_repair_executed: Option<u64>,
|
||||
nodes: Vec<NodeObservation>,
|
||||
next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
fn summarize_cluster_mrf(nodes: &[NodeObservation]) -> Option<(usize, u64, u64, u64)> {
|
||||
let mut saw_summary = false;
|
||||
let mut pending = 0usize;
|
||||
let mut recreate_failed_loops = 0u64;
|
||||
let mut scanner_heal_executed = 0u64;
|
||||
let mut read_repair_executed = 0u64;
|
||||
for node in nodes {
|
||||
if let Some(MrfReply::Summary { summary }) = &node.reply {
|
||||
saw_summary = true;
|
||||
pending = pending
|
||||
.saturating_add(summary.active_responsibility_count)
|
||||
.saturating_add(summary.best_effort_queue_depth);
|
||||
recreate_failed_loops = recreate_failed_loops.saturating_add(summary.recreate_failed_loops);
|
||||
scanner_heal_executed = scanner_heal_executed.saturating_add(summary.scanner_heal_executed);
|
||||
read_repair_executed = read_repair_executed.saturating_add(summary.read_repair_executed);
|
||||
}
|
||||
}
|
||||
saw_summary.then_some((pending, recreate_failed_loops, scanner_heal_executed, read_repair_executed))
|
||||
}
|
||||
|
||||
fn response(route: &Route, started: u64, nodes: Vec<NodeObservation>, next_cursor: Option<String>) -> S3Result<AdminResponse> {
|
||||
let summary_totals = summarize_cluster_mrf(&nodes);
|
||||
let observation = Observation {
|
||||
contract_version: 1,
|
||||
topology_fingerprint: route.fingerprint.clone(),
|
||||
@@ -145,6 +176,11 @@ fn response(route: &Route, started: u64, nodes: Vec<NodeObservation>, next_curso
|
||||
observation_finished_at_ms: mrf::now_ms(),
|
||||
expected_nodes: route.nodes.len(),
|
||||
page_complete: !nodes.is_empty() && nodes.iter().all(|node| node.state == "ok"),
|
||||
pending_count: summary_totals.map(|(pending, _, _, _)| pending),
|
||||
total_pending: summary_totals.map(|(pending, _, _, _)| pending),
|
||||
recreate_failed_loops: summary_totals.map(|(_, loops, _, _)| loops),
|
||||
scanner_heal_executed: summary_totals.map(|(_, _, scanner, _)| scanner),
|
||||
read_repair_executed: summary_totals.map(|(_, _, _, read_repair)| read_repair),
|
||||
nodes,
|
||||
next_cursor,
|
||||
};
|
||||
@@ -541,6 +577,9 @@ mod tests {
|
||||
operator_accepted_count: 0,
|
||||
best_effort_queue_depth: 0,
|
||||
responsibility_bytes: 128,
|
||||
scanner_heal_executed: 0,
|
||||
read_repair_executed: 0,
|
||||
recreate_failed_loops: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -984,4 +1023,37 @@ mod tests {
|
||||
let body = r#"{"nodeId":"node","actor":"root","request":{"action":"refresh","responsibilityId":"00000000-0000-4000-8000-000000000001"}}"#;
|
||||
assert!(serde_json::from_str::<RoutedAction>(body).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_observation_aggregates_pending_and_execution_counters() {
|
||||
let mut s1 = summary();
|
||||
s1.active_responsibility_count = 2;
|
||||
s1.best_effort_queue_depth = 1;
|
||||
s1.scanner_heal_executed = 5;
|
||||
s1.read_repair_executed = 3;
|
||||
s1.recreate_failed_loops = 0;
|
||||
|
||||
let mut s2 = summary();
|
||||
s2.active_responsibility_count = 1;
|
||||
s2.best_effort_queue_depth = 0;
|
||||
s2.scanner_heal_executed = 7;
|
||||
s2.read_repair_executed = 4;
|
||||
s2.recreate_failed_loops = 1;
|
||||
|
||||
let nodes = vec![
|
||||
NodeObservation {
|
||||
node_id: "n1".into(),
|
||||
host: "n1:9000".into(),
|
||||
state: "ok".into(),
|
||||
reply: Some(MrfReply::Summary { summary: s1 }),
|
||||
},
|
||||
NodeObservation {
|
||||
node_id: "n2".into(),
|
||||
host: "n2:9000".into(),
|
||||
state: "ok".into(),
|
||||
reply: Some(MrfReply::Summary { summary: s2 }),
|
||||
},
|
||||
];
|
||||
assert_eq!(summarize_cluster_mrf(&nodes), Some((4, 1, 12, 7)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,25 +229,30 @@ fn list_multipart_uploads_output(
|
||||
result: ListMultipartsInfo,
|
||||
encoding_type: Option<gateway_dto::EncodingType>,
|
||||
) -> rustfs_s3_types::S3Result<gateway_dto::ListMultipartUploadsOutput> {
|
||||
let owner = dto_values::owner();
|
||||
let initiator = gateway_dto::Initiator {
|
||||
id: owner.id.clone(),
|
||||
display_name: owner.display_name.clone(),
|
||||
};
|
||||
let uploads = result
|
||||
.uploads
|
||||
.into_iter()
|
||||
.map(|upload| {
|
||||
Ok(gateway_dto::MultipartUpload {
|
||||
key: Some(dto_values::stored_object_key(&upload.object)?),
|
||||
let mut uploads = Vec::with_capacity(result.uploads.len());
|
||||
if !result.uploads.is_empty() {
|
||||
let owner = dto_values::owner();
|
||||
let initiator = gateway_dto::Initiator {
|
||||
id: owner.id.clone(),
|
||||
display_name: owner.display_name.clone(),
|
||||
};
|
||||
for upload in result.uploads {
|
||||
let key = rustfs_gateway_types::ObjectKey::new(upload.object).map_err(|rejection| {
|
||||
rustfs_s3_types::S3Error::with_message(
|
||||
rustfs_s3_types::S3ErrorCode::InternalError,
|
||||
format!("a stored object key the gateway cannot represent: {rejection}"),
|
||||
)
|
||||
})?;
|
||||
uploads.push(gateway_dto::MultipartUpload {
|
||||
key: Some(key),
|
||||
upload_id: Some(upload.upload_id),
|
||||
initiated: upload.initiated.map(dto_values::timestamp),
|
||||
owner: Some(owner.clone()),
|
||||
initiator: Some(initiator.clone()),
|
||||
..Default::default()
|
||||
})
|
||||
})
|
||||
.collect::<rustfs_s3_types::S3Result<_>>()?;
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(gateway_dto::ListMultipartUploadsOutput {
|
||||
bucket: dto_values::stored_bucket_name(bucket)?,
|
||||
prefix: Some(prefix),
|
||||
|
||||
@@ -948,9 +948,9 @@ impl DefaultObjectUsecase {
|
||||
|
||||
// Phase 3 (serial): apply outcomes in the original request order so
|
||||
// per-key success/failure reporting is unchanged.
|
||||
let mut object_to_delete = Vec::new();
|
||||
let mut object_to_delete_idx = Vec::new();
|
||||
let mut object_versioning = Vec::new();
|
||||
let mut object_to_delete = Vec::with_capacity(pre_stat_deletes.len());
|
||||
let mut object_to_delete_idx = Vec::with_capacity(pre_stat_deletes.len());
|
||||
let mut object_versioning = Vec::with_capacity(pre_stat_deletes.len());
|
||||
for admitted in pre_stat_deletes {
|
||||
if let Some(error) = admitted.error {
|
||||
delete_results[admitted.idx].error = Some(project_delete_objects_pre_stat_error(
|
||||
@@ -965,11 +965,17 @@ impl DefaultObjectUsecase {
|
||||
object_to_delete.push(admitted.object);
|
||||
}
|
||||
let cache_adapter = self.object_data_cache();
|
||||
let cache_keys_before_delete = object_to_delete
|
||||
.iter()
|
||||
.map(|object| object.object_name.clone())
|
||||
.collect::<Vec<_>>();
|
||||
invalidate_object_data_cache_objects_before_mutation(&cache_adapter, &bucket, cache_keys_before_delete.iter()).await;
|
||||
fn object_to_delete_name(object: &ObjectToDelete) -> &String {
|
||||
&object.object_name
|
||||
}
|
||||
invalidate_object_data_cache_objects_before_mutation(
|
||||
&cache_adapter,
|
||||
&bucket,
|
||||
object_to_delete
|
||||
.iter()
|
||||
.map(object_to_delete_name as for<'a> fn(&'a ObjectToDelete) -> &'a String),
|
||||
)
|
||||
.await;
|
||||
|
||||
let mut storage_delete_opts = ObjectOptions {
|
||||
versioned: version_cfg.enabled(),
|
||||
@@ -1023,28 +1029,28 @@ impl DefaultObjectUsecase {
|
||||
return result;
|
||||
}
|
||||
|
||||
let mut committed_actions = HashSet::new();
|
||||
for (i, err) in errs.iter().enumerate() {
|
||||
debug_assert_eq!(dobjs.len(), errs.len());
|
||||
let mut committed_actions = HashSet::with_capacity(errs.len());
|
||||
for (i, (dobj, err)) in dobjs.into_iter().zip(errs.iter()).enumerate() {
|
||||
let didx = object_to_delete_idx[i];
|
||||
|
||||
match reduce_delete_objects_result(
|
||||
&object_to_delete[i],
|
||||
&dobjs[i],
|
||||
&dobj,
|
||||
err.as_ref(),
|
||||
delete_results[didx].synthetic_version_id,
|
||||
) {
|
||||
Ok(deleted_object) => {
|
||||
Ok(_) => {
|
||||
let (versioned, version_suspended) = object_versioning[i];
|
||||
delete_results[didx].delete_object = Some(deleted_object.clone());
|
||||
let committed_delete_marker = dobj.delete_marker;
|
||||
let action_identity = delete_objects_action_identity(&dobj, delete_results[didx].requested_version_id);
|
||||
delete_results[didx].delete_object = Some(dobj);
|
||||
delete_results[didx].version_suspended = version_suspended;
|
||||
if !committed_actions
|
||||
.insert(delete_objects_action_identity(deleted_object, delete_results[didx].requested_version_id))
|
||||
{
|
||||
if !committed_actions.insert(action_identity) {
|
||||
continue;
|
||||
}
|
||||
delete_results[didx].emit_side_effects = true;
|
||||
let creates_delete_marker = object_to_delete[i].version_id.is_none() && versioned && !version_suspended;
|
||||
let committed_delete_marker = dobjs[i].delete_marker;
|
||||
let delete_accounting = accounting.get(i).and_then(Option::as_ref);
|
||||
// `requested_version_id` distinguishes marker creation
|
||||
// (no version in the request) from marker removal by
|
||||
@@ -1144,9 +1150,10 @@ impl DefaultObjectUsecase {
|
||||
let _ = replication_task.await;
|
||||
}
|
||||
|
||||
let req_headers = envelope.headers().clone();
|
||||
let notify = current_notify_interface_for_context(self.context.as_deref());
|
||||
let req_params = rustfs_targets::extract_params_header(&req_headers);
|
||||
let req_params = rustfs_targets::extract_params_header(envelope.headers());
|
||||
let req_host = get_request_host(envelope.headers());
|
||||
let req_user_agent = get_request_user_agent(envelope.headers());
|
||||
let resp_elements = build_owned_event_resp_elements(&HeaderMap::new(), &request_context.request_id);
|
||||
let deleted_any = delete_results.iter().any(|result| result.delete_object.is_some());
|
||||
let delete_producers = delete_results
|
||||
@@ -1202,8 +1209,8 @@ impl DefaultObjectUsecase {
|
||||
.version_id(version_id.unwrap_or_default())
|
||||
.req_params(req_params.clone())
|
||||
.resp_elements(resp_elements.clone())
|
||||
.host(get_request_host(&req_headers))
|
||||
.user_agent(get_request_user_agent(&req_headers))
|
||||
.host(req_host.clone())
|
||||
.user_agent(req_user_agent.clone())
|
||||
.build();
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -357,9 +357,13 @@ impl fmt::Debug for AuthzFacts {
|
||||
/// age. POST Object forms are authenticated by form fields and drop any derived
|
||||
/// age in `authorization_conditions_with_internal`.
|
||||
pub(super) fn presigned_signature_age_millis(headers: &HeaderMap, raw_query: Option<&str>, now: OffsetDateTime) -> Option<i64> {
|
||||
let raw_query = raw_query?;
|
||||
if !raw_query.contains("X-Amz-Signature") && !raw_query.contains('%') {
|
||||
return None;
|
||||
}
|
||||
let mut is_presigned_v4 = false;
|
||||
let mut amz_dates = Vec::new();
|
||||
for (name, value) in form_urlencoded::parse(raw_query?.as_bytes()) {
|
||||
for (name, value) in form_urlencoded::parse(raw_query.as_bytes()) {
|
||||
match name.as_ref() {
|
||||
"Signature" => return None,
|
||||
"X-Amz-Signature" => is_presigned_v4 = true,
|
||||
@@ -418,6 +422,13 @@ pub(crate) fn list_query_pairs(raw_query: Option<&str>) -> Vec<(String, String)>
|
||||
let Some(raw_query) = raw_query else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !raw_query.contains("prefix")
|
||||
&& !raw_query.contains("delimiter")
|
||||
&& !raw_query.contains("max-keys")
|
||||
&& !raw_query.contains('%')
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
form_urlencoded::parse(raw_query.as_bytes())
|
||||
.filter(|(key, _)| LIST_QUERY_KEYS.contains(&key.as_ref()))
|
||||
.map(|(key, value)| (key.into_owned(), value.into_owned()))
|
||||
@@ -545,7 +556,7 @@ static NO_CLAIMS: LazyLock<HashMap<String, Value>> = LazyLock::new(HashMap::new)
|
||||
/// caller wants [`build_conditions`].
|
||||
pub(crate) fn base_conditions(principal: &AuthzPrincipal<'_>, facts: &AuthzFacts) -> HashMap<String, Vec<String>> {
|
||||
let headers = &facts.headers;
|
||||
let mut args = HashMap::new();
|
||||
let mut args = HashMap::with_capacity(headers.keys_len() + 12);
|
||||
|
||||
args.insert("CurrentTime".to_owned(), vec![facts.now.format(&Rfc3339).unwrap_or_default()]);
|
||||
args.insert("EpochTime".to_owned(), vec![facts.now.unix_timestamp().to_string()]);
|
||||
|
||||
@@ -929,6 +929,24 @@ fn absent_request_facts_leave_their_keys_absent() {
|
||||
fn listing_keys_ignore_other_actions_and_other_spellings() {
|
||||
let pairs = list_query_pairs(Some("Prefix=a&PREFIX=b&max_keys=1&delimiter%20=x&prefix=kept"));
|
||||
assert_eq!(pairs, vec![("prefix".to_owned(), "kept".to_owned())]);
|
||||
assert!(list_query_pairs(Some("partNumber=1&uploadId=abc")).is_empty());
|
||||
assert_eq!(
|
||||
list_query_pairs(Some("%70refix=encoded-key")),
|
||||
vec![("prefix".to_owned(), "encoded-key".to_owned())]
|
||||
);
|
||||
let now = OffsetDateTime::from_unix_timestamp(1_700_000_010).expect("valid timestamp");
|
||||
assert_eq!(
|
||||
super::presigned_signature_age_millis(&HeaderMap::new(), Some("partNumber=1&uploadId=abc"), now),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
super::presigned_signature_age_millis(
|
||||
&HeaderMap::new(),
|
||||
Some("X%2DAmz%2DSignature=deadbeef&X-Amz-Date=20231114T221320Z"),
|
||||
now
|
||||
),
|
||||
Some(10_000)
|
||||
);
|
||||
let mut conditions = HashMap::new();
|
||||
merge_list_query_conditions(Action::S3Action(S3Action::GetObjectAction), &pairs, &mut conditions);
|
||||
merge_list_query_conditions(Action::None, &pairs, &mut conditions);
|
||||
|
||||
@@ -649,7 +649,9 @@ pub async fn export_cpu_profile(
|
||||
)
|
||||
))]
|
||||
mod local_cpu {
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
use std::collections::HashSet;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
@@ -662,6 +664,7 @@ mod local_cpu {
|
||||
use super::{CpuProfileData, CpuProfileSample, ProfileCaptureRequest, ProfileError, check_cancel, hex_lower};
|
||||
|
||||
const SYMBOL_DOMAIN: &[u8] = b"rustfs-connect-cpu-symbol-v1\0";
|
||||
const REVIEWED_SYMBOL_DOMAIN: &[u8] = b"rustfs-connect-cpu-reviewed-symbol-v1\0";
|
||||
const MAX_SAMPLE_RATE_HZ: u32 = 100;
|
||||
const MAX_STACK_RECORDS: usize = 65_536;
|
||||
const MAX_SAMPLES: u64 = 65_536;
|
||||
@@ -669,9 +672,37 @@ mod local_cpu {
|
||||
const MAX_OUTPUT_SYMBOLS: usize = 256;
|
||||
const MAX_SYMBOL_BYTES: usize = 4_096;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
const MAX_CATALOG_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_CATALOG_BYTES: usize = 128 * 1024 * 1024;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
const MAX_CATALOG_SYMBOLS: usize = 200_000;
|
||||
const MAX_CATALOG_SYMBOLS: usize = 500_000;
|
||||
|
||||
/// Compact, bounded set of reviewed executable symbols represented as sorted SHA-256 digests
|
||||
/// (~8.6 MiB for 270k symbols instead of >100 MiB for retained strings), safe on 1 GiB nodes.
|
||||
struct ReviewedSymbolSet {
|
||||
digests: Vec<[u8; 32]>,
|
||||
}
|
||||
|
||||
impl ReviewedSymbolSet {
|
||||
fn digest(symbol: &str) -> [u8; 32] {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(REVIEWED_SYMBOL_DOMAIN);
|
||||
hasher.update(symbol.as_bytes());
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn from_symbols<'a>(symbols: impl IntoIterator<Item = &'a str>) -> Self {
|
||||
let mut digests: Vec<[u8; 32]> = symbols.into_iter().map(Self::digest).collect();
|
||||
digests.sort_unstable();
|
||||
digests.dedup();
|
||||
Self { digests }
|
||||
}
|
||||
|
||||
fn contains(&self, symbol: &str) -> bool {
|
||||
let target = Self::digest(symbol);
|
||||
self.digests.binary_search(&target).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn collect(
|
||||
request: &ProfileCaptureRequest,
|
||||
@@ -730,7 +761,7 @@ mod local_cpu {
|
||||
// The packaged Connect catalog is derived from this executable's ELF text symbols.
|
||||
// Match that exact symbol set before signing; shared-library and runtime frames
|
||||
// cannot be reviewed by a catalog bound to the RustFS executable alone.
|
||||
fn reviewed_executable_symbols(cancel: &CancellationToken) -> Result<Option<HashSet<String>>, ProfileError> {
|
||||
fn reviewed_executable_symbols(cancel: &CancellationToken) -> Result<Option<ReviewedSymbolSet>, ProfileError> {
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
{
|
||||
return load_executable_symbols(cancel).map(Some);
|
||||
@@ -743,7 +774,7 @@ mod local_cpu {
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
fn load_executable_symbols(cancel: &CancellationToken) -> Result<HashSet<String>, ProfileError> {
|
||||
fn load_executable_symbols(cancel: &CancellationToken) -> Result<ReviewedSymbolSet, ProfileError> {
|
||||
const MAX_EXECUTABLE_BYTES: u64 = 8_589_934_592;
|
||||
|
||||
check_cancel(cancel)?;
|
||||
@@ -758,7 +789,7 @@ mod local_cpu {
|
||||
if file.format() != object::BinaryFormat::Elf || file.symbol_table().is_none() {
|
||||
return Err(ProfileError::SourceUnavailable);
|
||||
}
|
||||
let mut symbols = HashSet::new();
|
||||
let mut seen: HashSet<[u8; 32]> = HashSet::new();
|
||||
let mut symbol_bytes = 0_usize;
|
||||
for (index, symbol) in file.symbols().chain(file.dynamic_symbols()).enumerate() {
|
||||
if index % 1_024 == 0 {
|
||||
@@ -767,22 +798,26 @@ mod local_cpu {
|
||||
if symbol.kind() != object::SymbolKind::Text || symbol.is_undefined() {
|
||||
continue;
|
||||
}
|
||||
if let Some(name) = symbol.name_bytes().ok().and_then(catalog_symbol_name)
|
||||
&& !symbols.contains(&name)
|
||||
{
|
||||
symbol_bytes = symbol_bytes
|
||||
.checked_add(name.len() + 3)
|
||||
.ok_or(ProfileError::SourceUnavailable)?;
|
||||
if symbol_bytes > MAX_CATALOG_BYTES || symbols.len() >= MAX_CATALOG_SYMBOLS {
|
||||
return Err(ProfileError::SourceUnavailable);
|
||||
if let Some(name) = symbol.name_bytes().ok().and_then(catalog_symbol_name) {
|
||||
let digest = ReviewedSymbolSet::digest(&name);
|
||||
if !seen.contains(&digest) {
|
||||
symbol_bytes = symbol_bytes
|
||||
.checked_add(name.len() + 3)
|
||||
.ok_or(ProfileError::SourceUnavailable)?;
|
||||
if symbol_bytes > MAX_CATALOG_BYTES || seen.len() >= MAX_CATALOG_SYMBOLS {
|
||||
return Err(ProfileError::SourceUnavailable);
|
||||
}
|
||||
seen.insert(digest);
|
||||
}
|
||||
symbols.insert(name);
|
||||
}
|
||||
}
|
||||
if symbols.is_empty() {
|
||||
if seen.is_empty() {
|
||||
return Err(ProfileError::SourceUnavailable);
|
||||
}
|
||||
Ok(symbols)
|
||||
let mut digests: Vec<[u8; 32]> = seen.into_iter().collect();
|
||||
digests.sort_unstable();
|
||||
digests.shrink_to_fit();
|
||||
Ok(ReviewedSymbolSet { digests })
|
||||
}
|
||||
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
@@ -800,7 +835,7 @@ mod local_cpu {
|
||||
|
||||
struct Accumulator<'a> {
|
||||
nonce: [u8; 32],
|
||||
reviewed_symbols: Option<&'a HashSet<String>>,
|
||||
reviewed_symbols: Option<&'a ReviewedSymbolSet>,
|
||||
samples: HashMap<String, u64>,
|
||||
stack_records: usize,
|
||||
accepted_sample_count: u64,
|
||||
@@ -808,7 +843,7 @@ mod local_cpu {
|
||||
}
|
||||
|
||||
impl<'a> Accumulator<'a> {
|
||||
fn new(nonce: [u8; 32], reviewed_symbols: Option<&'a HashSet<String>>) -> Self {
|
||||
fn new(nonce: [u8; 32], reviewed_symbols: Option<&'a ReviewedSymbolSet>) -> Self {
|
||||
Self {
|
||||
nonce,
|
||||
reviewed_symbols,
|
||||
@@ -955,7 +990,7 @@ mod local_cpu {
|
||||
|
||||
#[test]
|
||||
fn unreviewed_symbol_counts_are_dropped_without_exporting_their_ids() {
|
||||
let reviewed = HashSet::from(["rustfs::known".to_owned()]);
|
||||
let reviewed = ReviewedSymbolSet::from_symbols(["rustfs::known"]);
|
||||
let mut accumulator = Accumulator::new([4; 32], Some(&reviewed));
|
||||
accumulator
|
||||
.record_stack(["rustfs::known"].into_iter(), 3)
|
||||
|
||||
+221
-121
@@ -244,6 +244,7 @@ const EVENT_TLS_HANDSHAKE_FAILED: &str = "tls_handshake_failed";
|
||||
const EVENT_HTTP_TRANSPORT_CLOSED: &str = "http_transport_closed";
|
||||
const EVENT_HTTP_TRANSPORT_FAILED: &str = "http_transport_failed";
|
||||
const EVENT_SOCKET_FALLBACK: &str = "socket_fallback";
|
||||
const EVENT_SOCKET_OPTION_UNAVAILABLE: &str = "socket_option_unavailable";
|
||||
const EVENT_HTTP_BIND_FAILED: &str = "http_bind_failed";
|
||||
const EVENT_HTTP_STARTUP_ENDPOINTS: &str = "http_startup_endpoints";
|
||||
const EVENT_HTTP_COMPRESSION_STATE: &str = "http_compression_state";
|
||||
@@ -2025,102 +2026,12 @@ async fn start_http_server_inner(
|
||||
|
||||
// Common setup for both IPv4 and successful dual-stack IPv6
|
||||
let backlog = get_listen_backlog();
|
||||
let keepalive = get_default_tcp_keepalive();
|
||||
let recv_buffer_bytes = rustfs_utils::get_env_usize(
|
||||
rustfs_config::ENV_HTTP_SOCKET_RECV_BUFFER_BYTES,
|
||||
rustfs_config::DEFAULT_HTTP_SOCKET_RECV_BUFFER_BYTES,
|
||||
);
|
||||
|
||||
// Helper to configure socket with optimized parameters
|
||||
let configure_socket = |socket: &socket2::Socket| -> Result<()> {
|
||||
if let Err(e) = socket.set_reuse_address(true) {
|
||||
debug!(
|
||||
event = "socket_option_unavailable",
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "SO_REUSEADDR",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
// Set the socket to non-blocking before passing it to Tokio.
|
||||
socket.set_nonblocking(true)?;
|
||||
|
||||
// 1. Disable Nagle algorithm: Critical for 4KB Payload, achieving ultra-low latency
|
||||
if let Err(e) = socket.set_tcp_nodelay(true) {
|
||||
debug!(
|
||||
event = "socket_option_unavailable",
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "TCP_NODELAY",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Enable SO_REUSEPORT for better multi-core scalability on supported platforms
|
||||
#[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
|
||||
if let Err(e) = socket.set_reuse_port(true) {
|
||||
debug!(
|
||||
event = "socket_option_unavailable",
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "SO_REUSEPORT",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Set system-level TCP KeepAlive to protect long connections
|
||||
if let Err(e) = socket.set_tcp_keepalive(&keepalive) {
|
||||
debug!(
|
||||
event = "socket_option_unavailable",
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "TCP_KEEPALIVE",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
// 4. Socket buffers. The receive buffer is left to kernel autotuning
|
||||
// unless RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES is set: a fixed SO_RCVBUF
|
||||
// is inherited by every accepted socket and disables autotuning.
|
||||
// A reused autotuned connection can retain a buffer enlarged by a
|
||||
// previous request, so queued multipart bodies still consume kernel
|
||||
// memory. Neither policy makes socket capacity an allocation or
|
||||
// guarantees a fixed per-waiter memory footprint. Keep the existing
|
||||
// send-buffer tuning independent of receive autotuning.
|
||||
// Some constrained local environments reject these socket options with
|
||||
// EPERM/ENOPROTOOPT-style failures; log and continue in that case.
|
||||
if recv_buffer_bytes > 0
|
||||
&& let Err(e) = socket.set_recv_buffer_size(recv_buffer_bytes)
|
||||
{
|
||||
debug!(
|
||||
event = "socket_option_unavailable",
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "SO_RCVBUF",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
if let Err(e) = socket.set_send_buffer_size(4 * rustfs_config::MI_B) {
|
||||
debug!(
|
||||
event = "socket_option_unavailable",
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "SO_SNDBUF",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
};
|
||||
|
||||
configure_socket(&socket)?;
|
||||
configure_listener_socket(&socket, recv_buffer_bytes)?;
|
||||
|
||||
// Attempt bind; if bind fails for IPv6, try IPv4 fallback once more.
|
||||
if let Err(bind_err) = socket.bind(&server_addr.into()) {
|
||||
@@ -2137,7 +2048,7 @@ async fn start_http_server_inner(
|
||||
let ipv4_addr = SocketAddr::new(std::net::Ipv4Addr::UNSPECIFIED.into(), server_addr.port());
|
||||
server_addr = ipv4_addr;
|
||||
socket = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, Some(socket2::Protocol::TCP))?;
|
||||
configure_socket(&socket)?;
|
||||
configure_listener_socket(&socket, recv_buffer_bytes)?;
|
||||
socket.bind(&server_addr.into())?;
|
||||
socket.listen(backlog)?;
|
||||
} else {
|
||||
@@ -2712,35 +2623,7 @@ async fn start_http_server_inner(
|
||||
if !matches!(shutdown_rx.try_recv(), Err(tokio::sync::broadcast::error::TryRecvError::Empty)) {
|
||||
break;
|
||||
}
|
||||
#[allow(unused)]
|
||||
let socket_ref = SockRef::from(&socket);
|
||||
|
||||
// ── POST-ACCEPT SOCKET SYSCALLS ──
|
||||
// The listening socket already sets TCP_NODELAY, TCP_KEEPALIVE, and
|
||||
// SO_SNDBUF (SO_RCVBUF stays kernel-autotuned unless
|
||||
// RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES is set, see the listener
|
||||
// setup). On Linux/BSD, these are inherited by accepted sockets, so
|
||||
// we skip redundant re-application here.
|
||||
//
|
||||
// Only TCP_QUICKACK (Linux) is kept — it is inherently per-connection
|
||||
// and NOT inherited from the listening socket.
|
||||
//
|
||||
// T03 optimized: syscall count reduced from 5 → 1 (Linux) / 0 (other)
|
||||
|
||||
// Enable TCP QuickAck to reduce latency for small requests (Linux only)
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Err(err) = socket_ref.set_tcp_quickack(true) {
|
||||
debug!(?err, "Failed to set TCP_QUICKACK");
|
||||
}
|
||||
|
||||
// Debug-only: verify listening socket options were inherited
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
debug!(
|
||||
nodelay = socket_ref.tcp_nodelay().unwrap_or(false),
|
||||
"TCP_NODELAY inherited from listening socket"
|
||||
);
|
||||
}
|
||||
configure_accepted_socket(&socket);
|
||||
|
||||
let connection_ctx = ConnectionContext {
|
||||
http_server: http_server.clone(),
|
||||
@@ -3879,6 +3762,149 @@ fn get_listen_backlog() -> i32 {
|
||||
DEFAULT_BACKLOG
|
||||
}
|
||||
|
||||
fn configure_listener_socket(socket: &socket2::Socket, recv_buffer_bytes: usize) -> Result<()> {
|
||||
if let Err(e) = socket.set_reuse_address(true) {
|
||||
debug!(
|
||||
event = EVENT_SOCKET_OPTION_UNAVAILABLE,
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "SO_REUSEADDR",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
// Set the socket to non-blocking before passing it to Tokio.
|
||||
socket.set_nonblocking(true)?;
|
||||
|
||||
// 1. Disable Nagle algorithm: Critical for 4KB Payload, achieving ultra-low latency
|
||||
if let Err(e) = socket.set_tcp_nodelay(true) {
|
||||
debug!(
|
||||
event = EVENT_SOCKET_OPTION_UNAVAILABLE,
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "TCP_NODELAY",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Enable SO_REUSEPORT for better multi-core scalability on supported platforms
|
||||
#[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
|
||||
if let Err(e) = socket.set_reuse_port(true) {
|
||||
debug!(
|
||||
event = EVENT_SOCKET_OPTION_UNAVAILABLE,
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "SO_REUSEPORT",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Set system-level TCP KeepAlive to protect long connections.
|
||||
// On Apple/XNU platforms, setting TCP_KEEPALIVE on a listening socket triggers a kernel
|
||||
// bug in macOS < 14 (XNU < xnu-10002) where TCPT_KEEP is armed unconditionally without
|
||||
// checking TCPS_HAVEESTABLISHED and drops the listening socket to CLOSED after 60s.
|
||||
// XNU also does not inherit t_keepidle (TCP_KEEPALIVE) onto accepted sockets, so Apple
|
||||
// targets apply keepalive in configure_accepted_socket after accept().
|
||||
#[cfg(not(target_vendor = "apple"))]
|
||||
{
|
||||
let keepalive = get_default_tcp_keepalive();
|
||||
if let Err(e) = socket.set_tcp_keepalive(&keepalive) {
|
||||
debug!(
|
||||
event = EVENT_SOCKET_OPTION_UNAVAILABLE,
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "TCP_KEEPALIVE",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Socket buffers. The receive buffer is left to kernel autotuning
|
||||
// unless RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES is set: a fixed SO_RCVBUF
|
||||
// is inherited by every accepted socket and disables autotuning.
|
||||
// A reused autotuned connection can retain a buffer enlarged by a
|
||||
// previous request, so queued multipart bodies still consume kernel
|
||||
// memory. Neither policy makes socket capacity an allocation or
|
||||
// guarantees a fixed per-waiter memory footprint. Keep the existing
|
||||
// send-buffer tuning independent of receive autotuning.
|
||||
// Some constrained local environments reject these socket options with
|
||||
// EPERM/ENOPROTOOPT-style failures; log and continue in that case.
|
||||
if recv_buffer_bytes > 0
|
||||
&& let Err(e) = socket.set_recv_buffer_size(recv_buffer_bytes)
|
||||
{
|
||||
debug!(
|
||||
event = EVENT_SOCKET_OPTION_UNAVAILABLE,
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "SO_RCVBUF",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
if let Err(e) = socket.set_send_buffer_size(4 * rustfs_config::MI_B) {
|
||||
debug!(
|
||||
event = EVENT_SOCKET_OPTION_UNAVAILABLE,
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_STARTUP,
|
||||
option = "SO_SNDBUF",
|
||||
error = %e,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_accepted_socket(socket: &TcpStream) {
|
||||
#[allow(unused)]
|
||||
let socket_ref = SockRef::from(socket);
|
||||
|
||||
// ── POST-ACCEPT SOCKET SYSCALLS ──
|
||||
// The listening socket already sets TCP_NODELAY and SO_SNDBUF (SO_RCVBUF
|
||||
// stays kernel-autotuned unless RUSTFS_HTTP_SOCKET_RECV_BUFFER_BYTES is
|
||||
// set, see configure_listener_socket), and sets TCP_KEEPALIVE on non-Apple
|
||||
// platforms where accepted sockets inherit it.
|
||||
//
|
||||
// Apple/XNU targets apply TCP_KEEPALIVE here instead: pre-macOS-14 XNU
|
||||
// drops listening sockets to CLOSED when TCP_KEEPALIVE is set before
|
||||
// ESTABLISHED, and XNU never inherits t_keepidle onto accepted sockets.
|
||||
//
|
||||
// Linux also sets TCP_QUICKACK per connection because it is not inherited.
|
||||
#[cfg(target_vendor = "apple")]
|
||||
{
|
||||
let keepalive = get_default_tcp_keepalive();
|
||||
if let Err(err) = socket_ref.set_tcp_keepalive(&keepalive) {
|
||||
debug!(
|
||||
event = EVENT_SOCKET_OPTION_UNAVAILABLE,
|
||||
component = LOG_COMPONENT_SERVER,
|
||||
subsystem = LOG_SUBSYSTEM_TRANSPORT,
|
||||
option = "TCP_KEEPALIVE",
|
||||
error = %err,
|
||||
"Socket option is unavailable"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Enable TCP QuickAck to reduce latency for small requests (Linux only)
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Err(err) = socket_ref.set_tcp_quickack(true) {
|
||||
debug!(?err, "Failed to set TCP_QUICKACK");
|
||||
}
|
||||
|
||||
// Debug-only: verify listening socket options were inherited
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
debug!(
|
||||
nodelay = socket_ref.tcp_nodelay().unwrap_or(false),
|
||||
"TCP_NODELAY inherited from listening socket"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_default_tcp_keepalive() -> TcpKeepalive {
|
||||
#[cfg(target_os = "openbsd")]
|
||||
{
|
||||
@@ -10862,4 +10888,78 @@ mod tests {
|
||||
"external connection must still reject >20 pending-accept RST_STREAM bursts with GOAWAY(ENHANCE_YOUR_CALM)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_listener_socket_keepalive_policy() {
|
||||
let socket =
|
||||
socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, Some(socket2::Protocol::TCP)).expect("TCP socket");
|
||||
configure_listener_socket(&socket, 0).expect("configure listener socket");
|
||||
|
||||
#[cfg(target_vendor = "apple")]
|
||||
{
|
||||
assert!(
|
||||
!socket.keepalive().expect("read listener SO_KEEPALIVE"),
|
||||
"Apple listening sockets must not enable TCP keepalive before accept"
|
||||
);
|
||||
assert_ne!(
|
||||
socket.tcp_keepalive_time().expect("read listener TCP_KEEPALIVE"),
|
||||
Duration::from_secs(60),
|
||||
"Apple listening sockets must not set TCP_KEEPALIVE before accept (triggers XNU <14 60s listener drop)"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(target_vendor = "apple"))]
|
||||
{
|
||||
assert!(
|
||||
socket.keepalive().expect("read listener SO_KEEPALIVE"),
|
||||
"non-Apple listening sockets should keep SO_KEEPALIVE enabled for inheritance"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_accepted_socket_receives_tcp_keepalive() {
|
||||
let raw_listener =
|
||||
socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, Some(socket2::Protocol::TCP)).expect("TCP socket");
|
||||
configure_listener_socket(&raw_listener, 0).expect("configure listener socket");
|
||||
let bind_addr: SocketAddr = "127.0.0.1:0".parse().expect("loopback address");
|
||||
raw_listener.bind(&bind_addr.into()).expect("bind loopback listener");
|
||||
raw_listener.listen(16).expect("listen loopback listener");
|
||||
let listener = TcpListener::from_std(raw_listener.into()).expect("tokio listener");
|
||||
let addr = listener.local_addr().expect("listener address");
|
||||
|
||||
let connect_task = tokio::spawn(async move { TcpStream::connect(addr).await });
|
||||
let (accepted, _) = listener.accept().await.expect("accept loopback connection");
|
||||
let _client = connect_task
|
||||
.await
|
||||
.expect("connect task join")
|
||||
.expect("connect loopback client");
|
||||
|
||||
configure_accepted_socket(&accepted);
|
||||
let accepted_ref = SockRef::from(&accepted);
|
||||
|
||||
assert!(
|
||||
accepted_ref.keepalive().expect("read accepted SO_KEEPALIVE"),
|
||||
"accepted connection must have SO_KEEPALIVE enabled"
|
||||
);
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
{
|
||||
assert_eq!(
|
||||
accepted_ref.tcp_keepalive_time().expect("read accepted TCP_KEEPALIVE"),
|
||||
Duration::from_secs(60),
|
||||
"accepted connection must receive 60s TCP keepalive idle time"
|
||||
);
|
||||
assert_eq!(
|
||||
accepted_ref.tcp_keepalive_interval().expect("read accepted TCP_KEEPINTVL"),
|
||||
Duration::from_secs(5),
|
||||
"accepted connection must receive 5s TCP keepalive interval"
|
||||
);
|
||||
assert_eq!(
|
||||
accepted_ref.tcp_keepalive_retries().expect("read accepted TCP_KEEPCNT"),
|
||||
3,
|
||||
"accepted connection must receive 3 TCP keepalive retries"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+23
-13
@@ -29,7 +29,9 @@ use crate::shared_types::ReadinessDegradedReason;
|
||||
use crate::storage_api::server::layer::apply_cors_headers;
|
||||
#[cfg(feature = "diagnostic-local-batch")]
|
||||
use crate::storage_api::server::layer::batch_diagnostic;
|
||||
use crate::storage_api::server::layer::request_context::{RequestContext, extract_request_id_from_headers, spawn_traced};
|
||||
use crate::storage_api::server::layer::request_context::{
|
||||
RequestContext, extract_request_id_from_headers, in_propagated_request_id, spawn_traced,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures::future::{BoxFuture, Either};
|
||||
use http::{HeaderMap, HeaderValue, Method, Request as HttpRequest, Response, StatusCode, Uri};
|
||||
@@ -282,6 +284,8 @@ where
|
||||
} else {
|
||||
req.headers().get(REQUEST_ID_HEADER).cloned()
|
||||
};
|
||||
let propagated_request_id: Option<Arc<str>> =
|
||||
(!request_context.request_id.is_empty()).then(|| Arc::from(request_context.request_id.as_str()));
|
||||
#[cfg(feature = "diagnostic-local-batch")]
|
||||
let diagnostic_request = is_s3
|
||||
.then(|| batch_diagnostic::request_context(&request_context.request_id))
|
||||
@@ -304,20 +308,23 @@ where
|
||||
let head_request = req.method() == Method::HEAD;
|
||||
let mut metrics = is_s3.then(|| s3_http_request_guard(req.method().as_str()));
|
||||
#[cfg(feature = "diagnostic-local-batch")]
|
||||
let inner = batch_diagnostic::in_request_context(diagnostic_request.as_ref(), || match metrics.as_mut() {
|
||||
let inner = in_propagated_request_id(propagated_request_id.as_ref(), || {
|
||||
batch_diagnostic::in_request_context(diagnostic_request.as_ref(), || match metrics.as_mut() {
|
||||
Some(metrics) => metrics.in_scope(|| self.inner.call(req)),
|
||||
None => self.inner.call(req),
|
||||
})
|
||||
});
|
||||
#[cfg(not(feature = "diagnostic-local-batch"))]
|
||||
let inner = in_propagated_request_id(propagated_request_id.as_ref(), || match metrics.as_mut() {
|
||||
Some(metrics) => metrics.in_scope(|| self.inner.call(req)),
|
||||
None => self.inner.call(req),
|
||||
});
|
||||
#[cfg(not(feature = "diagnostic-local-batch"))]
|
||||
let inner = match metrics.as_mut() {
|
||||
Some(metrics) => metrics.in_scope(|| self.inner.call(req)),
|
||||
None => self.inner.call(req),
|
||||
};
|
||||
if let Some(feedback) = feedback.as_mut() {
|
||||
feedback.set_class(foreground_class(metrics.as_ref().and_then(S3HttpRequestGuard::operation)));
|
||||
}
|
||||
ExternalRequestContextFuture {
|
||||
inner,
|
||||
propagated_request_id,
|
||||
diagnostic_request,
|
||||
request_id,
|
||||
is_s3,
|
||||
@@ -368,6 +375,7 @@ pin_project! {
|
||||
pub struct ExternalRequestContextFuture<F> {
|
||||
#[pin]
|
||||
inner: F,
|
||||
propagated_request_id: Option<Arc<str>>,
|
||||
diagnostic_request: BatchDiagnosticRequest,
|
||||
request_id: Option<HeaderValue>,
|
||||
is_s3: bool,
|
||||
@@ -386,15 +394,17 @@ where
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.project();
|
||||
#[cfg(feature = "diagnostic-local-batch")]
|
||||
let result = batch_diagnostic::in_request_context(this.diagnostic_request.as_ref(), || match this.metrics.as_mut() {
|
||||
let result = in_propagated_request_id(this.propagated_request_id.as_ref(), || {
|
||||
batch_diagnostic::in_request_context(this.diagnostic_request.as_ref(), || match this.metrics.as_mut() {
|
||||
Some(metrics) => metrics.in_scope(|| this.inner.poll(cx)),
|
||||
None => this.inner.poll(cx),
|
||||
})
|
||||
});
|
||||
#[cfg(not(feature = "diagnostic-local-batch"))]
|
||||
let result = in_propagated_request_id(this.propagated_request_id.as_ref(), || match this.metrics.as_mut() {
|
||||
Some(metrics) => metrics.in_scope(|| this.inner.poll(cx)),
|
||||
None => this.inner.poll(cx),
|
||||
});
|
||||
#[cfg(not(feature = "diagnostic-local-batch"))]
|
||||
let result = match this.metrics.as_mut() {
|
||||
Some(metrics) => metrics.in_scope(|| this.inner.poll(cx)),
|
||||
None => this.inner.poll(cx),
|
||||
};
|
||||
if let Some(feedback) = this.feedback.as_mut() {
|
||||
feedback.set_class(foreground_class(this.metrics.as_ref().and_then(S3HttpRequestGuard::operation)));
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
use super::{
|
||||
ClusterHealthProbeKind, DependencyReadiness, DependencyReadinessReport, EndpointServerPools, StorageAdminApi,
|
||||
StorageWriteReadinessStatus, collect_peer_health_readiness, configured_readiness_topology,
|
||||
ClusterHealthProbeKind, DependencyReadiness, DependencyReadinessReport, DiskSetSelector, EndpointServerPools,
|
||||
StorageAdminApi, StorageWriteReadinessStatus, collect_peer_health_readiness, configured_readiness_topology,
|
||||
dependency_readiness_report_from_write_status, disk_is_online_for_readiness, exclusive_lock_quorum, is_dist_erasure,
|
||||
pool_metadata_write_readiness, pool_read_quorum, pool_write_quorum, runtime_sources,
|
||||
};
|
||||
@@ -85,6 +85,28 @@ pub(super) async fn collect_cluster_probe_report(kind: ClusterHealthProbeKind) -
|
||||
);
|
||||
};
|
||||
let backend = StorageAdminApi::backend_info(store.as_ref()).await;
|
||||
// Snapshot this node's own local RemoteDisk/LocalDisk health so a peer reporting its
|
||||
// local disks healthy cannot vote for read/write quorum while this node's own disk handle
|
||||
// is Offline/Faulty/Returning (backlog#3390 health-probe blind spot).
|
||||
let mut local_unavailable_slots: HashSet<DiskSlot> = HashSet::new();
|
||||
for (pool_idx, &set_count) in backend.total_sets.iter().enumerate() {
|
||||
let drive_count = backend.drives_per_set.get(pool_idx).copied().unwrap_or(0);
|
||||
for set_idx in 0..set_count {
|
||||
if let Ok(inventory) = store.disk_set_inventory(DiskSetSelector::new(pool_idx, set_idx)).await {
|
||||
for disk_idx in 0..drive_count {
|
||||
let locally_usable = inventory
|
||||
.get(disk_idx)
|
||||
.and_then(|slot| slot.as_ref())
|
||||
.is_some_and(|disk| !disk.is_faulty() && disk.runtime_state().as_str() == rustfs_madmin::ITEM_ONLINE);
|
||||
if !locally_usable
|
||||
&& let (Ok(p), Ok(s), Ok(d)) = (i32::try_from(pool_idx), i32::try_from(set_idx), i32::try_from(disk_idx))
|
||||
{
|
||||
local_unavailable_slots.insert((p, s, d));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let storage_probes = StorageProbes::new();
|
||||
storage_probes.push(
|
||||
async move {
|
||||
@@ -116,7 +138,11 @@ pub(super) async fn collect_cluster_probe_report(kind: ClusterHealthProbeKind) -
|
||||
}
|
||||
|
||||
let (storage_ready, lock_quorum_ready) = tokio::join!(
|
||||
async { metadata.ready && collect_storage_quorum(kind, backend, &endpoints, storage_probes).await },
|
||||
async {
|
||||
metadata.ready
|
||||
&& collect_storage_quorum_with_exclusions(kind, backend, &endpoints, storage_probes, &local_unavailable_slots)
|
||||
.await
|
||||
},
|
||||
collect_lock_quorum(&endpoints),
|
||||
);
|
||||
let readiness = DependencyReadiness {
|
||||
@@ -201,7 +227,11 @@ fn disk_slot(disk: &Disk) -> DiskSlot {
|
||||
(disk.pool_index, disk.set_index, disk.disk_index)
|
||||
}
|
||||
|
||||
fn accept_storage_observation(observation: StorageObservation, quorum: &mut StorageQuorum) {
|
||||
fn accept_storage_observation_with_exclusions(
|
||||
observation: StorageObservation,
|
||||
quorum: &mut StorageQuorum,
|
||||
local_unavailable_slots: &HashSet<DiskSlot>,
|
||||
) {
|
||||
let Some(info) = observation.info else {
|
||||
return;
|
||||
};
|
||||
@@ -220,12 +250,17 @@ fn accept_storage_observation(observation: StorageObservation, quorum: &mut Stor
|
||||
continue;
|
||||
}
|
||||
configured.observed = true;
|
||||
if disk_is_online_for_readiness(&disk) {
|
||||
if !local_unavailable_slots.contains(&slot) && disk_is_online_for_readiness(&disk) {
|
||||
count_quorum_vote(&mut quorum.votes_needed, &mut quorum.unsatisfied_sets, configured.set_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn accept_storage_observation(observation: StorageObservation, quorum: &mut StorageQuorum) {
|
||||
accept_storage_observation_with_exclusions(observation, quorum, &HashSet::new());
|
||||
}
|
||||
|
||||
fn count_quorum_vote(votes_needed: &mut [usize], unsatisfied_sets: &mut usize, set_index: usize) {
|
||||
let needed = &mut votes_needed[set_index];
|
||||
if *needed > 0 {
|
||||
@@ -236,17 +271,28 @@ fn count_quorum_vote(votes_needed: &mut [usize], unsatisfied_sets: &mut usize, s
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
async fn collect_storage_quorum(
|
||||
kind: ClusterHealthProbeKind,
|
||||
backend: BackendInfo,
|
||||
endpoints: &EndpointServerPools,
|
||||
probes: StorageProbes,
|
||||
) -> bool {
|
||||
collect_storage_quorum_with_exclusions(kind, backend, endpoints, probes, &HashSet::new()).await
|
||||
}
|
||||
|
||||
async fn collect_storage_quorum_with_exclusions(
|
||||
kind: ClusterHealthProbeKind,
|
||||
backend: BackendInfo,
|
||||
endpoints: &EndpointServerPools,
|
||||
mut probes: StorageProbes,
|
||||
local_unavailable_slots: &HashSet<DiskSlot>,
|
||||
) -> bool {
|
||||
let Some(mut quorum) = configured_storage_quorum(kind, backend, endpoints) else {
|
||||
return false;
|
||||
};
|
||||
while let Some(observation) = probes.next().await {
|
||||
accept_storage_observation(observation, &mut quorum);
|
||||
accept_storage_observation_with_exclusions(observation, &mut quorum, local_unavailable_slots);
|
||||
if quorum.unsatisfied_sets == 0 {
|
||||
return true;
|
||||
}
|
||||
@@ -766,4 +812,24 @@ mod tests {
|
||||
}
|
||||
assert!(collect_storage_quorum(ClusterHealthProbeKind::Write, backend, &endpoints, probes).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn locally_unavailable_remote_slots_do_not_vote_for_cluster_read_quorum() {
|
||||
let (backend, endpoints) = topology(&[(1, 16, 4)]);
|
||||
// 3 nodes report online locally (12/16 drives = read quorum), EXCEPT this node's own
|
||||
// RemoteDisk handles for node-2 (4 drives) are locally Returning/Faulty.
|
||||
let probes = ready_probes(&endpoints, &[0, 1, 2]);
|
||||
let excluded: HashSet<DiskSlot> = endpoints.as_ref()[0]
|
||||
.endpoints
|
||||
.as_ref()
|
||||
.iter()
|
||||
.filter(|ep| ep.host_port() == "node-2:9000")
|
||||
.map(|ep| (ep.pool_idx, ep.set_idx, ep.disk_idx))
|
||||
.collect();
|
||||
assert_eq!(excluded.len(), 4);
|
||||
assert!(
|
||||
!collect_storage_quorum_with_exclusions(ClusterHealthProbeKind::Read, backend, &endpoints, probes, &excluded).await,
|
||||
"peer local-online reports must not satisfy local read quorum when this node's RemoteDisk handles are unavailable"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,6 +356,10 @@ pub(crate) async fn authorize_request_with_location_constraint<R: AuthorizationR
|
||||
|
||||
/// The policy decision shared by every request edge. `internal_object_authorization`
|
||||
/// marks an exact-object check inside an already authorized table-catalog operation.
|
||||
/// Non-probe callers must have already hoisted allowlisted signed `x-amz-*` query
|
||||
/// parameters (via [`authorize_request`] or `prepare_owned_authorization`) before
|
||||
/// calling this function so [`can_take_owner_read_fast_path`] inspects the complete
|
||||
/// post-hoist header map.
|
||||
pub(crate) async fn authorize_request_core<R: AuthorizationRequest + ?Sized>(
|
||||
req: &mut R,
|
||||
action: Action,
|
||||
@@ -371,9 +375,10 @@ pub(crate) async fn authorize_request_core<R: AuthorizationRequest + ?Sized>(
|
||||
authorize_request_with_facts(req, &facts, internal_object_authorization).await
|
||||
}
|
||||
|
||||
/// Checks whether a root/owner object read can be decided from a single bucket metadata snapshot
|
||||
/// without building full policy facts/conditions (only when no bucket policy and no table bucket
|
||||
/// exist; any policy, table bucket, STS credential, probe, or error falls back to full evaluation).
|
||||
/// Checks whether a root/owner object read, multipart, or staged-part action can be decided
|
||||
/// from a single bucket metadata snapshot without building full policy facts/conditions (only
|
||||
/// when no bucket policy, no table bucket, and no table publication fence requirement exist;
|
||||
/// any policy, table bucket, STS credential, probe, or error falls back to full evaluation).
|
||||
fn can_take_owner_read_fast_path<R: AuthorizationRequest + ?Sized>(
|
||||
req: &R,
|
||||
action: Action,
|
||||
@@ -383,11 +388,34 @@ fn can_take_owner_read_fast_path<R: AuthorizationRequest + ?Sized>(
|
||||
if internal_object_authorization
|
||||
|| location_constraint.is_some()
|
||||
|| req.permission_probe()
|
||||
|| req.uri().query().is_some()
|
||||
|| !matches!(action, Action::S3Action(S3Action::GetObjectAction | S3Action::GetObjectVersionAction))
|
||||
|| req.requested_retention().is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let action_eligible = match action {
|
||||
Action::S3Action(
|
||||
S3Action::GetObjectAction
|
||||
| S3Action::GetObjectVersionAction
|
||||
| S3Action::GetObjectTaggingAction
|
||||
| S3Action::GetObjectVersionTaggingAction
|
||||
| S3Action::GetObjectAclAction
|
||||
| S3Action::GetObjectAttributesAction
|
||||
| S3Action::GetObjectVersionAttributesAction
|
||||
| S3Action::GetObjectRetentionAction
|
||||
| S3Action::GetObjectLegalHoldAction
|
||||
| S3Action::AbortMultipartUploadAction
|
||||
| S3Action::ListMultipartUploadPartsAction,
|
||||
) => !super::table_data_plane::table_data_plane_content_mutation(action),
|
||||
Action::S3Action(S3Action::PutObjectAction) => {
|
||||
req.staged_multipart_part()
|
||||
&& req.requested_object_tags().is_none()
|
||||
&& !req.policy_headers().contains_key("x-amz-tagging")
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if !action_eligible {
|
||||
return false;
|
||||
}
|
||||
let Some(req_info) = req.req_info() else {
|
||||
return false;
|
||||
};
|
||||
@@ -426,7 +454,6 @@ async fn try_owner_read_fast_path<R: AuthorizationRequest + ?Sized>(req: &R) ->
|
||||
}
|
||||
match store.get_bucket_authz_snapshot(bucket).await {
|
||||
Ok(snapshot) if !snapshot.has_policy && !snapshot.table_bucket_enabled => Ok(true),
|
||||
Err(StorageError::ConfigNotFound) => Ok(true),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
@@ -975,3 +1002,133 @@ pub(crate) async fn authorize_staged_multipart_part<R: AuthorizationRequest + ?S
|
||||
req.set_staged_multipart_part(false);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod owner_fast_path_tests {
|
||||
use super::{Action, AuthorizationRequest, S3Action, can_take_owner_read_fast_path};
|
||||
use crate::storage::authorization::tests::fixture::request;
|
||||
use crate::storage::req_info::ReqInfo;
|
||||
use crate::storage::request_markers::{RequestedObjectLockRetention, RequestedObjectTags};
|
||||
use http::{HeaderValue, Method};
|
||||
use rustfs_credentials::Credentials;
|
||||
|
||||
fn owner_req(bucket: &str, query: Option<&str>) -> crate::app::RequestEnvelope {
|
||||
let uri = match query {
|
||||
Some(q) => format!("/{bucket}/key?{q}"),
|
||||
None => format!("/{bucket}/key"),
|
||||
};
|
||||
request(Method::GET)
|
||||
.uri(&uri)
|
||||
.extension(ReqInfo {
|
||||
cred: Some(Credentials {
|
||||
access_key: "owner-key".to_owned(),
|
||||
..Default::default()
|
||||
}),
|
||||
is_owner: true,
|
||||
bucket: Some(bucket.to_owned()),
|
||||
object: Some("key".to_owned()),
|
||||
..Default::default()
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_fast_path_admits_query_reads_multipart_and_staged_parts_only_when_safe() {
|
||||
let req_with_query = owner_req("ordinary-bucket", Some("partNumber=1&uploadId=u1"));
|
||||
for action in [
|
||||
S3Action::GetObjectAction,
|
||||
S3Action::GetObjectVersionAction,
|
||||
S3Action::GetObjectTaggingAction,
|
||||
S3Action::GetObjectVersionTaggingAction,
|
||||
S3Action::GetObjectAclAction,
|
||||
S3Action::GetObjectAttributesAction,
|
||||
S3Action::GetObjectVersionAttributesAction,
|
||||
S3Action::GetObjectRetentionAction,
|
||||
S3Action::GetObjectLegalHoldAction,
|
||||
S3Action::AbortMultipartUploadAction,
|
||||
S3Action::ListMultipartUploadPartsAction,
|
||||
] {
|
||||
assert!(
|
||||
can_take_owner_read_fast_path(&req_with_query, Action::S3Action(action), None, false),
|
||||
"expected fast path for {action:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// Unstaged PutObject requires table-bucket publication fencing on non-lockless buckets.
|
||||
assert!(!can_take_owner_read_fast_path(
|
||||
&req_with_query,
|
||||
Action::S3Action(S3Action::PutObjectAction),
|
||||
None,
|
||||
false
|
||||
));
|
||||
|
||||
// Staged multipart part PutObject is eligible only when no x-amz-tagging header is present.
|
||||
let mut staged_req = owner_req("ordinary-bucket", Some("partNumber=1&uploadId=u1"));
|
||||
staged_req.set_staged_multipart_part(true);
|
||||
assert!(can_take_owner_read_fast_path(
|
||||
&staged_req,
|
||||
Action::S3Action(S3Action::PutObjectAction),
|
||||
None,
|
||||
false
|
||||
));
|
||||
staged_req
|
||||
.headers_mut()
|
||||
.insert("x-amz-tagging", HeaderValue::from_static("k=v"));
|
||||
assert!(!can_take_owner_read_fast_path(
|
||||
&staged_req,
|
||||
Action::S3Action(S3Action::PutObjectAction),
|
||||
None,
|
||||
false
|
||||
));
|
||||
|
||||
let mut tagged_staged_req = owner_req("ordinary-bucket", Some("partNumber=1&uploadId=u1"));
|
||||
tagged_staged_req.set_staged_multipart_part(true);
|
||||
tagged_staged_req.install_requested_object_tags(RequestedObjectTags(vec![("k".to_owned(), "v".to_owned())]));
|
||||
assert!(!can_take_owner_read_fast_path(
|
||||
&tagged_staged_req,
|
||||
Action::S3Action(S3Action::PutObjectAction),
|
||||
None,
|
||||
false
|
||||
));
|
||||
|
||||
let mut retention_req = owner_req("ordinary-bucket", None);
|
||||
retention_req.install_requested_retention(RequestedObjectLockRetention {
|
||||
mode: Some("GOVERNANCE".to_owned()),
|
||||
retain_until: None,
|
||||
});
|
||||
assert!(!can_take_owner_read_fast_path(
|
||||
&retention_req,
|
||||
Action::S3Action(S3Action::GetObjectAction),
|
||||
None,
|
||||
false
|
||||
));
|
||||
|
||||
// Reserved and S3 Vectors storage buckets must never take the owner fast path.
|
||||
let vector_bucket = format!("{}b1", crate::storage::storage_api::managed::BUCKET_VECTOR_STORAGE_PREFIX);
|
||||
for forbidden_bucket in [".rustfs.sys", ".minio.sys", vector_bucket.as_str()] {
|
||||
let mut forbidden = owner_req(forbidden_bucket, Some("partNumber=1&uploadId=u1"));
|
||||
for action in [
|
||||
S3Action::GetObjectAction,
|
||||
S3Action::GetObjectVersionAction,
|
||||
S3Action::GetObjectTaggingAction,
|
||||
S3Action::GetObjectVersionTaggingAction,
|
||||
S3Action::GetObjectAclAction,
|
||||
S3Action::GetObjectAttributesAction,
|
||||
S3Action::GetObjectVersionAttributesAction,
|
||||
S3Action::GetObjectRetentionAction,
|
||||
S3Action::GetObjectLegalHoldAction,
|
||||
S3Action::AbortMultipartUploadAction,
|
||||
S3Action::ListMultipartUploadPartsAction,
|
||||
] {
|
||||
assert!(!can_take_owner_read_fast_path(&forbidden, Action::S3Action(action), None, false));
|
||||
}
|
||||
forbidden.set_staged_multipart_part(true);
|
||||
assert!(!can_take_owner_read_fast_path(
|
||||
&forbidden,
|
||||
Action::S3Action(S3Action::PutObjectAction),
|
||||
None,
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -971,6 +971,12 @@ async fn handle_read_file(req: Request<Incoming>) -> Response<Body> {
|
||||
|
||||
let request_url = req.uri().to_string();
|
||||
let request_method = req.method().clone();
|
||||
let request_id = req
|
||||
.headers()
|
||||
.get(rustfs_utils::http::headers::REQUEST_ID_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or("-")
|
||||
.to_owned();
|
||||
let query = match parse_query::<ReadFileQuery>(&req) {
|
||||
Ok(query) => query,
|
||||
Err(response) => return *response,
|
||||
@@ -1003,6 +1009,7 @@ async fn handle_read_file(req: Request<Incoming>) -> Response<Body> {
|
||||
component = LOG_COMPONENT_INTERNODE_RPC,
|
||||
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
|
||||
operation = INTERNODE_OPERATION_READ_FILE_STREAM,
|
||||
request_id = %request_id,
|
||||
result = "rejected",
|
||||
status_code = StatusCode::BAD_REQUEST.as_u16(),
|
||||
rpc_path = req.uri().path(),
|
||||
@@ -1028,6 +1035,7 @@ async fn handle_read_file(req: Request<Incoming>) -> Response<Body> {
|
||||
component = LOG_COMPONENT_INTERNODE_RPC,
|
||||
subsystem = LOG_SUBSYSTEM_FILE_TRANSFER,
|
||||
operation = INTERNODE_OPERATION_READ_FILE_STREAM,
|
||||
request_id = %request_id,
|
||||
result = "failed",
|
||||
status_code = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
|
||||
rpc_path = req.uri().path(),
|
||||
|
||||
@@ -100,6 +100,106 @@ pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
|
||||
hex_simd::encode_to_string(Sha256::digest(bytes), hex_simd::AsciiCase::Lower)
|
||||
}
|
||||
|
||||
fn decode_sha256_hex(hex: &str) -> Option<[u8; 32]> {
|
||||
let bytes = hex_simd::decode_to_vec(hex.trim().as_bytes()).ok()?;
|
||||
<[u8; 32]>::try_from(bytes).ok()
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MetadataRefusal {
|
||||
status: StatusCode,
|
||||
reason: &'static str,
|
||||
detail: String,
|
||||
}
|
||||
|
||||
impl MetadataRefusal {
|
||||
fn into_response(self) -> Response<Body> {
|
||||
refuse(self.status, self.reason, self.detail)
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates that the request carries `x-rustfs-nixl-metadata` and that its raw
|
||||
/// bytes hash to the signed `nixl_md` query digest.
|
||||
fn extract_verified_metadata<'a>(
|
||||
headers: &'a http::HeaderMap,
|
||||
agent: &str,
|
||||
expected_md_hex: &str,
|
||||
) -> Result<(&'a str, [u8; 32]), MetadataRefusal> {
|
||||
let expected_digest = decode_sha256_hex(expected_md_hex).ok_or_else(|| MetadataRefusal {
|
||||
status: StatusCode::BAD_REQUEST,
|
||||
reason: "bad_metadata_digest",
|
||||
detail: agent.to_owned(),
|
||||
})?;
|
||||
let encoded = match headers.get(NIXL_METADATA_HEADER).map(HeaderValue::to_str) {
|
||||
Some(Ok(value)) if !value.trim().is_empty() => value,
|
||||
Some(Ok(_)) | None => {
|
||||
return Err(MetadataRefusal {
|
||||
status: StatusCode::BAD_REQUEST,
|
||||
reason: "missing_metadata_header",
|
||||
detail: agent.to_owned(),
|
||||
});
|
||||
}
|
||||
Some(Err(_)) => {
|
||||
return Err(MetadataRefusal {
|
||||
status: StatusCode::BAD_REQUEST,
|
||||
reason: "bad_metadata_header",
|
||||
detail: "not ascii".to_owned(),
|
||||
});
|
||||
}
|
||||
};
|
||||
let raw = base64_simd::STANDARD
|
||||
.decode_to_vec(encoded.trim())
|
||||
.map_err(|error| MetadataRefusal {
|
||||
status: StatusCode::BAD_REQUEST,
|
||||
reason: "bad_metadata_encoding",
|
||||
detail: error.to_string(),
|
||||
})?;
|
||||
let actual_digest: [u8; 32] = Sha256::digest(&raw).into();
|
||||
if actual_digest != expected_digest {
|
||||
return Err(MetadataRefusal {
|
||||
status: StatusCode::FORBIDDEN,
|
||||
reason: "metadata_digest_mismatch",
|
||||
detail: agent.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok((encoded, expected_digest))
|
||||
}
|
||||
|
||||
fn validate_segment_offset(append: bool, nixl_offset: Option<u64>) -> Result<(), u64> {
|
||||
if let Some(offset) = nixl_offset
|
||||
&& ((!append && offset != 0) || (append && offset == 0))
|
||||
{
|
||||
return Err(offset);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_final_write_size(
|
||||
append: bool,
|
||||
last: bool,
|
||||
declared_size: i64,
|
||||
nixl_offset: Option<u64>,
|
||||
written: u64,
|
||||
) -> Result<(), String> {
|
||||
let Ok(expected) = u64::try_from(declared_size) else {
|
||||
return Ok(());
|
||||
};
|
||||
let total_written = match nixl_offset {
|
||||
Some(offset) => offset
|
||||
.checked_add(written)
|
||||
.ok_or_else(|| format!("write offset {offset} + {written} overflowed"))?,
|
||||
None if !append => written,
|
||||
None => return Ok(()),
|
||||
};
|
||||
if last && total_written != expected {
|
||||
return Err(format!("expected {expected} bytes, received {total_written}"));
|
||||
}
|
||||
if !last && total_written > expected {
|
||||
return Err(format!("segment end {total_written} exceeds declared {expected} bytes"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_read_file_nixl(req: Request<Incoming>) -> Response<Body> {
|
||||
let query: NixlReadQuery = match serde_urlencoded::from_str(req.uri().query().unwrap_or_default()) {
|
||||
Ok(query) => query,
|
||||
@@ -109,23 +209,14 @@ pub(crate) async fn handle_read_file_nixl(req: Request<Incoming>) -> Response<Bo
|
||||
return reply(StatusCode::SERVICE_UNAVAILABLE, "nixl transport is not running on this node");
|
||||
};
|
||||
|
||||
// The metadata travels unsigned in a header; it must match the signed digest,
|
||||
// so a replayed request cannot point the transfer at another endpoint.
|
||||
let metadata = match req.headers().get(NIXL_METADATA_HEADER).map(HeaderValue::to_str) {
|
||||
Some(Ok(value)) => Some(value),
|
||||
Some(Err(_)) => return refuse(StatusCode::BAD_REQUEST, "bad_metadata_header", "not ascii"),
|
||||
None => None,
|
||||
// The metadata travels unsigned in a header; require it and bind it to the
|
||||
// signed digest so neither a replayed request nor a stripped header can
|
||||
// redirect the transfer to another endpoint or an S3 client registration.
|
||||
let (metadata, expected_digest) = match extract_verified_metadata(req.headers(), &query.nixl_agent, &query.nixl_md) {
|
||||
Ok(verified) => verified,
|
||||
Err(refusal) => return refusal.into_response(),
|
||||
};
|
||||
if let Some(encoded) = metadata {
|
||||
let raw = match base64_simd::STANDARD.decode_to_vec(encoded) {
|
||||
Ok(raw) => raw,
|
||||
Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_metadata_encoding", error),
|
||||
};
|
||||
if sha256_hex(&raw) != query.nixl_md.to_ascii_lowercase() {
|
||||
return refuse(StatusCode::FORBIDDEN, "metadata_digest_mismatch", &query.nixl_agent);
|
||||
}
|
||||
}
|
||||
let token = match RdmaToken::from_headers(&query.nixl_agent, metadata, &query.nixl_buffer) {
|
||||
let token = match RdmaToken::for_internode(&query.nixl_agent, metadata, expected_digest, &query.nixl_buffer) {
|
||||
Ok(token) => token,
|
||||
Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_nixl_token", error),
|
||||
};
|
||||
@@ -207,6 +298,8 @@ struct NixlWriteQuery {
|
||||
append: bool,
|
||||
size: i64,
|
||||
last: bool,
|
||||
#[serde(default)]
|
||||
nixl_offset: Option<u64>,
|
||||
nixl_nonce: uuid::Uuid,
|
||||
nixl_agent: String,
|
||||
nixl_buffers: String,
|
||||
@@ -222,6 +315,9 @@ pub(crate) async fn handle_write_file_nixl(req: Request<Incoming>) -> Response<B
|
||||
Ok(query) => query,
|
||||
Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_query", error),
|
||||
};
|
||||
if let Err(offset) = validate_segment_offset(query.append, query.nixl_offset) {
|
||||
return refuse(StatusCode::BAD_REQUEST, "bad_offset", offset);
|
||||
}
|
||||
if let Err(error) = check_and_record_signed_rpc_nonce(
|
||||
req.headers(),
|
||||
query.nixl_nonce,
|
||||
@@ -234,23 +330,13 @@ pub(crate) async fn handle_write_file_nixl(req: Request<Incoming>) -> Response<B
|
||||
let Some(server) = nixl_server() else {
|
||||
return reply(StatusCode::SERVICE_UNAVAILABLE, "nixl transport is not running on this node");
|
||||
};
|
||||
let metadata = match req.headers().get(NIXL_METADATA_HEADER).map(HeaderValue::to_str) {
|
||||
Some(Ok(value)) => Some(value),
|
||||
Some(Err(_)) => return refuse(StatusCode::BAD_REQUEST, "bad_metadata_header", "not ascii"),
|
||||
None => None,
|
||||
let (metadata, expected_digest) = match extract_verified_metadata(req.headers(), &query.nixl_agent, &query.nixl_md) {
|
||||
Ok(verified) => verified,
|
||||
Err(refusal) => return refusal.into_response(),
|
||||
};
|
||||
if let Some(encoded) = metadata {
|
||||
let raw = match base64_simd::STANDARD.decode_to_vec(encoded) {
|
||||
Ok(raw) => raw,
|
||||
Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_metadata_encoding", error),
|
||||
};
|
||||
if sha256_hex(&raw) != query.nixl_md.to_ascii_lowercase() {
|
||||
return refuse(StatusCode::FORBIDDEN, "metadata_digest_mismatch", &query.nixl_agent);
|
||||
}
|
||||
}
|
||||
let mut tokens = Vec::new();
|
||||
for descriptor in query.nixl_buffers.split(',').filter(|descriptor| !descriptor.is_empty()) {
|
||||
match RdmaToken::from_headers(&query.nixl_agent, metadata, descriptor) {
|
||||
match RdmaToken::for_internode(&query.nixl_agent, metadata, expected_digest, descriptor) {
|
||||
Ok(token) if token.buffer_len as usize <= server.chunk_bytes() => tokens.push(token),
|
||||
Ok(token) => return refuse(StatusCode::BAD_REQUEST, "buffer_too_large", token.buffer_len),
|
||||
Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_nixl_token", error),
|
||||
@@ -296,12 +382,8 @@ pub(crate) async fn handle_write_file_nixl(req: Request<Incoming>) -> Response<B
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from("nixl_write_file_write", write_started);
|
||||
written += len as u64;
|
||||
}
|
||||
if !query.append && query.last && query.size > 0 && written != query.size as u64 {
|
||||
return refuse(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"size_mismatch",
|
||||
format!("expected {} bytes, received {written}", query.size),
|
||||
);
|
||||
if let Err(detail) = validate_final_write_size(query.append, query.last, query.size, query.nixl_offset, written) {
|
||||
return refuse(StatusCode::INTERNAL_SERVER_ERROR, "size_mismatch", detail);
|
||||
}
|
||||
let finish_started = rustfs_io_metrics::put_stage_timer();
|
||||
if let Err(error) = finish_segment_file(&mut file).await {
|
||||
@@ -315,7 +397,11 @@ pub(crate) async fn handle_write_file_nixl(req: Request<Incoming>) -> Response<B
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::finish_segment_file;
|
||||
use super::{
|
||||
NIXL_METADATA_HEADER, extract_verified_metadata, finish_segment_file, sha256_hex, validate_final_write_size,
|
||||
validate_segment_offset,
|
||||
};
|
||||
use http::{HeaderMap, HeaderValue, StatusCode};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::io::{AsyncWrite, AsyncWriteExt};
|
||||
@@ -359,4 +445,57 @@ mod tests {
|
||||
finish_segment_file(&mut file).await.expect("finish");
|
||||
assert_eq!(file.written, data, "finishing the segment must write every byte");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_verification_rejects_stripped_or_mismatched_headers() {
|
||||
let raw = b"rustfs-peer-2:mlx5_0";
|
||||
let encoded = base64_simd::STANDARD.encode_to_string(raw);
|
||||
let valid_md = sha256_hex(raw);
|
||||
let other_md = sha256_hex(b"rustfs-peer-2:attacker");
|
||||
|
||||
let empty_headers = HeaderMap::new();
|
||||
let stripped = extract_verified_metadata(&empty_headers, "rustfs-peer-2", &valid_md)
|
||||
.expect_err("stripped metadata header must be rejected");
|
||||
assert_eq!(stripped.status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(stripped.reason, "missing_metadata_header");
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(NIXL_METADATA_HEADER, HeaderValue::from_str(&encoded).expect("header"));
|
||||
let bad_hex =
|
||||
extract_verified_metadata(&headers, "rustfs-peer-2", "not-sha256").expect_err("malformed digest must be rejected");
|
||||
assert_eq!(bad_hex.status, StatusCode::BAD_REQUEST);
|
||||
assert_eq!(bad_hex.reason, "bad_metadata_digest");
|
||||
|
||||
let mismatch =
|
||||
extract_verified_metadata(&headers, "rustfs-peer-2", &other_md).expect_err("digest mismatch must be forbidden");
|
||||
assert_eq!(mismatch.status, StatusCode::FORBIDDEN);
|
||||
assert_eq!(mismatch.reason, "metadata_digest_mismatch");
|
||||
|
||||
let (verified_header, digest) =
|
||||
extract_verified_metadata(&headers, "rustfs-peer-2", &valid_md).expect("matching metadata");
|
||||
assert_eq!(verified_header, encoded);
|
||||
assert_eq!(hex_simd::encode_to_string(digest, hex_simd::AsciiCase::Lower), valid_md);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_segment_bounds_verify_multi_segment_and_zero_byte_sizes() {
|
||||
assert!(validate_segment_offset(false, Some(0)).is_ok());
|
||||
assert!(validate_segment_offset(false, Some(8)).is_err());
|
||||
assert!(validate_segment_offset(true, Some(0)).is_err());
|
||||
assert!(validate_segment_offset(true, Some(32)).is_ok());
|
||||
|
||||
// Multi-segment shard write: 32 bytes in segment 0, 8 bytes in final segment 1.
|
||||
assert!(validate_final_write_size(false, false, 40, Some(0), 32).is_ok());
|
||||
assert!(validate_final_write_size(true, true, 40, Some(32), 8).is_ok());
|
||||
assert!(validate_final_write_size(true, true, 40, Some(32), 4).is_err());
|
||||
assert!(validate_final_write_size(false, false, 40, Some(0), 48).is_err());
|
||||
|
||||
// Zero-byte create must reject unexpected payload bytes.
|
||||
assert!(validate_final_write_size(false, true, 0, Some(0), 0).is_ok());
|
||||
assert!(validate_final_write_size(false, true, 0, Some(0), 4).is_err());
|
||||
assert!(validate_final_write_size(false, true, 0, None, 4).is_err());
|
||||
|
||||
// Legacy rolling-upgrade peer without nixl_offset still passes append segments.
|
||||
assert!(validate_final_write_size(true, true, 40, None, 8).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,6 +320,7 @@ pub(crate) mod request_context_consumer {
|
||||
pub(crate) use super::super::request_context::{
|
||||
RequestContext, extract_request_id_from_headers, spawn_traced, spawn_traced_join,
|
||||
};
|
||||
pub(crate) use rustfs_ecstore::api::rpc::in_propagated_request_id;
|
||||
}
|
||||
|
||||
pub(crate) mod rpc_consumer {
|
||||
|
||||
@@ -289,7 +289,7 @@ pub(crate) mod server {
|
||||
|
||||
pub(crate) mod request_context {
|
||||
pub(crate) use crate::storage::storage_api::request_context_consumer::{
|
||||
RequestContext, extract_request_id_from_headers, spawn_traced,
|
||||
RequestContext, extract_request_id_from_headers, in_propagated_request_id, spawn_traced,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user