Merge remote-tracking branch 'origin/main' into fix/replication-resync-walk-total-timeout

This commit is contained in:
唐小鸭
2026-11-30 11:10:12 +08:00
196 changed files with 24919 additions and 2524 deletions
+6 -6
View File
@@ -162,10 +162,10 @@ setup = 'ecstore-base-stack'
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
setup = 'lifecycle-large-stack'
# This conditional GET fixture composes real-store futures that overflowed
# the default Linux test-thread stack.
# These conditional GET and delete-marker fixtures overflowed the default
# Linux test-thread stack while composing real-store futures.
[[profile.default.scripts]]
filter = 'package(rustfs) & test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data)'
filter = 'package(rustfs) & (test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data) | test(=app::delete_objects_stat_gating_test::batch_delete_can_purge_an_explicit_delete_marker_version))'
setup = 'ecstore-large-stack'
# These heal fixtures compose deep real-store recovery futures that can
@@ -507,10 +507,10 @@ setup = 'ecstore-base-stack'
filter = 'binary(lifecycle_integration_test) | (package(rustfs) & test(/^app::lifecycle_transition_api_test::/))'
setup = 'lifecycle-large-stack'
# This conditional GET fixture composes real-store futures that overflowed
# the default Linux test-thread stack.
# These conditional GET and delete-marker fixtures overflowed the default
# Linux test-thread stack while composing real-store futures.
[[profile.ci.scripts]]
filter = 'package(rustfs) & test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data)'
filter = 'package(rustfs) & (test(=app::object::get::tests::conditional_get_304_uses_metadata_without_decoding_damaged_data) | test(=app::delete_objects_stat_gating_test::batch_delete_can_purge_an_explicit_delete_marker_version))'
setup = 'ecstore-large-stack'
# These heal fixtures compose deep real-store recovery futures that can
+1 -1
View File
@@ -113,7 +113,7 @@ jobs:
printf '%s\n' 'mode=full' >> "$GITHUB_OUTPUT"
echo "Base CI policy unavailable; running the full matrix."
fi
if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=11$' "$GITHUB_OUTPUT"; then
if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=12$' "$GITHUB_OUTPUT"; then
printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT"
echo "Base policy does not cover this workflow contract; retaining the full matrix."
fi
+4 -4
View File
@@ -221,9 +221,9 @@ jobs:
binary_root="fuzz/prebuilt/${CARGO_BUILD_TARGET}/release"
mkdir -p "${binary_root}"
# Keep this list in sync with fuzz/Cargo.toml, scripts/fuzz/run.sh,
# scripts/fuzz/select_targets.py, and the nightly matrix below (all 7
# scripts/fuzz/select_targets.py, and the nightly matrix below (all 13
# buildable bins). The *_storage_api.rs files are `mod` submodules.
for target in archive_extract bucket_validation local_metadata notify_xml path_containment policy_ingress sigv4_request; do
for target in archive_extract bucket_validation fuzz_bitrot_framing fuzz_filemeta_decode fuzz_iam_policy_eval fuzz_kms_envelope fuzz_s3_select_sql fuzz_s3_sigv4_and_xml local_metadata notify_xml path_containment policy_ingress sigv4_request; do
case ",${SELECTED_TARGETS_CSV}," in
*",${target},"*)
install -Dm755 "fuzz/target/${CARGO_BUILD_TARGET}/release/${target}" "${binary_root}/${target}"
@@ -352,7 +352,7 @@ jobs:
retention-days: 7
# ──────────────────────────────────────────────────────────────
# Phase 2 (Nightly): Run all 7 targets in parallel via matrix.
# Phase 2 (Nightly): Run all 13 targets in parallel via matrix.
# ──────────────────────────────────────────────────────────────
nightly-fuzz-corpus:
name: "Nightly / ${{ matrix.target }}"
@@ -368,7 +368,7 @@ jobs:
strategy:
fail-fast: false
matrix:
target: [archive_extract, bucket_validation, local_metadata, notify_xml, path_containment, policy_ingress, sigv4_request]
target: [archive_extract, bucket_validation, fuzz_bitrot_framing, fuzz_filemeta_decode, fuzz_iam_policy_eval, fuzz_kms_envelope, fuzz_s3_select_sql, fuzz_s3_sigv4_and_xml, local_metadata, notify_xml, path_containment, policy_ingress, sigv4_request]
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
CARGO_BUILD_TARGET: x86_64-unknown-linux-gnu
Generated
+781 -826
View File
File diff suppressed because it is too large Load Diff
+39 -32
View File
@@ -73,7 +73,12 @@ members = [
"crates/zip", # ZIP file handling and compression
"crates/zstd-compat", # Fixed codec for dependencies requiring zstd 0.13
]
exclude = ["vendor/hyper", "vendor/openidconnect"]
exclude = [
"vendor/hyper",
"vendor/openidconnect",
"vendor/rustfs-dst-faults",
"vendor/rustfs-dst-runtime",
]
resolver = "3"
[workspace.package]
@@ -151,25 +156,27 @@ rustfs-test-utils = { path = "crates/test-utils", version = "1.0.5" }
rustfs-tls-runtime = { path = "crates/tls-runtime", version = "1.0.5" }
rustfs-utils = { path = "crates/utils", version = "1.0.5" }
rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
rustfs-dst-runtime = { path = "vendor/rustfs-dst-runtime", default-features = false }
rustfs-dst-faults = { path = "vendor/rustfs-dst-faults", default-features = false }
# Pin the gateway and its protocol crates to the same revision.
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.44.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.2.0", default-features = false }
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.44.0", default-features = false }
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.2.0", default-features = false }
# The gateway framework itself, consumed for its extension traits by the ring-2
# adapter. `default-features = false` keeps the `server` feature, and with it the
# server crate, out of the build.
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.70.0", default-features = false }
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.70.0", default-features = false }
# Test-only: builds the `EffectiveHost` a host-resolution test queries with.
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.67.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "5ef262952e66308ef2c01dcee7c487f7497fe4fe", version = "0.15.0", default-features = false }
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", default-features = false }
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.67.0", default-features = false }
rustfs-gateway-corpus-recorder = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.1.0", default-features = false }
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "ac50e9af28fd1cbb2a643e3f047bff1d446b0919", version = "0.15.0", default-features = false }
# Async Runtime and Networking
async-channel = "2.5.0"
async_zip = { default-features = false, version = "0.0.19" }
mysql_async = { default-features = false, version = "0.37.1" }
async-compression = { version = "0.4.52" }
async-compression = { version = "0.4.54" }
async-trait = "0.1.92"
async-nats = { version = "0.53.0", default-features = false }
axum = "0.8.9"
@@ -180,8 +187,8 @@ futures-util = "0.3.34"
pollster = "1.0.3"
pulsar = { default-features = false, version = "=6.9.0" }
lapin = { default-features = false, version = "4.13.0" }
hyper = { version = "1.12.0" }
h2 = { version = "0.4.20" }
hyper = { version = "=1.12.0" } # Keep the HTTP/2 Expect backport below active.
h2 = { version = "0.4.21" }
hyper-rustls = { default-features = false, version = "0.27.10" }
hyper-util = { version = "0.1.21" }
http = "1.5.0"
@@ -253,7 +260,7 @@ rustls-native-certs = "0.8"
rustls-pki-types = "1.16.0"
x509-parser = "0.18.1"
sha1 = "0.11.0"
sha2 = "0.11.1"
sha2 = "0.11.2"
subtle = "2.6"
zeroize = { version = "1.9.2" }
proptest = "1"
@@ -261,7 +268,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.0.2" }
jiff = { version = "1.0.3" }
time = { version = "0.3.55" }
# Database
@@ -270,27 +277,27 @@ tokio-postgres = { default-features = false, version = "0.7.18" }
tokio-postgres-rustls = "0.14.0"
# Utilities and Tools
anyhow = "1.0.104"
anyhow = "1.0.105"
arc-swap = "1.9.5"
rustfs-tokio-tar = { version = "0.7.1" }
# Candidate Snowball parser versions exercised by rustfs-zip compatibility fixtures.
tar-codec = "0.0.16"
tar-framing = "0.0.16"
tar-codec = "0.0.17"
tar-framing = "0.0.17"
atoi = "3.1.1"
atomic_enum = "0.3.0"
aws-config = { version = "1.13.3" }
aws-config = { version = "1.13.4" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.133.0" }
aws-sdk-s3 = { default-features = false, version = "1.161.0" }
aws-sdk-sts = { default-features = false, version = "1.128.0" }
aws-sdk-kms = { default-features = false, version = "1.134.0" }
aws-sdk-s3 = { default-features = false, version = "1.162.0" }
aws-sdk-sts = { default-features = false, version = "1.129.0" }
aws-sdk-s3vectors = { default-features = false, version = "=1.49.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
aws-smithy-runtime-api = { version = "1.22.0" }
aws-smithy-types = { version = "1.9.4" }
aws-smithy-runtime-api = { version = "1.22.1" }
aws-smithy-types = { version = "1.9.5" }
base64-simd = "0.8.0"
brotli = "9.1.3"
clap = { version = "4.6.9" }
clap = { version = "4.6.10" }
const-str = { version = "1.1.0" }
convert_case = "0.12.0"
criterion = { version = "0.8" }
@@ -298,11 +305,11 @@ crossbeam-queue = "0.3.14"
crossbeam-channel = "0.5.17"
crossbeam-deque = "0.8.8"
crossbeam-utils = "0.8.23"
datafusion = { default-features = false, version = "55.3.0" }
datafusion = { default-features = false, version = "56.0.0" }
derive_builder = "0.20.2"
ed25519-dalek = "3.0.0"
enumset = "1.1.15"
faster-hex = "2.0.0"
faster-hex = "2.1.0"
flate2 = "1.1.11"
glob = "0.3.4"
google-cloud-storage = "1.22.0"
@@ -359,7 +366,7 @@ rustfs-erasure-codec = { version = "9.1.0" }
reed-solomon-simd = "3.1.0"
regex = { version = "1.13.2" }
rumqttc = { package = "rumqttc-next", version = "0.34.0" }
redis = { version = "1.8.2" }
redis = { version = "1.8.3" }
rustify = { version = "0.7", default-features = false }
rustix = { version = "1.1.6" }
rust-embed = { version = "8.14.0" }
@@ -395,8 +402,8 @@ winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
xxhash-rust = { version = "0.8.21" }
zip = "9.8.1"
zstd = "0.14.4"
zip = "9.9.0"
zstd = "0.14.5"
# Observability and Metrics
metrics = "0.24.6"
@@ -414,7 +421,7 @@ pyroscope = { version = "2.1.5" }
# FTP and SFTP
libunftp = { version = "0.25.1" }
unftp-core = "0.1.1"
suppaftp = { version = "13.0.0" }
suppaftp = { version = "13.1.0" }
rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] }
russh = { version = "0.65.4" }
russh-sftp = "4.0.0"
@@ -423,9 +430,9 @@ russh-sftp = "4.0.0"
dav-server = "0.12.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.4" }
# Preserve Unicode focus filters until rustfs/backlog#2302 is resolved.
hotpath = { version = "0.32.1", default-features = false }
rustfs-mimalloc = { version = "0.7.5" }
# Preserve method names in existing HOTPATH_FOCUS filters and reports.
hotpath = { version = "=0.32.1", default-features = false }
# Snapshot testing for output format regression detection
insta = { version = "1.49" }
@@ -15,6 +15,7 @@
use crate::common::{ClusterTopology, RustFSTestClusterEnvironment};
use aws_sdk_s3::Client;
use aws_sdk_s3::error::SdkError;
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
use bytes::Bytes;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -27,6 +28,7 @@ const KEY: &str = "thumb/79/concurrent-overwrite.jpg";
type TestResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
async fn assert_degraded_cluster_publication_guard_errors_are_retryable() -> TestResult {
const PART_BODY: &[u8] = b"multipart publication guard regression";
let mut cluster = RustFSTestClusterEnvironment::new(4).await?;
cluster.set_env("RUSTFS_STORAGE_CLASS_STANDARD", "EC:2");
cluster.set_env("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", "false");
@@ -48,6 +50,7 @@ async fn assert_degraded_cluster_publication_guard_errors_are_retryable() -> Tes
})
.collect();
let mut retained_uploads = Vec::new();
for alive in (1..=4).rev() {
if alive < 4 {
cluster.stop_node(alive)?;
@@ -89,13 +92,24 @@ async fn assert_degraded_cluster_publication_guard_errors_are_retryable() -> Tes
let upload_id = upload
.upload_id()
.expect("successful multipart initialization must return an upload ID");
client
let abort = client
.abort_multipart_upload()
.bucket(BUCKET)
.key(&multipart_key)
.upload_id(upload_id)
.send()
.await?;
.await;
if alive == 4 {
abort?;
} else {
// A native Abort needs a closure certificate from every original participant.
let err = abort.expect_err("an upload created with one node down cannot certify Abort");
let response = err.raw_response().expect("Abort must return an S3 response");
assert_eq!(response.status().as_u16(), 503);
assert_eq!(err.as_service_error().and_then(|error| error.meta().code()), Some("ServiceUnavailable"));
assert_eq!(response.headers().get("x-rustfs-error-cause"), Some("storage_write_quorum"));
retained_uploads.push((multipart_key, upload_id.to_owned()));
}
} else {
let err = multipart.expect_err("multipart initialization must reject writes without a write quorum");
assert_eq!(
@@ -114,7 +128,33 @@ async fn assert_degraded_cluster_publication_guard_errors_are_retryable() -> Tes
cluster.stop();
cluster.start().await?;
for (key, upload_id) in &retained_uploads {
let part = clients[0]
.upload_part()
.bucket(BUCKET)
.key(key)
.upload_id(upload_id)
.part_number(1)
.body(Bytes::from_static(PART_BODY).into())
.send()
.await?;
let part = CompletedPart::builder()
.part_number(1)
.e_tag(part.e_tag().expect("uploaded part must have an ETag"))
.build();
clients[0]
.complete_multipart_upload()
.bucket(BUCKET)
.key(key)
.upload_id(upload_id)
.multipart_upload(CompletedMultipartUpload::builder().parts(part).build())
.send()
.await?;
}
for client in &clients {
for (key, _) in &retained_uploads {
assert_quorum_object_body(client, BUCKET, key, PART_BODY).await?;
}
for alive in [1, 3, 4] {
for node in 0..alive {
let key = format!("publication-put-{alive}-{node}");
+7
View File
@@ -122,6 +122,11 @@ hotpath-cpu = [
# injection, xl.meta transition assertions) via `api::tier::test_util`.
# Enable only from `[dev-dependencies]` (rustfs/backlog#1148 ilm-6).
test-util = []
# Deterministic Simulation Testing backend (`DstSimDisk` over `SimDiskIo`).
# Off by default so production builds carry zero extra dependencies or branches.
dst = ["dep:rustfs-dst-runtime", "dep:rustfs-dst-faults"]
# Exposes internal bitrot/shard framing types to `fuzz/` targets only.
fuzzing = []
# Observes real startup CAS only in the dedicated E2E binary.
e2e-test-hooks = []
@@ -133,6 +138,8 @@ rustfs-filemeta.workspace = true
rustfs-utils = { workspace = true, features = ["full"] }
rustfs-rio.workspace = true
rustfs-rio-v2 = { workspace = true, optional = true }
rustfs-dst-runtime = { workspace = true, optional = true }
rustfs-dst-faults = { workspace = true, optional = true }
rustfs-storage-api.workspace = true
rustfs-config = { workspace = true, features = ["notify", "audit", "server-config-model"] }
rustfs-concurrency.workspace = true
+54 -33
View File
@@ -595,12 +595,13 @@ pub mod notification {
ScannerPublicationLeaseGrant, acquire_cross_pool_fence_fleet_proof, acquire_ilm_recovery_export_fleet_proof,
acquire_legacy_transition_state_reconcile_fleet_proof, acquire_mrf_lifecycle_writer_fleet_proof,
configured_fleet_topology_fingerprint, cross_pool_fence_fleet_proof_matches, get_global_notification_sys,
ilm_recovery_export_fleet_proof_matches, ilm_recovery_export_local_process_epoch,
ilm_recovery_export_member_epochs_sha256, ilm_recovery_export_topology_generation,
legacy_transition_state_reconcile_fleet_proof_matches, mrf_lifecycle_reader_local_process_epoch,
mrf_lifecycle_writer_fleet_proof_current, mrf_lifecycle_writer_fleet_proof_matches, new_global_notification_sys,
scanner_peer_transport_error_message_is_retryable, start_remote_version_state_fleet_probe,
with_mrf_lifecycle_writer_fleet_proof,
has_decommission_target_fence_fleet_proof, ilm_recovery_export_fleet_proof_matches,
ilm_recovery_export_local_process_epoch, ilm_recovery_export_member_epochs_sha256,
ilm_recovery_export_topology_generation, legacy_transition_state_reconcile_fleet_proof_matches,
mrf_lifecycle_reader_local_process_epoch, mrf_lifecycle_writer_fleet_proof_current,
mrf_lifecycle_writer_fleet_proof_matches, new_global_notification_sys, replace_global_notification_sys,
replace_remote_version_state_probe_topology, scanner_peer_transport_error_message_is_retryable,
start_remote_version_state_fleet_probe, trigger_fleet_capability_probe_refresh, with_mrf_lifecycle_writer_fleet_proof,
};
#[cfg(any(test, feature = "test-util"))]
pub use crate::services::notification_sys::{
@@ -709,29 +710,29 @@ pub mod rpc {
}
pub use crate::cluster::rpc::{
AuthenticatedChannel, KMS_SIGNAL_SUBSYSTEM, LocalPeerS3Client, MAX_NETWORK_PROBE_BYTES, MAX_NETWORK_PROBE_DURATION,
NetworkPeerProbeClient, NetworkPeerProbeError, NetworkPeerProbeMeasurement, NetworkPeerTarget, PEER_RESTDRY_RUN,
PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient, PeerS3Client, RpcReplayCacheAdmissionError, S3PeerSys,
SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerBucketListing, ScannerDirtyUsageAcknowledgement,
ScannerPeerActivity, ScannerPeerDirtyUsageBucket, ScannerPeerDirtyUsageSnapshot, ScannerPublicationLease,
ScannerScopedDirtyUsageAckEntry, StreamResponseAuthDomain, TONIC_RPC_PREFIX, TonicInterceptor,
build_put_file_auth_trailer, check_and_record_signed_rpc_nonce, check_and_record_signed_rpc_nonce_for_peer,
decode_heal_bucket_rpc_options, encode_heal_bucket_rpc_options, encode_stream_auth_data_frame,
encode_stream_auth_eof_frame, gen_signature_headers, gen_tonic_replay_scope_headers, gen_tonic_signature_headers,
gen_tonic_signature_interceptor, node_service_time_out_client, node_service_time_out_client_no_auth,
normalize_tonic_rpc_audience, rpc_auth_is_resource_exhausted, rpc_background_admission, set_tonic_canonical_body_digest,
sign_ns_scanner_capability, sign_ns_scanner_capability_with_checkpoint_coverage,
sign_ns_scanner_capability_with_durable_progress, sign_ns_scanner_capability_with_tier_registry_generation,
sign_ns_scanner_capability_with_usage_capabilities, sign_ns_scanner_tier_registry_preflight_capability,
sign_ns_scanner_usage_watch_capability, sign_put_file_capability, sign_tonic_rpc_response_proof,
tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers, tonic_boot_epoch_response_headers_with_msgpack_capability,
tonic_msgpack_manifest_capability_requested, tonic_rpc_auth_failure_reason, verify_ns_scanner_capability,
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_ns_scanner_tier_registry_preflight_capability, verify_ns_scanner_usage_watch_capability,
verify_put_file_auth_trailer, verify_put_file_capability, verify_rpc_signature, verify_stream_auth_data_frame,
verify_stream_auth_eof_frame, verify_tonic_boot_epoch_response, verify_tonic_canonical_body_digest,
verify_tonic_mutation_body_digest, verify_tonic_mutation_body_digest_reject_unsigned, verify_tonic_rpc_response_proof,
verify_tonic_rpc_signature, verify_tonic_rpc_signature_with_bootstrap,
NetworkPeerProbeClient, NetworkPeerProbeError, NetworkPeerProbeMeasurement, NetworkPeerTarget, PEER_REST_POOL_RELOAD_OP,
PEER_REST_POOL_RELOAD_PAYLOAD, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS, POOL_RELOAD_SIGNAL_SUBSYSTEM,
PeerRestClient, PeerS3Client, RpcReplayCacheAdmissionError, S3PeerSys, SERVICE_SIGNAL_REFRESH_CONFIG,
SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerBucketListing, ScannerDirtyUsageAcknowledgement, ScannerPeerActivity,
ScannerPeerDirtyUsageBucket, ScannerPeerDirtyUsageSnapshot, ScannerPublicationLease, ScannerScopedDirtyUsageAckEntry,
StreamResponseAuthDomain, TONIC_RPC_PREFIX, TonicInterceptor, build_put_file_auth_trailer,
check_and_record_signed_rpc_nonce, check_and_record_signed_rpc_nonce_for_peer, decode_heal_bucket_rpc_options,
encode_heal_bucket_rpc_options, encode_stream_auth_data_frame, encode_stream_auth_eof_frame, gen_signature_headers,
gen_tonic_replay_scope_headers, gen_tonic_signature_headers, gen_tonic_signature_interceptor,
node_service_time_out_client, node_service_time_out_client_no_auth, normalize_tonic_rpc_audience,
rpc_auth_is_resource_exhausted, rpc_background_admission, set_tonic_canonical_body_digest, sign_ns_scanner_capability,
sign_ns_scanner_capability_with_checkpoint_coverage, sign_ns_scanner_capability_with_durable_progress,
sign_ns_scanner_capability_with_tier_registry_generation, sign_ns_scanner_capability_with_usage_capabilities,
sign_ns_scanner_tier_registry_preflight_capability, sign_ns_scanner_usage_watch_capability, sign_put_file_capability,
sign_tonic_rpc_response_proof, tonic_boot_epoch_challenge, tonic_boot_epoch_response_headers,
tonic_boot_epoch_response_headers_with_msgpack_capability, tonic_msgpack_manifest_capability_requested,
tonic_rpc_auth_failure_reason, verify_ns_scanner_capability, 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_ns_scanner_tier_registry_preflight_capability,
verify_ns_scanner_usage_watch_capability, verify_put_file_auth_trailer, verify_put_file_capability, verify_rpc_signature,
verify_stream_auth_data_frame, verify_stream_auth_eof_frame, verify_tonic_boot_epoch_response,
verify_tonic_canonical_body_digest, verify_tonic_mutation_body_digest, verify_tonic_mutation_body_digest_reject_unsigned,
verify_tonic_rpc_response_proof, verify_tonic_rpc_signature, verify_tonic_rpc_signature_with_bootstrap,
verify_tonic_rpc_signature_with_bootstrap_and_peer,
};
}
@@ -778,10 +779,13 @@ pub mod storage {
#[cfg(feature = "internode-transport")]
pub use crate::store::external_rpc_disk;
pub use crate::store::{
BootstrapLocalTarget, ECStore, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, all_local_disk,
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc,
init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
prewarm_local_disk_id_map_with_instance_ctx,
BootstrapLocalTarget, CandidateDiskFormatState, CandidateDiskProbe, CandidateDiskProbeReport, DynamicECStoreHandle,
ECStore, PoolGeometrySummary, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, TopologyDiff,
TopologyReloadMode, TopologyReloadOutcome, TopologyTransitionKind, all_local_disk, all_local_disk_path,
analyze_topology_transition, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc,
find_local_disk_by_ref_for_scanner_rpc, init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients,
prewarm_local_disk_id_map, prewarm_local_disk_id_map_with_instance_ctx, refresh_local_disks_for_topology_reload,
refresh_lock_clients, summarize_endpoint_pools, summarize_pool_geometry,
};
pub use crate::store::{HealObjectAbsenceProof, HealObjectStorageResult};
}
@@ -836,3 +840,20 @@ pub mod tier {
};
}
}
#[cfg(feature = "dst")]
pub mod dst {
pub use crate::disk::dst_sim::{DstSimDisk, DstSimSetFixture, dst_object_options, make_dst_sim_set_disks};
pub use crate::disk::format::{DistributionAlgoVersion, FormatBackend, FormatErasureV3, FormatErasureVersion, FormatV3};
pub use crate::disk::{
CHECK_PART_DISK_NOT_FOUND, CHECK_PART_FILE_CORRUPT, CHECK_PART_FILE_NOT_FOUND, CHECK_PART_SUCCESS, CHECK_PART_UNKNOWN,
CHECK_PART_VOLUME_NOT_FOUND,
};
pub use crate::store::init_format::{load_format_erasure, save_format_file};
pub use rustfs_dst_faults::crash::{CrashPoint, CrashRegistry};
pub use rustfs_dst_runtime::{
disk::{CrashSemantics, DiskError as SimDiskError, DiskFaultConfig, DiskIo, SimDiskIo},
rng::{RngSource, SimRng},
};
pub use rustfs_heal_contracts::heal_channel::{DriveState, HealOpts, HealScanMode};
}
+28 -1
View File
@@ -55,10 +55,16 @@ fn consume_tokens<C: Clock>(limiter: &Ratelimiter<C>, n: u64) -> (u64, f64, u64)
pub struct BucketThrottle {
limiter: Arc<Mutex<Ratelimiter>>,
pub node_bandwidth_per_sec: i64,
pub cluster_limit_bytes_per_sec: i64,
}
impl BucketThrottle {
#[allow(dead_code)]
fn new(node_bandwidth_per_sec: i64) -> Result<Self, RatelimitError> {
Self::new_with_cluster_limit(node_bandwidth_per_sec, node_bandwidth_per_sec)
}
fn new_with_cluster_limit(node_bandwidth_per_sec: i64, cluster_limit_bytes_per_sec: i64) -> Result<Self, RatelimitError> {
let node_bandwidth_per_sec = node_bandwidth_per_sec.max(1);
let amount = node_bandwidth_per_sec as u64;
// ratelimit 2.0's builder takes a per-second rate; the refill period
@@ -67,6 +73,7 @@ impl BucketThrottle {
Ok(Self {
limiter: Arc::new(Mutex::new(limiter_inner)),
node_bandwidth_per_sec,
cluster_limit_bytes_per_sec,
})
}
@@ -359,7 +366,7 @@ impl Monitor {
name: bucket.to_string(),
replication_arn: arn.to_string(),
};
let throttle = match BucketThrottle::new(limit_bytes) {
let throttle = match BucketThrottle::new_with_cluster_limit(limit_bytes, limit) {
Ok(t) => t,
Err(e) => {
warn!(
@@ -381,6 +388,26 @@ impl Monitor {
.insert(opts, throttle);
}
/// Build a replacement monitor for an updated cluster node count while
/// preserving all configured per-bucket bandwidth limits.
pub fn with_inherited_limits(&self, num_nodes: u64) -> Arc<Self> {
let next = Self::new(num_nodes);
let configured: Vec<(BucketOptions, i64)> = self
.t_lock
.read()
.unwrap_or_else(|e| {
warn!("bucket monitor throttle rwlock read poisoned, recovering");
e.into_inner()
})
.iter()
.map(|(opts, throttle)| (opts.clone(), throttle.cluster_limit_bytes_per_sec))
.collect();
for (opts, cluster_limit) in configured {
next.set_bandwidth_limit(&opts.name, &opts.replication_arn, cluster_limit);
}
next
}
pub fn is_throttled(&self, bucket: &str, arn: &str) -> bool {
let opt = BucketOptions {
name: bucket.to_string(),
@@ -1267,7 +1267,8 @@ impl ExpiryState {
while state.tasks_tx.len() < n {
let (tx, rx) = mpsc::channel(EXPIRY_WORKER_QUEUE_CAPACITY);
let api = Arc::downgrade(&api);
let instance_ctx = api.ctx.clone();
let fallback_api = Arc::downgrade(&api);
let rx = Arc::new(tokio::sync::Mutex::new(rx));
let stats = Arc::clone(&state.stats);
let recovery_notify = Arc::clone(&state.recovery_notify);
@@ -1276,8 +1277,7 @@ impl ExpiryState {
state.stats.increment_workers();
tokio::spawn(async move {
let mut rx = rx.lock().await;
//let mut expiry_state = runtime_sources::expiry_state_handle().read().await;
ExpiryState::worker(&mut rx, api, stats, recovery_notify).await;
ExpiryState::worker_with_instance_ctx(&mut rx, Some(instance_ctx), fallback_api, stats, recovery_notify).await;
});
}
@@ -1293,20 +1293,31 @@ impl ExpiryState {
state.stats.record_scanner_expiry_state();
}
#[cfg(test)]
async fn worker(
rx: &mut Receiver<Option<ExpiryOpType>>,
api: Weak<ECStore>,
fallback_api: Weak<ECStore>,
stats: Arc<ExpiryStats>,
recovery_notify: Arc<Notify>,
) {
let Some(initial_api) = api.upgrade() else {
return;
};
let cancel_token = initial_api.ctx.background_cancel_token().unwrap_or_else(|| {
static FALLBACK: std::sync::OnceLock<tokio_util::sync::CancellationToken> = std::sync::OnceLock::new();
FALLBACK.get_or_init(tokio_util::sync::CancellationToken::new).clone()
});
drop(initial_api);
let instance_ctx = fallback_api.upgrade().map(|s| s.ctx.clone());
Self::worker_with_instance_ctx(rx, instance_ctx, fallback_api, stats, recovery_notify).await;
}
async fn worker_with_instance_ctx(
rx: &mut Receiver<Option<ExpiryOpType>>,
instance_ctx: Option<Arc<crate::runtime::instance::InstanceContext>>,
fallback_api: Weak<ECStore>,
stats: Arc<ExpiryStats>,
recovery_notify: Arc<Notify>,
) {
let cancel_token = instance_ctx
.as_ref()
.and_then(|ctx| ctx.background_cancel_token())
.unwrap_or_else(|| {
static FALLBACK: std::sync::OnceLock<tokio_util::sync::CancellationToken> = std::sync::OnceLock::new();
FALLBACK.get_or_init(tokio_util::sync::CancellationToken::new).clone()
});
loop {
select! {
@@ -1335,7 +1346,11 @@ impl ExpiryState {
let v = v.expect("received None after None check");
stats.decrement_pending_tasks();
let _active_task = ExpiryActiveTask::begin(Arc::clone(&stats));
let Some(api) = api.upgrade() else {
let Some(api) = instance_ctx
.as_ref()
.and_then(|ctx| ctx.live_store())
.or_else(|| fallback_api.upgrade())
else {
return;
};
if v.as_any().is::<ExpiryTask>() {
@@ -2140,7 +2155,11 @@ impl TransitionState {
Self::counter_value(&self.compensation_running_tasks)
}
async fn worker_with_cancel(api: Arc<ECStore>, cancel_token: CancellationToken) {
async fn worker_with_cancel(
instance_ctx: Arc<crate::runtime::instance::InstanceContext>,
fallback_api: Weak<ECStore>,
cancel_token: CancellationToken,
) {
let transition_state = runtime_sources::transition_state_handle();
loop {
select! {
@@ -2160,6 +2179,9 @@ impl TransitionState {
return;
}
let task = task.expect("received None after None check");
let Some(api) = instance_ctx.live_store().or_else(|| fallback_api.upgrade()) else {
return;
};
if task.as_any().is::<TransitionTask>() {
let task = task.as_any().downcast_ref::<TransitionTask>().expect("TransitionTask downcast failed");
@@ -2311,11 +2333,12 @@ impl TransitionState {
let previous_num_workers = workers.len() as i64;
while workers.len() < target {
let clone_api = api.clone();
let instance_ctx = api.ctx.clone();
let fallback_api = Arc::downgrade(&api);
let cancel = CancellationToken::new();
let worker_cancel = cancel.clone();
let handle = runtime.spawn(async move {
TransitionState::worker_with_cancel(clone_api, worker_cancel).await;
TransitionState::worker_with_cancel(instance_ctx, fallback_api, worker_cancel).await;
});
workers.push(TransitionWorker { cancel, handle });
}
@@ -3022,16 +3045,24 @@ fn spawn_tier_free_version_recovery_once_with_options(
}
Some(tokio::spawn(async move {
let cancel_token = api.ctx.background_cancel_token().unwrap_or_default();
let acquire_api = Arc::clone(&api);
let instance_ctx = api.ctx.clone();
let fallback_api = Arc::downgrade(&api);
drop(api);
let cancel_token = instance_ctx.background_cancel_token().unwrap_or_default();
let acquire_ctx = Arc::clone(&instance_ctx);
let acquire_fallback = fallback_api.clone();
let acquire_lock_name = Arc::<str>::from(leader_lock_name);
run_tier_free_version_recovery_coordinator(
cancel_token,
retry_delay,
move || {
let api = Arc::clone(&acquire_api);
let ctx = Arc::clone(&acquire_ctx);
let fallback = acquire_fallback.clone();
let lock_name = Arc::clone(&acquire_lock_name);
async move {
let Some(api) = ctx.live_store().or_else(|| fallback.upgrade()) else {
return Ok(None);
};
let lock = api.new_ns_lock(RUSTFS_META_BUCKET, &lock_name).await?;
match lock.get_write_lock_quiet(TIER_FREE_VERSION_RECOVERY_LOCK_TIMEOUT).await {
Ok(guard) => Ok(Some(guard)),
@@ -3041,15 +3072,24 @@ fn spawn_tier_free_version_recovery_once_with_options(
}
},
move |leader_cancel| {
let api = Arc::clone(&api);
let ctx = Arc::clone(&instance_ctx);
let fallback = fallback_api.clone();
async move {
run_tier_free_version_recovery_loop(
leader_cancel,
api.ctx.expiry_state(),
ctx.expiry_state(),
jitter_tier_free_version_recovery_delay,
move |bucket_marker, object_marker, recovery_cancel| {
let api = Arc::clone(&api);
let ctx = Arc::clone(&ctx);
let fallback = fallback.clone();
async move {
let Some(api) = ctx.live_store().or_else(|| fallback.upgrade()) else {
return Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"tier free-version recovery store dropped",
)
.into());
};
recover_configured_tier_free_versions(api, bucket_marker, object_marker, recovery_cancel).await
}
},
@@ -3981,7 +4021,8 @@ pub fn schedule_stale_multipart_upload_cleanup_once(api: Arc<ECStore>) {
pub fn init_background_stale_multipart_upload_cleanup(api: Arc<ECStore>) {
let cleanup_interval = stale_uploads_cleanup_interval();
let default_expiry = stale_uploads_expiry();
let api = Arc::downgrade(&api);
let instance_ctx = api.ctx.clone();
let fallback_api = Arc::downgrade(&api);
tokio::spawn(async move {
let mut interval = tokio::time::interval(cleanup_interval);
@@ -3989,7 +4030,7 @@ pub fn init_background_stale_multipart_upload_cleanup(api: Arc<ECStore>) {
loop {
interval.tick().await;
let Some(api) = Weak::upgrade(&api) else {
let Some(api) = instance_ctx.live_store().or_else(|| Weak::upgrade(&fallback_api)) else {
return;
};
@@ -578,6 +578,9 @@ pub(crate) async fn run_recovery_disposition_maintenance_pass(
}
pub(crate) async fn run_recovery_disposition_maintenance_loop(api: Arc<ECStore>, cancel_token: CancellationToken) {
let instance_ctx = api.ctx.clone();
let fallback_api = Arc::downgrade(&api);
drop(api);
let mut interval = tokio::time::interval(RECOVERY_DISPOSITION_MAINTENANCE_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut marker = None;
@@ -594,6 +597,9 @@ pub(crate) async fn run_recovery_disposition_maintenance_loop(api: Arc<ECStore>,
} else if cancel_token.is_cancelled() {
return;
}
let Some(api) = instance_ctx.live_store().or_else(|| fallback_api.upgrade()) else {
return;
};
let now_unix_nanos = match now_unix_nanos() {
Ok(now) => now,
Err(_) => {
@@ -6167,14 +6167,24 @@ async fn drive_tier_delete_journal_recovery(
pub async fn run_tier_delete_journal_recovery_loop(api: Arc<ECStore>, cancel_token: CancellationToken) {
let mut marker: Option<String> = None;
let mut manifest_marker: Option<String> = None;
let wake_context = api.ctx.clone();
let instance_ctx = api.ctx.clone();
let fallback_api = std::sync::Arc::downgrade(&api);
drop(api);
let wake_context = instance_ctx.clone();
let recovery_cancel_token = cancel_token.clone();
drive_tier_delete_journal_recovery(
&cancel_token,
async move || wake_context.wait_for_tier_delete_journal_recovery().await,
async move || {
let Some(api) = instance_ctx.live_store().or_else(|| fallback_api.upgrade()) else {
recovery_cancel_token.cancel();
return TierDeleteJournalRecoveryPassStats {
canceled: true,
..Default::default()
};
};
let stats = recover_tier_delete_journal_pass(
api.clone(),
api,
&recovery_cancel_token,
&mut manifest_marker,
&mut marker,
@@ -2118,6 +2118,9 @@ async fn recover_transition_transaction_records_with_now(
}
pub async fn run_transition_transaction_recovery_loop(api: Arc<ECStore>, cancel_token: CancellationToken) {
let instance_ctx = api.ctx.clone();
let fallback_api = std::sync::Arc::downgrade(&api);
drop(api);
let mut interval = tokio::time::interval(TRANSITION_TRANSACTION_RECOVERY_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut marker: Option<String> = None;
@@ -2129,8 +2132,10 @@ pub async fn run_transition_transaction_recovery_loop(api: Arc<ECStore>, cancel_
_ = interval.tick() => {},
}
let recovery =
recover_transition_transaction_records(api.clone(), DEFAULT_TRANSITION_TRANSACTION_RECOVERY_LIMIT, marker.clone());
let Some(api) = instance_ctx.live_store().or_else(|| fallback_api.upgrade()) else {
return;
};
let recovery = recover_transition_transaction_records(api, DEFAULT_TRANSITION_TRANSACTION_RECOVERY_LIMIT, marker.clone());
let Some(result) =
await_transition_transaction_recovery(&cancel_token, TRANSITION_TRANSACTION_RECOVERY_TIMEOUT, recovery).await
else {
+19 -8
View File
@@ -273,10 +273,11 @@ pub async fn init_bucket_metadata_sys(api: Arc<ECStore>, buckets: Vec<String>) {
let mut sys = BucketMetadataSys::new(api);
sys.init(buckets).await;
let store_cell = sys.store_handle();
let sys = Arc::new(RwLock::new(sys));
instance_ctx.init_bucket_metadata_sys(sys.clone());
instance_ctx.init_bucket_metadata_sys_with_store_cell(sys.clone(), store_cell);
if is_dist_erasure {
start_refresh_buckets_metadata_loop(sys);
@@ -2166,9 +2167,9 @@ pub(crate) fn needs_commit_metadata_snapshot(
&& !(opts.is_lockless_cache_write() && opts.quota_admission.is_none());
#[cfg(test)]
let base_required = base_required && opts.quota_admission.is_none();
#[cfg(any(test, feature = "test-util"))]
#[cfg(any(test, feature = "test-util", feature = "dst"))]
let base_required = base_required && ctx.bucket_metadata_sys().is_some();
#[cfg(not(any(test, feature = "test-util")))]
#[cfg(not(any(test, feature = "test-util", feature = "dst")))]
let _ = ctx;
base_required
}
@@ -2246,7 +2247,7 @@ pub(crate) async fn get_bucket_quota_limit_and_incarnation_in(
ctx: &crate::runtime::instance::InstanceContext,
bucket: &str,
) -> Result<Option<(u64, Option<Uuid>)>> {
#[cfg(any(test, feature = "test-util"))]
#[cfg(any(test, feature = "test-util", feature = "dst"))]
if ctx.bucket_metadata_sys().is_none() {
return Ok(None);
}
@@ -2568,7 +2569,7 @@ pub struct BucketMetadataSys {
/// Physically missing names are TTL-bounded to limit memory under bogus
/// name floods while avoiding repeated namespace and erasure reads.
missing_buckets: moka::future::Cache<String, ()>,
api: Weak<ECStore>,
api: Arc<std::sync::RwLock<Weak<ECStore>>>,
}
impl BucketMetadataSys {
@@ -2603,7 +2604,7 @@ impl BucketMetadataSys {
.max_capacity(MISSING_BUCKET_MAX_ENTRIES)
.time_to_live(MISSING_BUCKET_TTL)
.build(),
api: Arc::downgrade(&api),
api: Arc::new(std::sync::RwLock::new(Arc::downgrade(&api))),
}
}
@@ -2689,7 +2690,11 @@ impl BucketMetadataSys {
}
pub(crate) fn object_store_if_live(&self) -> Option<Arc<ECStore>> {
self.api.upgrade()
self.api.read().unwrap_or_else(|poisoned| poisoned.into_inner()).upgrade()
}
pub(crate) fn store_handle(&self) -> Arc<std::sync::RwLock<Weak<ECStore>>> {
Arc::clone(&self.api)
}
/// Whether the backing `ECStore` has been dropped.
@@ -2698,7 +2703,13 @@ impl BucketMetadataSys {
/// `ECStore::drop` so a shared bootstrap context does not retain a
/// `BucketMetadataSys` whose weak handle is dangling.
pub(crate) fn is_store_stale(&self) -> bool {
self.api.upgrade().is_none()
self.object_store_if_live().is_none()
}
/// Rebind this metadata system to a newly hot-reloaded `ECStore` generation
/// without blocking on outer async `BucketMetadataSys` read/write locks.
pub(crate) fn rebind_store(&self, api: Arc<ECStore>) {
*self.api.write().unwrap_or_else(|poisoned| poisoned.into_inner()) = Arc::downgrade(&api);
}
fn metadata_publish_lock(&self, bucket: &str) -> Arc<Mutex<MetadataPublishLockState>> {
@@ -852,7 +852,7 @@ pub(crate) async fn begin(
set_index: Some(set_index),
});
}
#[cfg(any(test, feature = "test-util"))]
#[cfg(any(test, feature = "test-util", feature = "dst"))]
if ctx.bucket_metadata_sys().is_none() {
return Ok(QuotaContext {
store: None,
+16 -3
View File
@@ -89,6 +89,7 @@ const RPC_RESPONSE_PROOF_DOMAIN: &[u8] = b"rustfs-rpc-response-proof-v1\0";
tokio::task_local! {
static RPC_BACKGROUND_REQUEST: bool;
static RPC_OMIT_LEGACY_SIGNATURE: bool;
}
pub(crate) fn current_rpc_background_request() -> bool {
@@ -97,6 +98,17 @@ pub(crate) fn current_rpc_background_request() -> bool {
.unwrap_or_else(|_| crate::disk::has_resource_io_scope())
}
pub(crate) fn current_rpc_omit_legacy_signature() -> bool {
RPC_OMIT_LEGACY_SIGNATURE.try_with(|omit| *omit).unwrap_or(false)
}
/// Execute `operation` while omitting the legacy unscoped v1 `x-rustfs-signature`
/// header from outbound gRPC metadata, ensuring candidate peer probes only send
/// audience-, method-, nonce-, and body-bound v2 signatures.
pub async fn with_v2_only_rpc_signing<F: std::future::Future>(operation: F) -> F::Output {
RPC_OMIT_LEGACY_SIGNATURE.scope(true, operation).await
}
/// Preserve the authenticated wire class while polling locally admitted work.
/// This scope carries only the class, never node, disk, or memory ownership.
pub async fn with_rpc_background_request<F: std::future::Future>(background: bool, operation: F) -> F::Output {
@@ -2111,7 +2123,6 @@ pub fn gen_tonic_signature_headers(
let body_nonce = (content_sha256 != UNSIGNED_PAYLOAD).then(|| Uuid::new_v4().to_string());
let nonce = body_nonce.as_deref().unwrap_or(UNSIGNED_PAYLOAD_NONCE);
let background = current_rpc_background_request();
let legacy_signature = generate_signature(&secret, TONIC_RPC_PREFIX, &Method::GET, timestamp, background);
let signature_v2 = generate_signature_v2(
&secret,
SignatureV2Scope {
@@ -2124,10 +2135,12 @@ pub fn gen_tonic_signature_headers(
content_sha256,
},
)?;
let mut headers = HeaderMap::new();
insert_background_admission(&mut headers, background);
headers.insert(SIGNATURE_HEADER, header_value(&legacy_signature, SIGNATURE_HEADER)?);
if !current_rpc_omit_legacy_signature() {
let legacy_signature = generate_signature(&secret, TONIC_RPC_PREFIX, &Method::GET, timestamp, background);
headers.insert(SIGNATURE_HEADER, header_value(&legacy_signature, SIGNATURE_HEADER)?);
}
headers.insert(TIMESTAMP_HEADER, header_value(&timestamp_header, TIMESTAMP_HEADER)?);
headers.insert(RPC_AUTH_VERSION_HEADER, HeaderValue::from_static(RPC_AUTH_VERSION_V2));
headers.insert(RPC_SIGNATURE_V2_HEADER, header_value(&signature_v2, RPC_SIGNATURE_V2_HEADER)?);
+4 -3
View File
@@ -65,9 +65,10 @@ pub use network_probe::{
};
pub(crate) use peer_rest_client::TierConfigReloadOutcome;
pub use peer_rest_client::{
KMS_SIGNAL_SUBSYSTEM, PEER_RESTDRY_RUN, PEER_RESTSIGNAL, PEER_RESTSUB_SYS, PeerRestClient, SERVICE_SIGNAL_REFRESH_CONFIG,
SERVICE_SIGNAL_RELOAD_DYNAMIC, ScannerDirtyUsageAcknowledgement, ScannerPeerActivity, ScannerPeerDirtyUsageBucket,
ScannerPeerDirtyUsageSnapshot, ScannerPublicationLease, ScannerScopedDirtyUsageAckEntry,
KMS_SIGNAL_SUBSYSTEM, PEER_REST_POOL_RELOAD_OP, PEER_REST_POOL_RELOAD_PAYLOAD, PEER_RESTDRY_RUN, PEER_RESTSIGNAL,
PEER_RESTSUB_SYS, POOL_RELOAD_SIGNAL_SUBSYSTEM, PeerRestClient, SERVICE_SIGNAL_REFRESH_CONFIG, SERVICE_SIGNAL_RELOAD_DYNAMIC,
ScannerDirtyUsageAcknowledgement, ScannerPeerActivity, ScannerPeerDirtyUsageBucket, ScannerPeerDirtyUsageSnapshot,
ScannerPublicationLease, ScannerScopedDirtyUsageAckEntry,
};
pub(crate) use peer_s3_client::heal_bucket_local_on_disks;
pub use peer_s3_client::{
@@ -88,6 +88,12 @@ pub const SERVICE_SIGNAL_RELOAD_DYNAMIC: u64 = 2;
/// config document, so it is not a `ServerConfig` subsystem; it only shares the
/// reload signal transport.
pub const KMS_SIGNAL_SUBSYSTEM: &str = "kms";
/// Dynamic signal subsystem for zero-downtime pool topology maintenance & hot-reload coordination.
pub const POOL_RELOAD_SIGNAL_SUBSYSTEM: &str = "pool_reload";
/// Signal variable key identifying the pool reload RPC operation (`probe`, `sync_maintenance`, `prepare`, `commit`, `abort`).
pub const PEER_REST_POOL_RELOAD_OP: &str = "pool-reload-op";
/// Signal variable key carrying the JSON request payload for pool reload coordination.
pub const PEER_REST_POOL_RELOAD_PAYLOAD: &str = "pool-reload-payload";
const BACKGROUND_HEAL_STATUS_MAX_MESSAGE_SIZE: usize = 64 * 1024;
const REPLACEMENT_RECOVERY_STATUS_MAX_MESSAGE_SIZE: usize = 64 * 1024;
const PEER_DRIVE_ADMISSION_MAX_MESSAGE_SIZE: usize = 256 * 1024;
@@ -181,7 +187,10 @@ fn validate_signal_service_protocol(sig: u64, sub_sys: &str, protocol_version: u
// Subsystems added after a peer was built are rejected by that peer's own
// subsystem allow-list, which surfaces as an explicit failed signal.
if sig == SERVICE_SIGNAL_RELOAD_DYNAMIC
&& matches!(sub_sys, SCANNER_SUB_SYS | HEAL_SUB_SYS | KMS_SIGNAL_SUBSYSTEM)
&& matches!(
sub_sys,
SCANNER_SUB_SYS | HEAL_SUB_SYS | KMS_SIGNAL_SUBSYSTEM | POOL_RELOAD_SIGNAL_SUBSYSTEM
)
&& protocol_version < rustfs_protos::DYNAMIC_CONFIG_PROTOCOL_VERSION
{
return Err(Error::other(format!("peer does not support dynamic {sub_sys} config convergence")));
@@ -2405,11 +2414,38 @@ impl PeerRestClient {
.map(|response| response.config_fingerprint)
}
/// Send an authenticated, body-bound pool topology maintenance / hot-reload
/// coordination signal (`probe`, `sync_maintenance`, `prepare`, `commit`, `abort`)
/// to this peer and return its optional JSON response payload.
pub async fn pool_reload_signal(&self, op: &str, payload_json: &str, dry_run: bool) -> Result<Option<String>> {
let mut extra_vars = HashMap::new();
extra_vars.insert(PEER_REST_POOL_RELOAD_OP.to_string(), op.to_string());
extra_vars.insert(PEER_REST_POOL_RELOAD_PAYLOAD.to_string(), payload_json.to_string());
super::http_auth::with_v2_only_rpc_signing(self.signal_service_checked_with_vars(
SERVICE_SIGNAL_RELOAD_DYNAMIC,
POOL_RELOAD_SIGNAL_SUBSYSTEM,
dry_run,
extra_vars,
))
.await
.map(|response| response.config_fingerprint)
}
async fn signal_service_checked(&self, sig: u64, sub_sys: &str, dry_run: bool) -> Result<SignalServiceResponse> {
self.signal_service_checked_with_vars(sig, sub_sys, dry_run, HashMap::new())
.await
}
async fn signal_service_checked_with_vars(
&self,
sig: u64,
sub_sys: &str,
dry_run: bool,
mut vars: HashMap<String, String>,
) -> Result<SignalServiceResponse> {
self.finalize_result(
async {
let mut client = self.get_client().await?;
let mut vars = HashMap::new();
vars.insert(PEER_RESTSIGNAL.to_string(), sig.to_string());
vars.insert(PEER_RESTSUB_SYS.to_string(), sub_sys.to_string());
vars.insert(PEER_RESTDRY_RUN.to_string(), dry_run.to_string());
@@ -1086,6 +1086,12 @@ pub struct RemotePeerS3Client {
cancel_token: CancellationToken,
}
impl Drop for RemotePeerS3Client {
fn drop(&mut self) {
self.cancel_token.cancel();
}
}
impl RemotePeerS3Client {
fn encode_delete_bucket_options(opts: &DeleteBucketOptions) -> Result<String> {
let mut remote_opts = opts.clone();
+12 -3
View File
@@ -339,7 +339,7 @@ fn attach_quota_mutation_body_digest<T>(
let topology = crate::services::notification_sys::configured_fleet_topology_fingerprint()
.ok_or_else(|| Error::other("quota mutation topology is not initialized or conflicts with startup"))?;
let body = canonical_body.map_err(|_| Error::other("quota request length cannot be represented"))?;
let body = rustfs_protos::canonical_quota_mutation_request_body(topology, &body)
let body = rustfs_protos::canonical_quota_mutation_request_body(&topology, &body)
.map_err(|_| Error::other("quota topology envelope length cannot be represented"))?;
request.metadata_mut().insert(
rustfs_protos::QUOTA_MUTATION_TOPOLOGY_HEADER,
@@ -1026,6 +1026,8 @@ pub struct RemoteDisk {
pub scanning: Arc<AtomicU32>,
/// Whether health checking is enabled
health_check: bool,
/// Ensures `enable_health_check` spawns at most one active monitor per handle
health_monitor_started: AtomicBool,
/// Health tracker for connection monitoring
health: Arc<DiskHealthTracker>,
/// Cancellation token for monitoring tasks
@@ -1049,6 +1051,12 @@ pub struct RemoteDisk {
rename_admission: Option<Arc<Semaphore>>,
}
impl Drop for RemoteDisk {
fn drop(&mut self) {
self.cancel_token.cancel();
}
}
/// Shortest gap between two failure warnings of one kind from one remote disk.
const REMOTE_DISK_RPC_FAILURE_LOG_INTERVAL_MS: u64 = 5_000;
const BULK_BODY_ADMISSION_REGISTRY_CAPACITY: usize = 512;
@@ -1840,6 +1848,7 @@ impl RemoteDisk {
endpoint: ep.clone(),
scanning: Arc::new(AtomicU32::new(0)),
health_check: opt.health_check && env_health_check,
health_monitor_started: AtomicBool::new(false),
health: Arc::new(DiskHealthTracker::new()),
cancel_token: CancellationToken::new(),
recovery_monitor_active: Arc::new(AtomicBool::new(false)),
@@ -2185,7 +2194,7 @@ impl RemoteDisk {
/// Used to defer health checks until after startup format loading completes,
/// so that remote peers have time to come online.
pub fn enable_health_check(&self) {
if !self.health_check {
if !self.health_check || self.health_monitor_started.swap(true, Ordering::AcqRel) {
return;
}
let health = Arc::clone(&self.health);
@@ -14744,7 +14753,7 @@ mod tests {
async fn remote_disk_builds_optional_complete_body_gate_from_configuration() {
temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, Some("3"))], async {
let disk = remote_disk_for_addr("http://127.0.0.1:59996").await;
let gate = disk.bulk_body_admission.expect("configured body gate");
let gate = disk.bulk_body_admission.clone().expect("configured body gate");
assert_eq!(gate.available_permits(), 3);
})
.await;
+16
View File
@@ -368,6 +368,22 @@ pub fn lookup_config_for_pools(kvs: &KVS, set_drive_counts: &[usize]) -> Result<
lookup_config_for_pools_with_env(kvs, set_drive_counts, StorageClassEnvOverrides::from_process()?)
}
pub fn lookup_config_for_pools_with_overrides(
kvs: &KVS,
set_drive_counts: &[usize],
standard_override: Option<String>,
rrs_override: Option<String>,
) -> Result<Config> {
let mut overrides = StorageClassEnvOverrides::from_process()?;
if standard_override.is_some() {
overrides.standard = standard_override;
}
if rrs_override.is_some() {
overrides.rrs = rrs_override;
}
lookup_config_for_pools_with_env(kvs, set_drive_counts, overrides)
}
fn lookup_config_for_pools_with_env(
kvs: &KVS,
set_drive_counts: &[usize],
+98 -13
View File
@@ -1164,25 +1164,80 @@ fn capacity_target_physical_bytes(data_bytes: usize, layout: DecommissionErasure
Ok(capacity_mul_div_ceil(data_bytes, layout.width(), layout.data))
}
fn directory_owned_bytes_excluding_meta_sync(root: &std::path::Path) -> usize {
let mut total = 0usize;
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let name = entry.file_name();
if dir == root && name.to_string_lossy() == crate::disk::RUSTFS_META_BUCKET {
continue;
}
let Ok(ft) = entry.file_type() else {
continue;
};
if ft.is_symlink() {
continue;
}
if ft.is_dir() {
stack.push(entry.path());
} else if ft.is_file()
&& let Ok(meta) = entry.metadata()
{
total = total.saturating_add(usize::try_from(meta.len()).unwrap_or(usize::MAX));
}
}
}
total
}
async fn decommission_owned_physical_usage(sets: &Sets, layout: DecommissionErasureLayout) -> HashMap<i32, usize> {
let bypass_shared_mount_check = rustfs_utils::get_env_bool_with_aliases(
rustfs_config::ENV_UNSAFE_BYPASS_DISK_CHECK,
&[rustfs_config::ENV_MINIO_CI],
rustfs_config::DEFAULT_UNSAFE_BYPASS_DISK_CHECK,
);
let mut usage = HashMap::with_capacity(sets.disk_set.len());
for (set_index, set) in sets.disk_set.iter().enumerate() {
let Ok(cache) = load_data_usage_cache(set.as_ref(), DATA_USAGE_CACHE_NAME).await else {
let Ok(set_index_i32) = i32::try_from(set_index) else {
continue;
};
let data_usage = cache.dui(DATA_USAGE_ROOT, &[]);
if !data_usage.is_complete_bucket_usage_snapshot() {
continue;
if let Ok(cache) = load_data_usage_cache(set.as_ref(), DATA_USAGE_CACHE_NAME).await {
let data_usage = cache.dui(DATA_USAGE_ROOT, &[]);
if data_usage.is_complete_bucket_usage_snapshot()
&& let Ok(logical_bytes) = usize::try_from(data_usage.objects_total_size)
{
// The data-usage snapshot excludes unrelated files on a shared mount.
// Convert logical object bytes to the source set's physical EC footprint.
usage.insert(set_index_i32, capacity_mul_div_ceil(logical_bytes, layout.width(), layout.data));
continue;
}
}
if bypass_shared_mount_check {
let local_roots: Vec<std::path::PathBuf> = sets
.endpoints
.endpoints
.as_ref()
.iter()
.filter(|ep| ep.is_local && ep.set_idx == set_index_i32)
.map(|ep| std::path::PathBuf::from(ep.get_file_path()))
.collect();
if !local_roots.is_empty()
&& let Ok(max_drive_bytes) = tokio::task::spawn_blocking(move || {
local_roots
.iter()
.map(|root| directory_owned_bytes_excluding_meta_sync(root))
.max()
.unwrap_or(0)
})
.await
{
usage.insert(set_index_i32, max_drive_bytes.saturating_mul(layout.width()));
}
}
let Ok(logical_bytes) = usize::try_from(data_usage.objects_total_size) else {
continue;
};
let Ok(set_index) = i32::try_from(set_index) else {
continue;
};
// The data-usage snapshot excludes unrelated files on a shared mount.
// Convert logical object bytes to the source set's physical EC footprint.
usage.insert(set_index, capacity_mul_div_ceil(logical_bytes, layout.width(), layout.data));
}
usage
}
@@ -15171,6 +15226,31 @@ impl ECStore {
Ok(())
}
pub(crate) async fn rollback_pool_meta_after_failed_reload(&self, previous: &PoolMeta) -> Result<()> {
let mut save_guard = self.pool_meta_save_gate.write().await;
let (pool_meta_guard, _current_on_disk) = self
.acquire_pool_meta_write_guard(&mut save_guard, "pool metadata rollback failed")
.await?;
let mut restored = previous.clone();
restored.dont_save = false;
let indices: Vec<usize> = (0..restored.pools.len()).collect();
let outcome = restored
.save_no_lock_armed(
self.pools.clone(),
&mut save_guard,
PoolMetaPersistenceFence::Owned(Arc::clone(&pool_meta_guard)),
&indices,
)
.await?;
let mut pool_meta = self.pool_meta.write().await;
ensure_pool_meta_write_fence(&pool_meta_guard, "pool metadata rollback failed")?;
*pool_meta = outcome.committed.clone();
ensure_pool_meta_write_fence(&pool_meta_guard, "pool metadata rollback failed")?;
drop(pool_meta);
outcome.disarm();
Ok(())
}
#[cfg(test)]
pub(crate) async fn save_current_pool_meta_for_test(&self, indices: &[usize]) -> Result<()> {
self.save_current_pool_meta(indices).await
@@ -20378,9 +20458,14 @@ impl ECStore {
#[cfg(test)]
pause_decommission_start_for_test(self.id, DecommissionStartPausePoint::StartGate).await;
let movement_start_gate = self.ctx.movement_start_gate();
let _instance_start_guard = budget
.acquire(DECOMMISSION_ACTIVATION_START_GATE, movement_start_gate.lock())
.await?;
let _start_guard = budget
.acquire(DECOMMISSION_ACTIVATION_START_GATE, self.start_gate.lock())
.await?;
self.ensure_not_retired()?;
self.ensure_decommission_rebalance_idle_after_refresh_under_start_gate(budget)
.await?;
// Another start may have activated these pools since the unlocked
+46 -7
View File
@@ -239,16 +239,43 @@ impl Sets {
pool_idx: usize,
parity_count: usize,
instance_ctx: Arc<InstanceContext>,
) -> Result<Arc<Self>> {
Self::new_with_staged_resources(disks, endpoints, fm, pool_idx, parity_count, instance_ctx, None, None, None, None).await
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn new_with_staged_resources(
disks: Vec<Option<DiskStore>>,
endpoints: &PoolEndpoints,
fm: &FormatV3,
pool_idx: usize,
parity_count: usize,
instance_ctx: Arc<InstanceContext>,
staged_is_dist_erasure: Option<bool>,
staged_local_set_drives: Option<&[Vec<Option<DiskStore>>]>,
staged_lock_registry: Option<&runtime_sources::LockRegistry>,
staged_local_node_name: Option<String>,
) -> Result<Arc<Self>> {
let set_count = fm.erasure.sets.len();
let set_drive_count = fm.erasure.sets[0].len();
let mut disk_set = Vec::with_capacity(set_count);
let pool_lockers = runtime_sources::lock_registry()
.as_ref()
.map(|registry| registry.clients_for_endpoints(endpoints.endpoints.as_ref()))
.unwrap_or_default();
let pool_lockers = match staged_lock_registry {
Some(registry) => registry.clients_for_endpoints(endpoints.endpoints.as_ref()),
None => runtime_sources::lock_registry()
.as_ref()
.map(|registry| registry.clients_for_endpoints(endpoints.endpoints.as_ref()))
.unwrap_or_default(),
};
let is_dist = match staged_is_dist_erasure {
Some(flag) => flag,
None => instance_ctx.is_dist_erasure().await,
};
let resolved_node_name = match staged_local_node_name {
Some(name) => name,
None => runtime_sources::local_node_name().await,
};
for i in 0..set_count {
let mut set_drive = Vec::with_capacity(set_drive_count);
@@ -265,8 +292,12 @@ impl Sets {
continue;
};
if disk.is_local() && instance_ctx.is_dist_erasure().await {
let Some(local_disk) = runtime_sources::local_disk_set_drive(&instance_ctx, pool_idx, i, j).await else {
if disk.is_local() && is_dist {
let local_disk_opt = match staged_local_set_drives {
Some(pool_sets) => pool_sets.get(i).and_then(|s| s.get(j)).cloned().flatten(),
None => runtime_sources::local_disk_set_drive(&instance_ctx, pool_idx, i, j).await,
};
let Some(local_disk) = local_disk_opt else {
warn!("sets new set_drive {}-{} local_disk is none", i, j);
set_drive.push(None);
continue;
@@ -306,7 +337,7 @@ impl Sets {
.unwrap_or_else(|| pool_lockers.clone());
let set_disks = SetDisks::new_with_instance_ctx(
runtime_sources::local_node_name().await,
resolved_node_name.clone(),
Arc::new(RwLock::new(set_drive)),
set_drive_count,
parity_count,
@@ -356,6 +387,14 @@ impl Sets {
&self.ctx
}
/// Signal the background endpoint reconnect monitor to stop immediately
/// when a store generation is retired during hot-reload or aborted staging.
pub fn stop_endpoint_monitor(&self) {
if let Some(exit_signal) = &self.exit_signal {
let _ = exit_signal.send(());
}
}
/// Stop endpoint reconnection and wait for any in-flight pass before a test owns disk probes.
#[cfg(any(test, feature = "test-util"))]
pub async fn stop_endpoint_monitor_for_test(&self) {
+7 -4
View File
@@ -36,8 +36,6 @@ use rustfs_io_metrics::walk_metrics::LocalWalkGuard;
use rustfs_madmin::{info_commands::DiskMetrics, metrics::TimedAction};
#[cfg(not(test))]
use std::sync::OnceLock;
#[cfg(test)]
use std::sync::atomic::AtomicBool;
use std::{
collections::HashMap,
io,
@@ -45,7 +43,7 @@ use std::{
pin::Pin,
sync::{
Arc, LazyLock, RwLock as StdRwLock,
atomic::{AtomicI64, AtomicU32, AtomicU64, Ordering},
atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering},
},
task::{Context, Poll},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
@@ -66,6 +64,8 @@ pub async fn wait_for_multipart_index_bootstrap(disk: &crate::disk::DiskStore) -
Ok(())
}
crate::disk::Disk::Remote(_) => Err(DiskError::MethodNotAllowed),
#[cfg(feature = "dst")]
crate::disk::Disk::Sim(_) => Ok(()),
}
}
@@ -1629,6 +1629,8 @@ pub struct LocalDiskWrapper {
physical_admission: Arc<crate::disk::io_admission::PhysicalDiskBinding>,
/// Whether health checking is enabled
health_check: bool,
/// Ensures `enable_health_check` spawns at most one active monitor per wrapper epoch
health_monitor_started: Arc<AtomicBool>,
/// Cancellation token for monitoring tasks
cancel_token: CancellationToken,
/// Retirement belongs to this wrapper instance, not its monitoring policy.
@@ -1785,6 +1787,7 @@ impl LocalDiskWrapper {
io_admission,
physical_admission: Arc::new(crate::disk::io_admission::PhysicalDiskBinding::default()),
health_check: health_check && env_health_check,
health_monitor_started: Arc::new(AtomicBool::new(false)),
cancel_token: CancellationToken::new(),
retired: CancellationToken::new(),
disk_id: Arc::new(RwLock::new(None)),
@@ -1967,7 +1970,7 @@ impl LocalDiskWrapper {
/// Enable health monitoring after disk creation.
/// Used to defer health checks until after startup format loading completes.
pub fn enable_health_check(&self) {
if !self.health_check {
if !self.health_check || self.health_monitor_started.swap(true, Ordering::AcqRel) {
return;
}
let health = Arc::clone(&self.health);
File diff suppressed because it is too large Load Diff
+59 -21
View File
@@ -3947,12 +3947,22 @@ fn run_format_probe_hook(path: &Path, read: bool) {
}
}
#[derive(Debug, Clone)]
pub(crate) struct CachedSlotCohort {
pub disk_id: Uuid,
pub data: Bytes,
pub set: usize,
pub physical_slot: usize,
pub disk_ids: Vec<Uuid>,
}
#[derive(Debug, Clone)]
pub struct FormatInfo {
pub id: Option<Uuid>,
pub data: Bytes,
pub file_info: Option<Metadata>,
pub last_check: Option<OffsetDateTime>,
pub(crate) slot_cohort: Option<CachedSlotCohort>,
}
fn read_format_control_record(
@@ -8384,6 +8394,7 @@ pub struct LocalDisk {
// handles while separating replacement roots at the same configured path.
format_control_key: PathBuf,
pub endpoint: Endpoint,
endpoint_pool_idx: std::sync::atomic::AtomicI32,
pub disk_info_cache: Arc<Cache<DiskInfo>>,
pub scanning: Arc<AtomicU32>,
pub rotational: bool,
@@ -8652,6 +8663,16 @@ impl LocalDisk {
.unwrap_or(crate::disk::multipart_source::ProofVerificationContext::RpcOnly)
}
pub(crate) fn current_endpoint(&self) -> Endpoint {
let mut ep = self.endpoint.clone();
ep.pool_idx = self.endpoint_pool_idx.load(Ordering::Acquire);
ep
}
pub(crate) fn set_pool_index(&self, pool_idx: i32) {
self.endpoint_pool_idx.store(pool_idx, Ordering::Release);
}
pub(crate) fn bind_multipart_proof_authority(
&self,
authority: &crate::disk::multipart_source::ProofVerificationContext,
@@ -8663,7 +8684,7 @@ impl LocalDisk {
Err(DiskError::ConditionalDeleteConflict)
};
}
authority.validate_endpoint(&self.endpoint)?;
authority.validate_endpoint(&self.current_endpoint())?;
let stored = self.multipart_proof_authority.get_or_init(|| authority.clone());
if !stored.same_authority(authority) {
return Err(DiskError::ConditionalDeleteConflict);
@@ -8867,6 +8888,7 @@ impl LocalDisk {
let mut id = None;
// let mut format_legacy = false;
let mut format_last_check = None;
let mut slot_cohort = None;
if !format_data.is_empty() {
let s = format_data.as_ref();
@@ -8880,6 +8902,15 @@ impl LocalDisk {
id = Some(fm.erasure.this);
// format_legacy = fm.erasure.distribution_algo == DistributionAlgoVersion::V1;
format_last_check = Some(OffsetDateTime::now_utc());
if let Some(cohort) = fm.erasure.sets.get(set_idx) {
slot_cohort = Some(CachedSlotCohort {
disk_id: fm.erasure.this,
data: format_data.clone(),
set: set_idx,
physical_slot: disk_idx,
disk_ids: cohort.clone(),
});
}
}
let format_info = FormatInfo {
@@ -8887,6 +8918,7 @@ impl LocalDisk {
data: format_data,
file_info: format_meta,
last_check: format_last_check,
slot_cohort,
};
let root_clone = root.clone();
let update_fn: UpdateFn<DiskInfo> = Box::new(move || {
@@ -8965,6 +8997,7 @@ impl LocalDisk {
#[cfg(target_os = "linux")]
mount_lease_identity,
endpoint: ep.clone(),
endpoint_pool_idx: std::sync::atomic::AtomicI32::new(ep.pool_idx),
format_path,
io_format_path,
format_info: Arc::new(RwLock::new(format_info)),
@@ -12804,6 +12837,7 @@ impl LocalDisk {
if volume == RUSTFS_META_BUCKET && path == super::FORMAT_CONFIG_FILE {
let mut format_info = self.format_info.write().await;
format_info.data.clone_from(&data);
format_info.slot_cohort = None;
}
let volume_dir = self.io_get_bucket_path(volume)?;
@@ -15451,7 +15485,7 @@ impl DiskAPI for LocalDisk {
}
fn endpoint(&self) -> Endpoint {
self.endpoint.clone()
self.current_endpoint()
}
async fn close(&self) -> Result<()> {
@@ -15475,14 +15509,9 @@ impl DiskAPI for LocalDisk {
}
fn get_disk_location(&self) -> DiskLocation {
let pool_idx = self.endpoint_pool_idx.load(Ordering::Acquire);
DiskLocation {
pool_idx: {
if self.endpoint.pool_idx < 0 {
None
} else {
Some(self.endpoint.pool_idx as usize)
}
},
pool_idx: { if pool_idx < 0 { None } else { Some(pool_idx as usize) } },
set_idx: {
if self.endpoint.set_idx < 0 {
None
@@ -15502,21 +15531,18 @@ impl DiskAPI for LocalDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn get_disk_id(&self) -> Result<Option<Uuid>> {
let format_info = {
let (id, cached_file_info) = {
let format_info = self.format_info.read().await;
format_info.clone()
};
let id = format_info.id;
if format_info.file_info.is_some() && id.is_some() {
// Reuse the cached disk id only when the cached format check is fresh.
if let Some(last_check) = format_info.last_check
let id = format_info.id;
if format_info.file_info.is_some()
&& id.is_some()
&& let Some(last_check) = format_info.last_check
&& last_check.unix_timestamp() + 1 >= OffsetDateTime::now_utc().unix_timestamp()
{
return Ok(id);
}
}
(id, format_info.file_info.clone())
};
let file_meta = match self.check_format_json().await {
Ok(meta) => meta,
@@ -15527,12 +15553,13 @@ impl DiskAPI for LocalDisk {
format_info.data = Bytes::new();
format_info.file_info = None;
format_info.last_check = None;
format_info.slot_cohort = None;
}
return Err(err);
}
};
if let Some(file_info) = &format_info.file_info
if let Some(file_info) = &cached_file_info
&& super::fs::same_file(&file_meta, file_info)
{
let mut format_info = self.format_info.write().await;
@@ -15565,11 +15592,21 @@ impl DiskAPI for LocalDisk {
return Err(DiskError::InconsistentDisk);
}
let data_bytes: Bytes = b.into();
let slot_cohort = fm.erasure.sets.get(m).map(|cohort| CachedSlotCohort {
disk_id,
data: data_bytes.clone(),
set: m,
physical_slot: n,
disk_ids: cohort.clone(),
});
let mut format_info = self.format_info.write().await;
format_info.id = Some(disk_id);
format_info.file_info = Some(file_meta);
format_info.data = b.into();
format_info.data = data_bytes;
format_info.last_check = Some(OffsetDateTime::now_utc());
format_info.slot_cohort = slot_cohort;
drop(format_info);
Ok(Some(disk_id))
@@ -15626,6 +15663,7 @@ impl DiskAPI for LocalDisk {
format_info.id = None;
format_info.file_info = None;
format_info.last_check = None;
format_info.slot_cohort = None;
}
};
// The native owner outlives a cancelled RPC. Both invalidations
+4 -2
View File
@@ -15,6 +15,8 @@
//! Single-disk object rename publication and rollback. The shared execution core
//! retains instrumentation, mutation leases, and commit guards through the syscall.
#[cfg(target_os = "linux")]
use super::has_rename_data_test_failpoints;
#[cfg(all(test, windows))]
use super::run_destination_commit_directory_preparation;
#[cfg(any(not(windows), test))]
@@ -22,8 +24,8 @@ use super::should_fail_local_inline_rollback_hardlink;
use super::{
EVENT_DISK_LOCAL_ACCESS_FAILED, EVENT_DISK_LOCAL_HEAL_PURGE_FAILED, EVENT_DISK_LOCAL_RENAME_REJECTED, LOG_COMPONENT_ECSTORE,
LOG_SUBSYSTEM_DISK_LOCAL, LocalDisk, SyncMode, effective_durability, has_inline_commit_test_failpoints,
has_rename_data_test_failpoints, inline_metadata_rollback_dir, observe_old_current, remove_dir_all_if_exists,
remove_dst_base_before_commit, remove_file_if_exists, rename_data_versions_signature, run_inline_preparation_before_backup,
inline_metadata_rollback_dir, observe_old_current, remove_dir_all_if_exists, remove_dst_base_before_commit,
remove_file_if_exists, rename_data_versions_signature, run_inline_preparation_before_backup,
should_fail_after_metadata_commit, should_fail_before_old_metadata_backup, should_fail_commit_rename,
should_remove_staged_meta_before_commit, skip_access_checks, tmp_staging_mutation_path,
};
@@ -329,49 +329,67 @@ pub(in crate::disk) fn generation(mut canonical: FileInfo) -> Result<crate::disk
// Only schema-declared string fields and the inline presence marker are
// aliases here. Unknown suffixes and opaque binary fields stay distinct.
use rustfs_utils::http::metadata_compat as compat;
for suffix in [
compat::SUFFIX_INLINE_DATA,
compat::SUFFIX_COMPRESSION,
compat::SUFFIX_COMPRESSION_SIZE,
compat::SUFFIX_ACTUAL_SIZE,
compat::SUFFIX_ACTUAL_OBJECT_SIZE,
compat::SUFFIX_ACTUAL_OBJECT_SIZE_CAP,
compat::SUFFIX_TRANSITION_STATUS,
compat::SUFFIX_TRANSITIONED_OBJECTNAME,
compat::SUFFIX_TRANSITION_TIER,
compat::SUFFIX_TRANSITIONED_VERSION_STATE,
compat::SUFFIX_TRANSITION_TIER_DESTINATION_ID,
compat::SUFFIX_PURGESTATUS,
compat::SUFFIX_REPLICA_STATUS,
compat::SUFFIX_REPLICATION_STATUS,
compat::SUFFIX_REPLICA_TIMESTAMP,
compat::SUFFIX_REPLICATION_TIMESTAMP,
compat::SUFFIX_TAGGING_TIMESTAMP,
compat::SUFFIX_OBJECTLOCK_RETENTION_TIMESTAMP,
compat::SUFFIX_OBJECTLOCK_LEGALHOLD_TIMESTAMP,
] {
if canonical.metadata.is_empty() {
break;
}
if !compat::contains_key_str(&canonical.metadata, suffix) {
continue;
}
// Identity compares persisted bytes, including a consistently empty field.
// Conflicting aliases still cannot identify a unique generation.
let rustfs_key = compat::internal_key_rustfs(suffix);
let minio_key = format!("{}{suffix}", compat::MINIO_INTERNAL_PREFIX);
let mut value = None;
for (key, candidate) in &canonical.metadata {
if !key.eq_ignore_ascii_case(&rustfs_key) && !key.eq_ignore_ascii_case(&minio_key) {
continue;
if canonical.metadata.keys().any(|k| compat::is_internal_key(k)) {
for suffix in [
compat::SUFFIX_INLINE_DATA,
compat::SUFFIX_COMPRESSION,
compat::SUFFIX_COMPRESSION_SIZE,
compat::SUFFIX_ACTUAL_SIZE,
compat::SUFFIX_ACTUAL_OBJECT_SIZE,
compat::SUFFIX_ACTUAL_OBJECT_SIZE_CAP,
compat::SUFFIX_TRANSITION_STATUS,
compat::SUFFIX_TRANSITIONED_OBJECTNAME,
compat::SUFFIX_TRANSITION_TIER,
compat::SUFFIX_TRANSITIONED_VERSION_STATE,
compat::SUFFIX_TRANSITION_TIER_DESTINATION_ID,
compat::SUFFIX_PURGESTATUS,
compat::SUFFIX_REPLICA_STATUS,
compat::SUFFIX_REPLICATION_STATUS,
compat::SUFFIX_REPLICA_TIMESTAMP,
compat::SUFFIX_REPLICATION_TIMESTAMP,
compat::SUFFIX_TAGGING_TIMESTAMP,
compat::SUFFIX_OBJECTLOCK_RETENTION_TIMESTAMP,
compat::SUFFIX_OBJECTLOCK_LEGALHOLD_TIMESTAMP,
] {
// Identity compares persisted bytes, including a consistently empty field.
// Conflicting aliases still cannot identify a unique generation.
let mut value = None;
let mut exact_rustfs = false;
let mut exact_minio = false;
for (key, candidate) in &canonical.metadata {
let is_rustfs = key.len() == compat::RUSTFS_INTERNAL_PREFIX.len() + suffix.len()
&& compat::starts_with_ignore_ascii_case(key, compat::RUSTFS_INTERNAL_PREFIX)
&& key.as_bytes()[compat::RUSTFS_INTERNAL_PREFIX.len()..].eq_ignore_ascii_case(suffix.as_bytes());
let is_minio = !is_rustfs
&& key.len() == compat::MINIO_INTERNAL_PREFIX.len() + suffix.len()
&& compat::starts_with_ignore_ascii_case(key, compat::MINIO_INTERNAL_PREFIX)
&& key.as_bytes()[compat::MINIO_INTERNAL_PREFIX.len()..].eq_ignore_ascii_case(suffix.as_bytes());
if !is_rustfs && !is_minio {
continue;
}
if value.is_some_and(|current: &String| current != candidate) {
return Err(DiskError::FileCorrupt);
}
value = Some(candidate);
if is_rustfs
&& key.starts_with(compat::RUSTFS_INTERNAL_PREFIX)
&& &key[compat::RUSTFS_INTERNAL_PREFIX.len()..] == suffix
{
exact_rustfs = true;
} else if is_minio
&& key.starts_with(compat::MINIO_INTERNAL_PREFIX)
&& &key[compat::MINIO_INTERNAL_PREFIX.len()..] == suffix
{
exact_minio = true;
}
}
if value.is_some_and(|current: &String| current != candidate) {
return Err(DiskError::FileCorrupt);
if let Some(value) = value
&& !(exact_rustfs && exact_minio && !matches!(suffix, compat::SUFFIX_COMPRESSION | compat::SUFFIX_ACTUAL_SIZE))
{
let value = value.clone();
compat::insert_str(&mut canonical.metadata, suffix, value);
}
value = Some(candidate);
}
let value = value.ok_or(DiskError::FileCorrupt)?.clone();
compat::insert_str(&mut canonical.metadata, suffix, value);
}
fn sort_json_in_place(value: &mut serde_json::Value) {
match value {
@@ -2367,12 +2385,23 @@ impl LocalDisk {
.await?
}
};
let surviving: HashSet<_> = plan
.versions
.iter()
.map(|version| (version.header.version_id, std::mem::discriminant(&version.header.version_type)))
.collect();
deleted_headers.retain(|header| !surviving.contains(header));
if !plan.versions.is_empty() {
if plan.versions.len() <= 8 {
deleted_headers.retain(|header| {
!plan
.versions
.iter()
.any(|v| (v.header.version_id, std::mem::discriminant(&v.header.version_type)) == *header)
});
} else {
let surviving: HashSet<_> = plan
.versions
.iter()
.map(|version| (version.header.version_id, std::mem::discriminant(&version.header.version_type)))
.collect();
deleted_headers.retain(|header| !surviving.contains(header));
}
}
let deleted_versions = deleted_headers.into_iter().map(|(id, _)| id.unwrap_or_default()).collect();
let requests = requests
.iter()
@@ -3286,12 +3315,23 @@ impl LocalDisk {
check_path_length(old_path.to_string_lossy().as_ref())?;
old_path_to_verify = Some(old_path);
}
let surviving: HashSet<_> = meta
.versions
.iter()
.map(|v| (v.header.version_id, std::mem::discriminant(&v.header.version_type)))
.collect();
deleted_headers.retain(|header| !surviving.contains(header));
if !meta.versions.is_empty() {
if meta.versions.len() <= 8 {
deleted_headers.retain(|header| {
!meta
.versions
.iter()
.any(|v| (v.header.version_id, std::mem::discriminant(&v.header.version_type)) == *header)
});
} else {
let surviving: HashSet<_> = meta
.versions
.iter()
.map(|v| (v.header.version_id, std::mem::discriminant(&v.header.version_type)))
.collect();
deleted_headers.retain(|header| !surviving.contains(header));
}
}
let deleted_versions = deleted_headers.into_iter().map(|(id, _)| id.unwrap_or_default()).collect();
let target = (!meta.versions.is_empty()).then(|| meta.marshal_msg()).transpose()?;
let DeleteObjectDirScanOutcome {
@@ -175,6 +175,36 @@ impl ValidatedOwnedCertificate {
}
impl LocalDisk {
pub(super) async fn get_disk_slot_and_cohort(&self, disk_id: Uuid) -> Result<(usize, usize, Vec<Uuid>)> {
{
let format_info = self.format_info.read().await;
if let Some(cached) = &format_info.slot_cohort
&& cached.disk_id == disk_id
&& cached.data.as_ptr() == format_info.data.as_ptr()
&& cached.data.len() == format_info.data.len()
{
return Ok((cached.set, cached.physical_slot, cached.disk_ids.clone()));
}
}
let format_bytes = self.format_info.read().await.data.clone();
let format = crate::disk::format::FormatV3::try_from(format_bytes.as_ref()).map_err(|_| DiskError::CorruptedBackend)?;
let (set, physical_slot) = format.find_disk_index_by_disk_id(disk_id)?;
let disk_ids = format.erasure.sets.get(set).ok_or(DiskError::CorruptedBackend)?.clone();
{
let mut format_info = self.format_info.write().await;
if format_info.data.as_ptr() == format_bytes.as_ptr() && format_info.data.len() == format_bytes.len() {
format_info.slot_cohort = Some(super::CachedSlotCohort {
disk_id,
data: format_bytes,
set,
physical_slot,
disk_ids: disk_ids.clone(),
});
}
}
Ok((set, physical_slot, disk_ids))
}
pub(super) async fn open_multipart_source_store(
&self,
path: &str,
@@ -195,12 +225,9 @@ impl LocalDisk {
.await?
.filter(|id| !id.is_nil())
.ok_or(DiskError::UnformattedDisk)?;
let format = self.format_info.read().await.data.clone();
let format = crate::disk::format::FormatV3::try_from(format.as_ref()).map_err(|_| DiskError::CorruptedBackend)?;
let (set, physical_slot) = format.find_disk_index_by_disk_id(disk_id)?;
let disk_ids = format.erasure.sets.get(set).ok_or(DiskError::CorruptedBackend)?.clone();
let (_set, physical_slot, disk_ids) = self.get_disk_slot_and_cohort(disk_id).await?;
if (self.endpoint.disk_idx >= 0 && self.endpoint.disk_idx as usize != physical_slot)
|| (self.endpoint.set_idx >= 0 && self.endpoint.set_idx as usize != set)
|| (self.endpoint.set_idx >= 0 && self.endpoint.set_idx as usize != _set)
{
return Err(DiskError::ConditionalDeleteConflict);
}
@@ -1690,10 +1717,8 @@ impl LocalDisk {
if self.root != proof.root || self.io_root() != proof.base || self.get_disk_id().await? != Some(proof.disk_id) {
return Err(DiskError::ConditionalDeleteConflict);
}
let format = self.format_info.read().await.data.clone();
let format = crate::disk::format::FormatV3::try_from(format.as_ref()).map_err(|_| DiskError::CorruptedBackend)?;
let (set, slot) = format.find_disk_index_by_disk_id(proof.disk_id)?;
if slot != proof.physical_slot || format.erasure.sets.get(set) != Some(&proof.disk_ids) {
let (_set, slot, cohort) = self.get_disk_slot_and_cohort(proof.disk_id).await?;
if slot != proof.physical_slot || cohort != proof.disk_ids {
return Err(DiskError::ConditionalDeleteConflict);
}
let volume = proof.publication.lineage.bucket.clone();
@@ -2859,10 +2884,7 @@ impl LocalDisk {
.await?
.filter(|id| !id.is_nil())
.ok_or(DiskError::UnformattedDisk)?;
let format = self.format_info.read().await.data.clone();
let format = crate::disk::format::FormatV3::try_from(format.as_ref()).map_err(|_| DiskError::CorruptedBackend)?;
let (set, slot) = format.find_disk_index_by_disk_id(disk_id)?;
let cohort = format.erasure.sets.get(set).ok_or(DiskError::CorruptedBackend)?;
let (_set, slot, cohort) = self.get_disk_slot_and_cohort(disk_id).await?;
if anchor.protocol_version != MULTIPART_SOURCE_PROTOCOL_VERSION
|| anchor.disk_id != disk_id
|| anchor.physical_slot != slot
@@ -563,7 +563,6 @@ impl LocalDisk {
cleaned: Arc::new(std::sync::atomic::AtomicBool::new(false)),
fresh_source_head: None,
};
let canonical_metadata = self.io_get_object_path(RUSTFS_META_MULTIPART_BUCKET, &format!("{source_path}/xl.meta"))?;
let source_object = self.io_get_object_path(RUSTFS_META_MULTIPART_BUCKET, source_path)?;
let private_object = staging.io_path.clone();
let base = self.io_root().to_path_buf();
@@ -581,6 +580,10 @@ impl LocalDisk {
let (raw, source, from_active_cache) = if let Some((raw, source)) = cached_head {
(raw, source, true)
} else {
let canonical_metadata = source_object.join(crate::disk::STORAGE_FORMAT_FILE);
if std::fs::symlink_metadata(&canonical_metadata).is_ok_and(|meta| meta.file_type().is_symlink()) {
return Err(std::io::Error::from(DiskError::InvalidPath));
}
let raw = os::read_multipart_source_metadata(&canonical_metadata, &base, &publication_root).map_err(|error| {
// A retired source has no authority for this delayed completion.
// Preserve confinement and other I/O failures as their real errors.
+290
View File
@@ -16,6 +16,8 @@
pub(crate) mod cleanup_runtime;
pub mod disk_store;
#[cfg(feature = "dst")]
pub mod dst_sim;
pub mod endpoint;
pub mod error;
pub mod error_conv;
@@ -357,6 +359,8 @@ pub struct MmapCopyStageMetrics {
pub enum Disk {
Local(Box<LocalDiskWrapper>),
Remote(Box<RemoteDisk>),
#[cfg(feature = "dst")]
Sim(Box<dst_sim::DstSimDisk>),
}
impl Disk {
@@ -365,6 +369,8 @@ impl Disk {
match self {
Self::Local(disk) => disk.read_file(volume, path).await,
Self::Remote(disk) => disk.read_format_control(volume, path).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.read_file(volume, path).await,
}
}
@@ -373,6 +379,8 @@ impl Disk {
match self {
Self::Local(disk) => Some(disk.physical_admission()),
Self::Remote(_) => None,
#[cfg(feature = "dst")]
Self::Sim(_) => None,
}
}
@@ -381,6 +389,8 @@ impl Disk {
match self {
Self::Local(disk) => disk.get_disk().is_plain_orphan_data_dir(volume, path).await,
Self::Remote(disk) => disk.is_plain_orphan_data_dir(volume, path).await,
#[cfg(feature = "dst")]
Self::Sim(_) => Ok(true),
}
}
@@ -400,6 +410,11 @@ impl Disk {
let _owner = namespace_owner;
disk.delete_versions(volume, versions, opts).await
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
let _owner = namespace_owner;
disk.delete_versions(volume, versions, opts).await
}
}
}
@@ -426,6 +441,11 @@ impl Disk {
let _owner = namespace_owner;
disk.delete_versions_recoverable(volume, versions, opts).await
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
let _owner = namespace_owner;
disk.delete_versions_recoverable(volume, versions, opts).await
}
}
}
@@ -455,6 +475,12 @@ impl Disk {
disk.settle_delete_transaction(volume, object, transaction, expected_fingerprint, action)
.await
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
let _owner = namespace_owner;
disk.settle_delete_transaction(volume, object, transaction, expected_fingerprint, action)
.await
}
}
}
@@ -462,6 +488,8 @@ impl Disk {
match self {
Self::Local(disk) => disk.has_clean_active_multipart_source(upload_or_part_path, part_path),
Self::Remote(_) => false,
#[cfg(feature = "dst")]
Self::Sim(_) => false,
}
}
@@ -474,6 +502,8 @@ impl Disk {
match self {
Self::Local(disk) => disk.has_active_multipart_source_matching(upload_path, expected_data_dir, expected_mod_time),
Self::Remote(_) => false,
#[cfg(feature = "dst")]
Self::Sim(_) => false,
}
}
@@ -498,6 +528,8 @@ impl Disk {
.await
}
Self::Remote(_) => Ok(None),
#[cfg(feature = "dst")]
Self::Sim(_) => Ok(None),
}
}
@@ -526,6 +558,8 @@ impl Disk {
.await
}
Self::Remote(_) => Ok(false),
#[cfg(feature = "dst")]
Self::Sim(_) => Ok(false),
}
}
@@ -552,6 +586,12 @@ impl Disk {
disk.delete_version_recoverable(volume, path, fi, force_del_marker, opts)
.await
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
let _owner = namespace_owner;
disk.delete_version_recoverable(volume, path, fi, force_del_marker, opts)
.await
}
}
}
pub(crate) async fn set_disk_id_state(&self, id: Option<Uuid>) -> Result<()> {
@@ -561,6 +601,8 @@ impl Disk {
Ok(())
}
Disk::Remote(remote_disk) => remote_disk.set_disk_id(id).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.set_disk_id(id).await,
}
}
@@ -568,6 +610,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => Some(local_disk.health_tracker_epoch_for_reconnect()),
Disk::Remote(_) => None,
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -587,6 +631,11 @@ impl Disk {
let _owner = namespace_owner;
disk.delete_versions_guarded_recoverable(volume, versions, opts).await
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
let _owner = namespace_owner;
disk.delete_versions_guarded_recoverable(volume, versions, opts).await
}
}
}
@@ -594,6 +643,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.get_current_disk_id().await,
Disk::Remote(remote_disk) => remote_disk.get_disk_id().await.ok().flatten(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.get_disk_id().await.ok().flatten(),
}
}
}
@@ -608,6 +659,8 @@ impl DiskAPI for Disk {
match self {
Self::Local(disk) => disk.list_multipart_index_roots(bucket, marker).await,
Self::Remote(disk) => disk.list_multipart_index_roots(bucket, marker).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.list_multipart_index_roots(bucket, marker).await,
}
}
@@ -615,6 +668,8 @@ impl DiskAPI for Disk {
match self {
Self::Local(disk) => disk.supports_guarded_delete_versions().await,
Self::Remote(disk) => disk.supports_guarded_delete_versions().await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.supports_guarded_delete_versions().await,
}
}
async fn delete_versions_guarded_recoverable(
@@ -646,12 +701,16 @@ impl DiskAPI for Disk {
match self {
Self::Local(disk) => disk.delete_versions_recoverable(volume, versions, opts).await,
Self::Remote(disk) => disk.delete_versions_recoverable(volume, versions, opts).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.delete_versions_recoverable(volume, versions, opts).await,
}
}
async fn has_delete_transaction_evidence(&self, volume: &str, object: &str) -> Result<bool> {
match self {
Self::Local(disk) => disk.has_delete_transaction_evidence(volume, object).await,
Self::Remote(disk) => disk.has_delete_transaction_evidence(volume, object).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.has_delete_transaction_evidence(volume, object).await,
}
}
async fn discover_delete_transactions_bounded(
@@ -663,6 +722,8 @@ impl DiskAPI for Disk {
match self {
Self::Local(disk) => disk.discover_delete_transactions_bounded(volume, object, max_entries).await,
Self::Remote(disk) => disk.discover_delete_transactions_bounded(volume, object, max_entries).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.discover_delete_transactions_bounded(volume, object, max_entries).await,
}
}
async fn discover_delete_transactions(
@@ -675,6 +736,8 @@ impl DiskAPI for Disk {
match self {
Self::Local(disk) => disk.discover_delete_transactions(volume, object, cursor, limit).await,
Self::Remote(disk) => disk.discover_delete_transactions(volume, object, cursor, limit).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.discover_delete_transactions(volume, object, cursor, limit).await,
}
}
async fn settle_delete_transaction_bounded(
@@ -686,6 +749,8 @@ impl DiskAPI for Disk {
match self {
Self::Local(disk) => disk.settle_delete_transaction_bounded(volume, request, namespace_owner).await,
Self::Remote(disk) => disk.settle_delete_transaction_bounded(volume, request, namespace_owner).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.settle_delete_transaction_bounded(volume, request, namespace_owner).await,
}
}
async fn inspect_delete_transaction_bounded(
@@ -704,6 +769,11 @@ impl DiskAPI for Disk {
disk.inspect_delete_transaction_bounded(volume, object, transaction, max_entries)
.await
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
disk.inspect_delete_transaction_bounded(volume, object, transaction, max_entries)
.await
}
}
}
async fn inspect_delete_transaction(
@@ -715,6 +785,8 @@ impl DiskAPI for Disk {
match self {
Self::Local(disk) => disk.inspect_delete_transaction(volume, object, transaction).await,
Self::Remote(disk) => disk.inspect_delete_transaction(volume, object, transaction).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => disk.inspect_delete_transaction(volume, object, transaction).await,
}
}
async fn settle_delete_transaction(
@@ -734,12 +806,19 @@ impl DiskAPI for Disk {
disk.settle_delete_transaction(volume, object, transaction, expected_fingerprint, action)
.await
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
disk.settle_delete_transaction(volume, object, transaction, expected_fingerprint, action)
.await
}
}
}
fn to_string(&self) -> String {
match self {
Disk::Local(local_disk) => local_disk.to_string(),
Disk::Remote(remote_disk) => remote_disk.to_string(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.to_string(),
}
}
@@ -747,6 +826,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.is_online().await,
Disk::Remote(remote_disk) => remote_disk.is_online().await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.is_online().await,
}
}
@@ -754,6 +835,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.is_local(),
Disk::Remote(remote_disk) => remote_disk.is_local(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.is_local(),
}
}
@@ -761,6 +844,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.host_name(),
Disk::Remote(remote_disk) => remote_disk.host_name(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.host_name(),
}
}
@@ -768,6 +853,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.endpoint(),
Disk::Remote(remote_disk) => remote_disk.endpoint(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.endpoint(),
}
}
@@ -775,6 +862,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.close().await,
Disk::Remote(remote_disk) => remote_disk.close().await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.close().await,
}
}
@@ -782,6 +871,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.get_disk_id().await,
Disk::Remote(remote_disk) => remote_disk.get_disk_id().await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.get_disk_id().await,
}
}
@@ -789,6 +880,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.set_disk_id(id).await,
Disk::Remote(remote_disk) => remote_disk.set_disk_id(id).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.set_disk_id(id).await,
}
}
@@ -796,6 +889,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.path(),
Disk::Remote(remote_disk) => remote_disk.path(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.path(),
}
}
@@ -803,6 +898,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.get_disk_location(),
Disk::Remote(remote_disk) => remote_disk.get_disk_location(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.get_disk_location(),
}
}
@@ -810,6 +907,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.bucket_creation_witness(volume).await,
Disk::Remote(_) => Ok(None),
#[cfg(feature = "dst")]
Disk::Sim(_) => Ok(None),
}
}
@@ -818,6 +917,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.make_volume(volume).await,
Disk::Remote(remote_disk) => remote_disk.make_volume(volume).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.make_volume(volume).await,
}
}
@@ -826,6 +927,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.make_volumes(volumes).await,
Disk::Remote(remote_disk) => remote_disk.make_volumes(volumes).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.make_volumes(volumes).await,
}
}
@@ -834,6 +937,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.list_volumes().await,
Disk::Remote(remote_disk) => remote_disk.list_volumes().await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.list_volumes().await,
}
}
@@ -841,6 +946,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.stat_volume(volume).await,
Disk::Remote(remote_disk) => remote_disk.stat_volume(volume).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.stat_volume(volume).await,
}
}
@@ -849,6 +956,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.delete_volume(volume, force_delete).await,
Disk::Remote(remote_disk) => remote_disk.delete_volume(volume, force_delete).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.delete_volume(volume, force_delete).await,
}
}
@@ -857,6 +966,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.walk_dir(opts, wr).await,
Disk::Remote(remote_disk) => remote_disk.walk_dir(opts, wr).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.walk_dir(opts, wr).await,
}
}
@@ -880,6 +991,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.delete_version(volume, path, fi, force_del_marker, opts).await,
Disk::Remote(remote_disk) => remote_disk.delete_version(volume, path, fi, force_del_marker, opts).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.delete_version(volume, path, fi, force_del_marker, opts).await,
}
}
@@ -888,6 +1001,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.delete_versions(volume, versions, opts).await,
Disk::Remote(remote_disk) => remote_disk.delete_versions(volume, versions, opts).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.delete_versions(volume, versions, opts).await,
}
}
@@ -896,6 +1011,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.delete_paths(volume, paths).await,
Disk::Remote(remote_disk) => remote_disk.delete_paths(volume, paths).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.delete_paths(volume, paths).await,
}
}
@@ -903,6 +1020,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.acquire_snapshot_lease(volume, path).await,
Disk::Remote(remote_disk) => remote_disk.acquire_snapshot_lease(volume, path).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.acquire_snapshot_lease(volume, path).await,
}
}
@@ -910,6 +1029,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.release_snapshot_lease(volume, path, token).await,
Disk::Remote(remote_disk) => remote_disk.release_snapshot_lease(volume, path, token).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.release_snapshot_lease(volume, path, token).await,
}
}
@@ -917,6 +1038,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.renew_snapshot_lease(volume, path, token).await,
Disk::Remote(remote_disk) => remote_disk.renew_snapshot_lease(volume, path, token).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.renew_snapshot_lease(volume, path, token).await,
}
}
@@ -924,6 +1047,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.delete_data_dir(volume, path, opts).await,
Disk::Remote(remote_disk) => remote_disk.delete_data_dir(volume, path, opts).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.delete_data_dir(volume, path, opts).await,
}
}
@@ -932,6 +1057,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.write_metadata(_org_volume, volume, path, fi).await,
Disk::Remote(remote_disk) => remote_disk.write_metadata(_org_volume, volume, path, fi).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.write_metadata(_org_volume, volume, path, fi).await,
}
}
@@ -940,6 +1067,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.update_metadata(volume, path, fi, opts).await,
Disk::Remote(remote_disk) => remote_disk.update_metadata(volume, path, fi, opts).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.update_metadata(volume, path, fi, opts).await,
}
}
@@ -957,6 +1086,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_version(_org_volume, volume, path, version_id, opts).await,
Disk::Remote(remote_disk) => remote_disk.read_version(_org_volume, volume, path, version_id, opts).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_version(_org_volume, volume, path, version_id, opts).await,
}
};
#[cfg(feature = "diagnostic-read-version-caller")]
@@ -974,6 +1105,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.batch_read_version(req).await,
Disk::Remote(remote_disk) => remote_disk.batch_read_version(req).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.batch_read_version(req).await,
}
}
@@ -982,6 +1115,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_xl(volume, path, read_data).await,
Disk::Remote(remote_disk) => remote_disk.read_xl(volume, path, read_data).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_xl(volume, path, read_data).await,
}
}
@@ -1015,6 +1150,11 @@ impl DiskAPI for Disk {
disk.rename_data_with_pool_meta_cas(src_volume, src_path, fi, dst_volume, dst_path)
.await
}
#[cfg(feature = "dst")]
Disk::Sim(disk) => {
disk.rename_data_with_pool_meta_cas(src_volume, src_path, fi, dst_volume, dst_path)
.await
}
}
}
@@ -1022,6 +1162,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(disk) => disk.undo_pool_meta_write(volume, path, fi, opts).await,
Disk::Remote(disk) => disk.undo_pool_meta_write(volume, path, fi, opts).await,
#[cfg(feature = "dst")]
Disk::Sim(disk) => disk.undo_pool_meta_write(volume, path, fi, opts).await,
}
}
@@ -1032,6 +1174,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(disk) => disk.recover_multipart_source(request).await,
Disk::Remote(disk) => disk.recover_multipart_source(request).await,
#[cfg(feature = "dst")]
Disk::Sim(disk) => disk.recover_multipart_source(request).await,
}
}
@@ -1039,6 +1183,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(disk) => disk.pool_meta_native_recovery(request).await,
Disk::Remote(disk) => disk.pool_meta_native_recovery(request).await,
#[cfg(feature = "dst")]
Disk::Sim(disk) => disk.pool_meta_native_recovery(request).await,
}
}
@@ -1047,6 +1193,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.list_dir(_origvolume, volume, dir_path, count).await,
Disk::Remote(remote_disk) => remote_disk.list_dir(_origvolume, volume, dir_path, count).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.list_dir(_origvolume, volume, dir_path, count).await,
}
}
@@ -1055,6 +1203,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_file(volume, path).await,
Disk::Remote(remote_disk) => remote_disk.read_file(volume, path).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_file(volume, path).await,
}
}
@@ -1063,6 +1213,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_file_stream(volume, path, offset, length).await,
Disk::Remote(remote_disk) => remote_disk.read_file_stream(volume, path, offset, length).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_file_stream(volume, path, offset, length).await,
}
}
@@ -1076,6 +1228,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(_) => Ok(None),
Disk::Remote(remote_disk) => remote_disk.read_file_stream_chunks(volume, path, offset, length).await,
#[cfg(feature = "dst")]
Disk::Sim(_) => Ok(None),
}
}
@@ -1084,6 +1238,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_file_mmap_copy(volume, path, offset, length).await,
Disk::Remote(remote_disk) => remote_disk.read_file_mmap_copy(volume, path, offset, length).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_file_mmap_copy(volume, path, offset, length).await,
}
}
@@ -1102,6 +1258,8 @@ impl DiskAPI for Disk {
.await
}
Disk::Remote(remote_disk) => remote_disk.read_file_mmap_copy(volume, path, offset, length).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_file_mmap_copy(volume, path, offset, length).await,
}
}
@@ -1110,6 +1268,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.append_file(volume, path).await,
Disk::Remote(remote_disk) => remote_disk.append_file(volume, path).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.append_file(volume, path).await,
}
}
@@ -1118,6 +1278,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.create_file(_origvolume, volume, path, _file_size).await,
Disk::Remote(remote_disk) => remote_disk.create_file(_origvolume, volume, path, _file_size).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.create_file(_origvolume, volume, path, _file_size).await,
}
}
@@ -1126,6 +1288,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.rename_file(src_volume, src_path, dst_volume, dst_path).await,
Disk::Remote(remote_disk) => remote_disk.rename_file(src_volume, src_path, dst_volume, dst_path).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.rename_file(src_volume, src_path, dst_volume, dst_path).await,
}
}
@@ -1134,6 +1298,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_parts(bucket, paths).await,
Disk::Remote(remote_disk) => remote_disk.read_parts(bucket, paths).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_parts(bucket, paths).await,
}
}
@@ -1141,6 +1307,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(disk) => disk.rename_file_durable(src_volume, src_path, dst_volume, dst_path).await,
Disk::Remote(disk) => disk.rename_file_durable(src_volume, src_path, dst_volume, dst_path).await,
#[cfg(feature = "dst")]
Disk::Sim(disk) => disk.rename_file_durable(src_volume, src_path, dst_volume, dst_path).await,
}
}
@@ -1153,6 +1321,8 @@ impl DiskAPI for Disk {
.rename_part(src_volume, src_path, dst_volume, dst_path, meta)
.await
}
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.rename_part(src_volume, src_path, dst_volume, dst_path, meta).await,
}
}
@@ -1175,6 +1345,12 @@ impl DiskAPI for Disk {
.prepare_part_transaction(src_volume, src_path, dst_volume, dst_path, meta)
.await
}
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => {
sim_disk
.prepare_part_transaction(src_volume, src_path, dst_volume, dst_path, meta)
.await
}
}
}
@@ -1182,6 +1358,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.settle_part_transaction(volume, path, action).await,
Disk::Remote(remote_disk) => remote_disk.settle_part_transaction(volume, path, action).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.settle_part_transaction(volume, path, action).await,
}
}
@@ -1196,6 +1374,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.delete(volume, path, opt).await,
Disk::Remote(remote_disk) => remote_disk.delete(volume, path, opt).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.delete(volume, path, opt).await,
}
}
@@ -1204,6 +1384,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.verify_file(volume, path, fi).await,
Disk::Remote(remote_disk) => remote_disk.verify_file(volume, path, fi).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.verify_file(volume, path, fi).await,
}
}
@@ -1212,6 +1394,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.check_parts(volume, path, fi).await,
Disk::Remote(remote_disk) => remote_disk.check_parts(volume, path, fi).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.check_parts(volume, path, fi).await,
}
}
@@ -1220,6 +1404,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_multiple(req).await,
Disk::Remote(remote_disk) => remote_disk.read_multiple(req).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_multiple(req).await,
}
}
@@ -1228,6 +1414,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.write_all(volume, path, data).await,
Disk::Remote(remote_disk) => remote_disk.write_all(volume, path, data).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.write_all(volume, path, data).await,
}
}
@@ -1235,6 +1423,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.write_format_control(path, data).await,
Disk::Remote(remote_disk) => remote_disk.write_format_control(path, data).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.write_format_control(path, data).await,
}
}
@@ -1248,6 +1438,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.compare_and_update_file(volume, path, expected, replacement).await,
Disk::Remote(remote_disk) => remote_disk.compare_and_update_file(volume, path, expected, replacement).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.compare_and_update_file(volume, path, expected, replacement).await,
}
}
@@ -1255,6 +1447,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.has_replacement_mount_lease(),
Disk::Remote(remote_disk) => remote_disk.has_replacement_mount_lease(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.has_replacement_mount_lease(),
}
}
@@ -1263,6 +1457,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_all(volume, path).await,
Disk::Remote(remote_disk) => remote_disk.read_all(volume, path).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_all(volume, path).await,
}
}
@@ -1271,6 +1467,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.disk_info(opts).await,
Disk::Remote(remote_disk) => remote_disk.disk_info(opts).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.disk_info(opts).await,
}
}
@@ -1278,6 +1476,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.start_scan(),
Disk::Remote(remote_disk) => remote_disk.start_scan(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.start_scan(),
}
}
@@ -1285,6 +1485,8 @@ impl DiskAPI for Disk {
match self {
Disk::Local(local_disk) => local_disk.read_metadata(volume, path).await,
Disk::Remote(remote_disk) => remote_disk.read_metadata(volume, path).await,
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.read_metadata(volume, path).await,
}
}
}
@@ -1309,6 +1511,11 @@ impl Disk {
.delete_with_scanner_publication_lease(volume, path, opts, scanner_publication_lease_token)
.await
}
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => {
let _ = (scanner_publication_lease_token, external_guard);
sim_disk.delete(volume, path, opts).await
}
}
}
@@ -1332,6 +1539,12 @@ impl Disk {
drop(namespace_owner);
result
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
let result = disk.delete_version(volume, path, fi, force_del_marker, opts).await;
drop(namespace_owner);
result
}
}
}
@@ -1349,6 +1562,12 @@ impl Disk {
drop(namespace_owner);
result
}
#[cfg(feature = "dst")]
Self::Sim(disk) => {
let result = disk.delete(volume, path, opts).await;
drop(namespace_owner);
result
}
}
}
@@ -1368,6 +1587,11 @@ impl Disk {
.await
}
Self::Remote(disk) => disk.delete_version(volume, path, fi, false, opts).await,
#[cfg(feature = "dst")]
Self::Sim(disk) => {
let _owner = namespace_owner;
disk.delete_version(volume, path, fi, false, opts).await
}
}
}
@@ -1409,6 +1633,15 @@ impl Disk {
.rename_data_observed(src_volume, src_path, fi, dst_volume, dst_path, guards)
.await
}
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => {
let _guards = guards;
RenameDataObservation::unknown(
sim_disk
.rename_data(src_volume, src_path, fi.clone(), dst_volume, dst_path)
.await,
)
}
}
}
@@ -1462,6 +1695,13 @@ impl Disk {
)
.await
}
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => {
let _ = (scanner_publication_lease_token, external_guard);
sim_disk
.rename_data(src_volume, src_path, fi.clone(), dst_volume, dst_path)
.await
}
}
}
}
@@ -1474,6 +1714,8 @@ impl Disk {
match self {
Disk::Local(_) => Ok(None),
Disk::Remote(remote_disk) => remote_disk.ns_scanner_progress_capability().await,
#[cfg(feature = "dst")]
Disk::Sim(_) => Ok(None),
}
}
@@ -1481,6 +1723,8 @@ impl Disk {
match self {
Disk::Local(_) => Ok(None),
Disk::Remote(remote_disk) => remote_disk.ns_scanner_server_epoch().await,
#[cfg(feature = "dst")]
Disk::Sim(_) => Ok(None),
}
}
@@ -1488,6 +1732,8 @@ impl Disk {
match self {
Disk::Remote(remote_disk) => remote_disk.open_ns_scanner_stream(request).await,
Disk::Local(_) => Err(Error::other("namespace scanner stream requires a remote disk")),
#[cfg(feature = "dst")]
Disk::Sim(_) => Err(Error::other("namespace scanner stream requires a remote disk")),
}
}
@@ -1495,6 +1741,14 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.runtime_state(),
Disk::Remote(remote_disk) => remote_disk.runtime_state(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => {
if sim_disk.sim().is_offline() {
RuntimeDriveHealthState::Offline
} else {
RuntimeDriveHealthState::Online
}
}
}
}
@@ -1502,6 +1756,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.is_faulty(),
Disk::Remote(remote_disk) => remote_disk.is_faulty(),
#[cfg(feature = "dst")]
Disk::Sim(_) => false,
}
}
@@ -1511,6 +1767,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => Some(local_disk.retirement_token()),
Disk::Remote(_) => None,
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -1518,6 +1776,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.offline_duration_secs(),
Disk::Remote(remote_disk) => remote_disk.offline_duration_secs(),
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -1525,6 +1785,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.last_capacity_snapshot(),
Disk::Remote(remote_disk) => remote_disk.last_capacity_snapshot(),
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -1532,6 +1794,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => Some(local_disk.metrics_snapshot()),
Disk::Remote(_) => None,
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -1540,6 +1804,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.health_check_enabled_for_test(),
Disk::Remote(remote_disk) => remote_disk.health_check_enabled_for_test(),
#[cfg(feature = "dst")]
Disk::Sim(_) => false,
}
}
@@ -1547,6 +1813,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.record_capacity_probe(total, used, free),
Disk::Remote(remote_disk) => remote_disk.record_capacity_probe(total, used, free),
#[cfg(feature = "dst")]
Disk::Sim(_) => {}
}
}
@@ -1555,6 +1823,10 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.force_runtime_state_for_test(state),
Disk::Remote(remote_disk) => remote_disk.force_runtime_state_for_test(state),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => {
sim_disk.set_offline(matches!(state, RuntimeDriveHealthState::Offline));
}
}
}
@@ -1563,6 +1835,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.force_offline_for_test(),
Disk::Remote(remote_disk) => remote_disk.force_offline_for_test(),
#[cfg(feature = "dst")]
Disk::Sim(sim_disk) => sim_disk.set_offline(true),
}
}
}
@@ -1586,6 +1860,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.reset_health_for_store_init_retry(),
Disk::Remote(remote_disk) => remote_disk.reset_health_for_store_init_retry(),
#[cfg(feature = "dst")]
Disk::Sim(_) => {}
}
}
@@ -1596,6 +1872,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.enable_health_check(),
Disk::Remote(remote_disk) => remote_disk.enable_health_check(),
#[cfg(feature = "dst")]
Disk::Sim(_) => {}
}
}
@@ -1605,6 +1883,8 @@ impl Disk {
match self {
Disk::Local(w) => Some(w.get_object_path_if_local(volume, path)),
Disk::Remote(_) => None,
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -1617,6 +1897,8 @@ impl Disk {
match self {
Disk::Local(w) => Some(w.get_object_path_for_io(volume, path)),
Disk::Remote(_) => None,
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -1624,6 +1906,8 @@ impl Disk {
match self {
Disk::Local(w) => Some(w.get_bucket_path_for_io(volume)),
Disk::Remote(_) => None,
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -1634,6 +1918,8 @@ impl Disk {
match self {
Disk::Local(local_disk) => local_disk.replacement_mount_lease_root(),
Disk::Remote(_) => None,
#[cfg(feature = "dst")]
Disk::Sim(_) => None,
}
}
@@ -1643,6 +1929,8 @@ impl Disk {
match self {
Self::Local(disk) => disk.get_disk().replacement_mount(mount_roots),
Self::Remote(_) => None,
#[cfg(feature = "dst")]
Self::Sim(_) => None,
}
}
@@ -1650,6 +1938,8 @@ impl Disk {
match self {
Self::Local(disk) => disk.get_disk().acquire_replacement_execution_lease().await,
Self::Remote(_) => Err(DiskError::other("replacement execution requires a local target")),
#[cfg(feature = "dst")]
Self::Sim(_) => Err(DiskError::other("replacement execution requires a local target")),
}
}
@@ -118,6 +118,22 @@ impl ProofVerificationContext {
}
}
/// Atomically replace the active local endpoint set on a committed live
/// topology hot-reload so removed pools' endpoints are pruned cleanly.
pub(crate) fn replace_topology(&self, candidate: &Self) -> Result<()> {
match (self, candidate) {
(Self::RpcOnly, Self::RpcOnly) => Ok(()),
(Self::Local(existing), Self::Local(next)) => {
if !Arc::ptr_eq(existing, next) {
let endpoints = next.endpoints.read().clone();
*existing.endpoints.write() = endpoints;
}
Ok(())
}
_ => Err(DiskError::InconsistentDisk),
}
}
pub(crate) fn validate_endpoint(&self, endpoint: &super::endpoint::Endpoint) -> Result<()> {
if let Self::Local(authority) = self
&& (!endpoint.is_local || !authority.endpoints.read().contains(endpoint))
@@ -165,6 +181,12 @@ pub(crate) fn bind_multipart_proof_snapshot(
return Err(DiskError::InconsistentDisk);
}
super::Disk::Remote(_) => {}
#[cfg(feature = "dst")]
super::Disk::Sim(sim) => {
if sim.disk_index() != slot {
return Err(DiskError::InconsistentDisk);
}
}
}
}
Ok(())
+103 -126
View File
@@ -15,6 +15,7 @@
use crate::erasure::codec::shard_buf::ShardBytes;
use crate::erasure::codec::workspace::RustfsCodecDecodeWorkspace;
use crate::erasure::coding::Erasure;
use crate::erasure::coding::erasure::{data_reconstruction_sources, recover_empty_payload_data_shards};
use rustfs_erasure_codec::galois_8::ReedSolomon;
use smallvec::SmallVec;
use std::io;
@@ -55,44 +56,6 @@ pub(crate) trait ErasureDecodeEngine: Send + Sync + 'static {
) -> io::Result<&'static str>;
}
fn data_shards_complete<S: ShardBytes>(shards: &[Option<S>], data_shards: usize) -> bool {
shards.len() >= data_shards && shards.iter().take(data_shards).all(Option::is_some)
}
fn recover_empty_payload_data_shards<S: ShardBytes>(
shards: &mut [Option<S>],
data_shards: usize,
parity_shards: usize,
) -> io::Result<bool> {
let expected_shards = data_shards + parity_shards;
if shards.len() != expected_shards {
return Err(io::Error::other(format!(
"invalid shard count: got {}, expected {}",
shards.len(),
expected_shards
)));
}
let mut present_shards = 0usize;
for shard in shards.iter().filter_map(Option::as_ref) {
present_shards += 1;
if !shard.is_empty() {
return Ok(false);
}
}
if present_shards == 0 || present_shards < data_shards {
return Ok(false);
}
for shard in shards.iter_mut().take(data_shards) {
if shard.is_none() {
*shard = Some(S::from(Vec::new()));
}
}
Ok(true)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LegacyDecodeWorkspace {
shard_len: usize,
@@ -163,12 +126,12 @@ impl ErasureDecodeEngine for LegacyEcDecodeEngine {
shards: &mut [Option<S>],
_workspace: &mut Self::Workspace,
) -> io::Result<&'static str> {
if data_shards_complete(shards, self.erasure.data_shards) {
return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE);
}
self.erasure.decode_data_with_reconstruction_verification(shards)?;
Ok(GET_RECONSTRUCT_OUTCOME_LEGACY_CALLED)
let reconstructed = self.erasure.decode_data_with_reconstruction_verification(shards)?;
Ok(if reconstructed {
GET_RECONSTRUCT_OUTCOME_LEGACY_CALLED
} else {
GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE
})
}
}
@@ -190,41 +153,19 @@ impl RustfsCodecDecodeEngine {
})
}
fn codec(&self) -> io::Result<Option<Arc<ReedSolomon>>> {
if self.parity_shards == 0 {
return Ok(None);
}
fn codec(&self) -> io::Result<&ReedSolomon> {
if let Some(codec) = self.codec.get() {
return Ok(Some(Arc::clone(codec)));
return Ok(codec);
}
let codec = Arc::new(
ReedSolomon::new(self.data_shards, self.parity_shards)
.map_err(|err| io::Error::other(format!("Failed to create RustFS codec decode engine: {err:?}")))?,
);
if self.codec.set(Arc::clone(&codec)).is_err() {
return Ok(self.codec.get().map(Arc::clone).or(Some(codec)));
}
Ok(Some(codec))
Ok(self.codec.get_or_init(|| codec))
}
fn needs_source_parity_verification<S: ShardBytes>(&self, shards: &[Option<S>]) -> bool {
let missing_data_source = shards.iter().take(self.data_shards).any(|shard| shard.is_none());
let available_shards = shards.iter().filter(|shard| shard.is_some()).count();
missing_data_source && available_shards > self.data_shards
}
fn verify_source_parity<S: ShardBytes>(
&self,
codec: &ReedSolomon,
shards: &[Option<S>],
needs_verification: bool,
) -> io::Result<()> {
if !needs_verification {
return Ok(());
}
fn verify_source_parity<S: ShardBytes>(&self, codec: &ReedSolomon, shards: &[Option<S>]) -> io::Result<()> {
// All slots must be present here: the verification path reconstructs
// missing parity alongside data (see `reconstruct_into`), so a `None`
// slot is an internal invariant violation, not a degraded-read state.
@@ -291,45 +232,61 @@ impl ErasureDecodeEngine for RustfsCodecDecodeEngine {
shards: &mut [Option<S>],
_workspace: &mut Self::Workspace,
) -> io::Result<&'static str> {
if data_shards_complete(shards, self.data_shards) {
let Some(available) = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)? else {
return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE);
}
if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? {
};
if recover_empty_payload_data_shards(shards, self.data_shards) {
return Ok(GET_RECONSTRUCT_OUTCOME_SKIP_EMPTY_PAYLOAD);
}
if let Some(codec) = self.codec()? {
let needs_source_parity_verification = self.needs_source_parity_verification(shards);
// The codec works on plain vectors: hand it the shard bytes (a
// move for heap buffers, a copy out of arena blocks) and put the
// results back. Reconstruction is the rare path, so the copy is
// acceptable.
let mut owned: Vec<Option<Vec<u8>>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect();
let vec_shards = owned.as_mut_slice();
if needs_source_parity_verification {
// Rebuild missing parity together with missing data so the
// shard set is complete for `verify`. Rebuilt parity is
// consistent with the reconstructed data by construction, so
// the verification below is equivalent to checking only the
// originally-present source parity — the same semantics as the
// legacy `decode_data_with_reconstruction_verification` path.
// Rebuilding only data here would leave missing parity slots
// as `None` and misreport a recoverable degraded read (for
// example one missing data shard plus one missing parity
// shard) as an inconsistent-source failure.
codec
.reconstruct_opt(vec_shards)
.map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}")))?;
} else {
codec
.reconstruct_data_opt(vec_shards)
.map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}")))?;
}
for (slot, shard) in shards.iter_mut().zip(owned) {
*slot = shard.map(S::from);
}
self.verify_source_parity(&codec, shards, needs_source_parity_verification)?;
let needs_source_parity_verification = available > self.data_shards;
let codec = self.codec()?;
let mut missing_parity: SmallVec<[usize; 16]> = SmallVec::new();
if needs_source_parity_verification {
missing_parity.extend(
shards
.iter()
.enumerate()
.skip(self.data_shards)
.filter_map(|(index, slot)| slot.is_none().then_some(index)),
);
}
// The codec works on plain vectors: hand it the shard bytes (a
// move for heap buffers, a copy out of arena blocks) and put the
// results back. Reconstruction is the rare path, so the copy is
// acceptable.
let mut owned: Vec<Option<Vec<u8>>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect();
let result = if needs_source_parity_verification {
// Rebuild missing parity together with missing data so the
// shard set is complete for `verify`. Rebuilt parity is
// consistent with the reconstructed data by construction, so
// the verification below is equivalent to checking only the
// originally-present source parity — the same semantics as the
// legacy `decode_data_with_reconstruction_verification` path.
// Rebuilding only data here would leave missing parity slots
// as `None` and misreport a recoverable degraded read (for
// example one missing data shard plus one missing parity
// shard) as an inconsistent-source failure.
codec.reconstruct_opt(owned.as_mut_slice())
} else {
codec.reconstruct_data_opt(owned.as_mut_slice())
}
.map_err(|err| io::Error::other(format!("RustFS codec reconstruct failed: {err:?}")))
.and_then(|()| {
if needs_source_parity_verification {
self.verify_source_parity(codec, &owned)?;
}
Ok(())
});
if result.is_err() {
for index in missing_parity {
owned[index] = None;
}
}
for (slot, shard) in shards.iter_mut().zip(owned) {
*slot = shard.map(S::from);
}
result?;
Ok(GET_RECONSTRUCT_OUTCOME_RUSTFS_CALLED)
}
@@ -483,7 +440,7 @@ mod tests {
fn data_shards_complete_ignores_parity_slots() {
let shards = vec![Some(vec![1]), Some(vec![2]), None];
assert!(data_shards_complete(&shards, 2));
assert_eq!(data_reconstruction_sources(&shards, 2, 1).expect("complete data"), None);
}
#[test]
@@ -491,8 +448,8 @@ mod tests {
let missing_data = vec![Some(vec![1]), None, Some(vec![3])];
let short = vec![Some(vec![1])];
assert!(!data_shards_complete(&missing_data, 2));
assert!(!data_shards_complete(&short, 2));
assert_eq!(data_reconstruction_sources(&missing_data, 2, 1).expect("valid shape"), Some(2));
assert!(data_reconstruction_sources(&short, 2, 1).is_err());
}
#[test]
@@ -585,18 +542,22 @@ mod tests {
#[test]
fn rustfs_codec_decode_engine_errors_on_insufficient_shards_like_legacy() {
let erasure = Erasure::new(4, 2, 16);
let mut legacy_shards = encoded_shards(&erasure, b"insufficient shards must fail");
let mut rustfs_shards = legacy_shards.clone();
for index in [0, 1, 2] {
legacy_shards[index] = None;
rustfs_shards[index] = None;
}
let legacy = LegacyEcDecodeEngine::new(erasure.clone());
let rustfs = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created");
for payload in [b"".as_slice(), b"insufficient shards must fail"] {
let mut original = encoded_shards(&erasure, payload);
original[..3].fill(None);
let mut legacy_shards = original.clone();
let mut rustfs_shards = original.clone();
assert!(reconstruct_with(&legacy, &mut legacy_shards).is_err());
assert!(reconstruct_with(&rustfs, &mut rustfs_shards).is_err());
let legacy_error = reconstruct_with(&legacy, &mut legacy_shards).expect_err("legacy needs quorum");
let rustfs_error = reconstruct_with(&rustfs, &mut rustfs_shards).expect_err("native needs quorum");
assert_eq!(legacy_error.kind(), io::ErrorKind::InvalidData);
assert_eq!(rustfs_error.kind(), io::ErrorKind::InvalidData);
assert_eq!(legacy_shards, original);
assert_eq!(rustfs_shards, original);
}
assert!(!rustfs.codec_is_initialized());
}
#[test]
@@ -653,12 +614,14 @@ mod tests {
panic!("test parity shard should be present");
};
corrupt_parity[0] ^= 0x80;
let source_parity = shards[erasure.data_shards..].to_vec();
let engine = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created");
let err = reconstruct_with(&engine, &mut shards).expect_err("corrupt surviving parity must still be rejected");
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(err.to_string().contains("inconsistent read source shards"));
assert_eq!(&shards[erasure.data_shards..], source_parity);
}
#[test]
@@ -774,19 +737,33 @@ mod tests {
}
#[test]
fn rustfs_codec_decode_engine_returns_called_without_parity_codec() {
fn streaming_decode_engines_reject_incomplete_zero_parity_shards() {
fn check<E: ErasureDecodeEngine>(engine: &E) {
let mut workspace = engine.prepare_workspace(4).expect("workspace should be prepared");
for malformed in [
vec![None, Some(vec![2; 4])],
vec![Some(vec![2; 4]); 3],
vec![None, Some(Vec::new())],
] {
let mut shards = malformed.clone();
let error = engine
.reconstruct_into(&mut shards, &mut workspace)
.expect_err("invalid shard set");
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(shards, malformed);
}
let mut shards = vec![Some(vec![2; 4]); 2];
let outcome = engine.reconstruct_into(&mut shards, &mut workspace).expect("complete data");
assert_eq!(outcome, GET_RECONSTRUCT_OUTCOME_SKIP_DATA_COMPLETE);
assert_eq!(shards, vec![Some(vec![2; 4]); 2]);
}
let erasure = Erasure::new(2, 0, 16);
let engine = RustfsCodecDecodeEngine::new(&erasure).expect("engine should be created");
let mut workspace = engine.prepare_workspace(4).expect("workspace should be prepared");
let mut shards = vec![None, Some(vec![2, 2, 2, 2])];
let outcome = engine
.reconstruct_into(&mut shards, &mut workspace)
.expect("zero parity engine should not allocate codec");
assert_eq!(outcome, GET_RECONSTRUCT_OUTCOME_RUSTFS_CALLED);
assert!(shards[0].is_none());
check(&engine);
assert!(!engine.codec_is_initialized());
check(&LegacyEcDecodeEngine::new(erasure));
}
#[test]
@@ -4396,6 +4396,37 @@ mod tests {
}
}
#[tokio::test]
async fn zero_parity_full_and_prefix_reads_reject_an_incomplete_stripe_before_output() {
let block_size = 64;
for data_shards in [1, 4] {
let erasure = Erasure::new(data_shards, 0, block_size);
let shard_size = erasure.shard_size();
for length in [block_size, shard_size / 2] {
let mut output = Vec::new();
let readers = make_test_readers(data_shards, shard_size, 1, &HashAlgorithm::HighwayHash256, &[], &[]).await;
let (written, error) = erasure.decode(&mut output, readers, 0, length, block_size).await;
assert!(error.is_none(), "complete stripe: {error:?}");
assert_eq!(written, length);
assert_eq!(output.len(), length);
let last = [data_shards - 1];
for (missing, corrupt) in [(&last[..], &[][..]), (&[][..], &last[..])] {
output.clear();
let readers =
make_test_readers(data_shards, shard_size, 1, &HashAlgorithm::HighwayHash256, missing, corrupt).await;
let (written, error) = erasure.decode(&mut output, readers, 0, length, block_size).await;
assert_eq!(
error.expect("incomplete stripe must fail").to_string(),
Error::ErasureReadQuorum.to_string()
);
assert_eq!(written, 0);
assert!(output.is_empty());
}
}
}
}
#[tokio::test]
#[serial_test::serial]
async fn copy_source_below_read_quorum_fails_before_output() {
+487 -159
View File
@@ -246,6 +246,22 @@ impl LegacyReedSolomonEncoder {
return Ok(());
}
let shard_len = shards[0].len();
let (data, parity) = shards
.split_at_mut_checked(self.data_shards)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing data shards for SIMD encoding"))?;
self.with_encoded_parity(data.iter().map(|shard| &**shard), shard_len, |result| {
for (output, recovery) in parity.iter_mut().zip(result.recovery_iter()) {
output.copy_from_slice(recovery);
}
})
}
fn with_encoded_parity<'a, T>(
&self,
data: impl IntoIterator<Item = &'a [u8]>,
shard_len: usize,
use_parity: impl FnOnce(&reed_solomon_simd::EncoderResult<'_>) -> T,
) -> io::Result<T> {
let cached_encoder = self
.encoder_cache
.write()
@@ -274,7 +290,7 @@ impl LegacyReedSolomonEncoder {
},
)?;
let encoder = &mut workspace.codec;
for (i, shard) in shards.iter().enumerate().take(self.data_shards) {
for (i, shard) in data.into_iter().enumerate() {
encoder
.add_original_shard(shard)
.map_err(|e| io::Error::other(format!("Failed to add shard {i}: {e:?}")))?;
@@ -282,11 +298,7 @@ impl LegacyReedSolomonEncoder {
let result = encoder
.encode()
.map_err(|e| io::Error::other(format!("SIMD encoding failed: {e:?}")))?;
for (i, recovery_shard) in result.recovery_iter().enumerate() {
if i + self.data_shards < shards.len() {
shards[i + self.data_shards].copy_from_slice(recovery_shard);
}
}
let output = use_parity(&result);
drop(result);
if self.should_cache_workspace(shard_len) {
let mut cache = self
@@ -297,20 +309,10 @@ impl LegacyReedSolomonEncoder {
*cache = Some(workspace);
}
}
Ok(())
Ok(output)
}
fn reconstruct_data<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? {
return Ok(());
}
// Every data shard present: nothing to rebuild. The conversions
// below would copy each shard out of its arena block and hand back
// heap buffers, which also defeats the zero-copy emit.
if shards.iter().take(self.data_shards).all(Option::is_some) {
return Ok(());
}
fn reconstruct_missing_data<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
let shard_len = shards
.iter()
.find_map(|s| s.as_ref().map(|v| v.len()))
@@ -361,14 +363,12 @@ impl LegacyReedSolomonEncoder {
.decode()
.map_err(|e| io::Error::other(format!("SIMD decode error: {e:?}")))?;
for (i, shard_opt) in shards.iter_mut().enumerate() {
if shard_opt.is_none() && i < self.data_shards {
for (restored_index, restored_data) in result.restored_original_iter() {
if restored_index == i {
*shard_opt = Some(S::from(restored_data.to_vec()));
break;
}
}
for (index, shard) in shards[..self.data_shards].iter_mut().enumerate() {
if shard.is_none() {
let restored = result
.restored_original(index)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing data shard after SIMD reconstruction"))?;
*shard = Some(S::from(restored.to_vec()));
}
}
@@ -387,11 +387,6 @@ impl LegacyReedSolomonEncoder {
Ok(())
}
fn reconstruct<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
self.reconstruct_data(shards)?;
self.encode_parity(shards)
}
fn verify(&self, shards: &[&[u8]]) -> io::Result<bool> {
let expected_shards = self.data_shards + self.parity_shards;
if shards.len() != expected_shards {
@@ -430,6 +425,25 @@ impl LegacyReedSolomonEncoder {
fn encode_parity<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
encode_parity_shards(shards, self.data_shards, self.parity_shards, |shards| self.encode(shards))
}
fn verify_and_rebuild_parity<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<Option<usize>> {
verify_rebuilt_parity(shards, self.data_shards, |data, parity, shard_len| {
self.with_encoded_parity(data.iter().copied(), shard_len, |result| {
let mismatch = parity
.iter()
.zip(result.recovery_iter())
.position(|(slot, rebuilt)| slot.as_ref().is_some_and(|source| source.as_slice() != rebuilt));
if mismatch.is_none() {
for (slot, rebuilt) in parity.iter_mut().zip(result.recovery_iter()) {
if slot.is_none() {
*slot = Some(S::from(rebuilt.to_vec()));
}
}
}
mismatch
})
})
}
}
/// Reed-Solomon encoder using rustfs-erasure-codec
@@ -485,31 +499,36 @@ impl ReedSolomonEncoder {
}
/// Reconstruct missing data shards.
///
/// # Errors
/// Returns an error for incorrect shard counts, insufficient source
/// shards, or failed reconstruction.
pub fn reconstruct_data<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
if recover_empty_payload_data_shards(shards, self.data_shards, self.parity_shards)? {
let sources = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)?;
if self.parity_shards == 0 {
return Ok(());
}
// Every data shard present: nothing to rebuild. The conversions
// below would copy each shard out of its arena block and hand back
// heap buffers, which also defeats the zero-copy emit.
if shards.iter().take(self.data_shards).all(Option::is_some) {
return Ok(());
let rs = self
.encoder
.as_deref()
.ok_or_else(|| io::Error::other("missing Reed-Solomon encoder"))?;
if sources.is_some() && !recover_empty_payload_data_shards(shards, self.data_shards) {
Self::reconstruct_missing_data(rs, shards)?;
}
Ok(())
}
if let Some(ref rs) = self.encoder {
// The codec works on plain vectors: a move for vectors, a copy out
// of arena blocks (reconstruction is the rare path).
let mut owned: Vec<Option<Vec<u8>>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect();
let result = rs
.reconstruct_data(owned.as_mut_slice())
.map_err(|e| io::Error::other(format!("Reed-Solomon reconstruct failed: {e:?}")));
for (slot, shard) in shards.iter_mut().zip(owned) {
*slot = shard.map(S::from);
}
result
} else {
Ok(())
fn reconstruct_missing_data<S: ShardBytes>(rs: &ReedSolomon, shards: &mut [Option<S>]) -> io::Result<()> {
// The codec works on plain vectors: a move for vectors, a copy out
// of arena blocks (reconstruction is the rare path).
let mut owned: Vec<Option<Vec<u8>>> = shards.iter_mut().map(|slot| slot.take().map(S::into_vec)).collect();
let result = rs
.reconstruct_data(owned.as_mut_slice())
.map_err(|e| io::Error::other(format!("Reed-Solomon reconstruct failed: {e:?}")));
for (slot, shard) in shards.iter_mut().zip(owned) {
*slot = shard.map(S::from);
}
result
}
/// Reconstruct missing data shards and regenerate parity shards.
@@ -544,6 +563,44 @@ impl ReedSolomonEncoder {
fn encode_parity<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
encode_parity_shards(shards, self.data_shards, self.parity_shards, |shards| self.encode(shards))
}
fn verify_and_rebuild_parity<S: ShardBytes>(&self, rs: &ReedSolomon, shards: &mut [Option<S>]) -> io::Result<Option<usize>> {
verify_rebuilt_parity(shards, self.data_shards, |data, parity, shard_len| {
let missing_count = parity.iter().filter(|slot| slot.is_none()).count();
let source_count = parity.len() - missing_count;
let scratch_len = shard_len.checked_mul(source_count).ok_or(io::ErrorKind::OutOfMemory)?;
let mut scratch = vec![0; scratch_len];
let mut rebuilt: SmallVec<[S; 16]> = (0..missing_count).map(|_| S::from(vec![0; shard_len])).collect();
let mut source_outputs = scratch.chunks_exact_mut(shard_len);
let mut missing_outputs = rebuilt.iter_mut().map(ShardBytes::as_mut_slice);
let mut outputs: SmallVec<[&mut [u8]; 16]> = SmallVec::with_capacity(parity.len());
for slot in parity.iter() {
let output = if slot.is_some() {
source_outputs.next()
} else {
missing_outputs.next()
};
outputs.push(output.ok_or_else(|| io::Error::other("missing parity verification output"))?);
}
rs.encode_sep(data, &mut outputs)
.map_err(|error| io::Error::other(format!("Reed-Solomon encode failed: {error:?}")))?;
drop(outputs);
let mismatch = parity
.iter()
.enumerate()
.filter_map(|(index, slot)| slot.as_ref().map(|source| (index, source)))
.zip(scratch.chunks_exact(shard_len))
.find_map(|((index, source), expected)| (source.as_slice() != expected).then_some(index));
if mismatch.is_none() {
for (slot, shard) in parity.iter_mut().filter(|slot| slot.is_none()).zip(rebuilt) {
*slot = Some(shard);
}
}
Ok(mismatch)
})
}
}
fn cached_modern_reed_solomon(data_shards: usize, parity_shards: usize) -> Result<Arc<ReedSolomon>, rustfs_erasure_codec::Error> {
@@ -666,29 +723,79 @@ where
encode(shard_refs)
}
fn recover_empty_payload_data_shards<S: ShardBytes>(
// Keep surviving parity read-only. Backends can compare against their own
// encoding workspace or generate into scratch without copying the sources.
fn verify_rebuilt_parity<S: ShardBytes>(
shards: &mut [Option<S>],
data_shards: usize,
parity_shards: usize,
) -> io::Result<bool> {
let expected_shards = data_shards + parity_shards;
if shards.len() != expected_shards {
return Err(io::Error::other(format!(
"invalid shard count: got {}, expected {}",
shards.len(),
expected_shards
)));
}
let mut has_present_shard = false;
for shard in shards.iter().filter_map(|shard| shard.as_ref()) {
has_present_shard = true;
if !shard.is_empty() {
return Ok(false);
rebuild: impl FnOnce(&[&[u8]], &mut [Option<S>], usize) -> io::Result<Option<usize>>,
) -> io::Result<Option<usize>> {
let (data, parity) = shards.split_at_mut(data_shards);
let shard_len = data
.first()
.and_then(Option::as_ref)
.map(ShardBytes::len)
.ok_or_else(|| io::Error::other("missing data shard after reconstruction"))?;
let mut inputs: SmallVec<[&[u8]; 16]> = SmallVec::with_capacity(data.len());
for slot in data {
let shard = slot
.as_ref()
.ok_or_else(|| io::Error::other("missing data shard after reconstruction"))?;
if shard.len() != shard_len {
return Err(io::Error::other("inconsistent shard length after reconstruction"));
}
inputs.push(shard.as_slice());
}
if !has_present_shard {
return Ok(false);
if parity.iter().flatten().any(|shard| shard.len() != shard_len) {
return Err(io::Error::other("inconsistent shard length after reconstruction"));
}
if shard_len == 0 {
for slot in parity {
slot.get_or_insert_with(|| S::from(Vec::new()));
}
return Ok(None);
}
rebuild(&inputs, parity, shard_len)
}
/// Returns the available source count when any data shard needs reconstruction.
/// Complete data returns `None` without scanning the parity slots.
pub(crate) fn data_reconstruction_sources<S>(
shards: &[Option<S>],
data_shards: usize,
parity_shards: usize,
) -> io::Result<Option<usize>> {
let expected = data_shards.checked_add(parity_shards).ok_or(io::ErrorKind::InvalidData)?;
if shards.len() != expected {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("invalid shard count: got {}, expected {expected}", shards.len()),
));
}
if shards[..data_shards].iter().all(Option::is_some) {
return Ok(None);
}
if parity_shards == 0 {
return Err(io::Error::new(io::ErrorKind::InvalidData, "missing data shard with zero parity"));
}
let available = shards.iter().flatten().count();
if available < data_shards {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"insufficient source shards to reconstruct data",
));
}
Ok(Some(available))
}
/// Recovers an empty stripe after its source quorum has been established.
pub(crate) fn recover_empty_payload_data_shards<S: ShardBytes>(shards: &mut [Option<S>], data_shards: usize) -> bool {
let mut present = shards.iter().flatten();
let Some(first) = present.next() else {
return false;
};
if !first.is_empty() || present.any(|shard| !shard.is_empty()) {
return false;
}
for shard in shards.iter_mut().take(data_shards) {
@@ -696,7 +803,22 @@ fn recover_empty_payload_data_shards<S: ShardBytes>(
*shard = Some(S::from(Vec::new()));
}
}
Ok(true)
true
}
#[derive(Clone, Copy)]
enum DecodeMode {
Data,
All,
Verified,
VerifiedLockstep,
}
fn validate_decoder_geometry(expected: (usize, usize), actual: (usize, usize)) -> io::Result<()> {
if expected != actual {
return Err(io::Error::new(io::ErrorKind::InvalidData, "erasure decoder geometry mismatch"));
}
Ok(())
}
/// Erasure coding utility for data reliability using Reed-Solomon codes.
@@ -1001,106 +1123,110 @@ impl Erasure {
/// # Arguments
/// * `shards` - Mutable slice of optional shard data. Missing shards should be `None`.
///
/// # Returns
/// Ok if reconstruction succeeds, error otherwise.
/// # Errors
/// Returns an error for an incorrect shard count, insufficient source
/// shards, or failed reconstruction.
#[hotpath::measure(impl_type = "Erasure")]
pub fn decode_data<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
if self.parity_shards > 0 {
if self.uses_legacy {
if let Some(encoder) = self.legacy_encoder.as_ref() {
encoder.reconstruct_data(shards)?;
} else {
warn!("parity_shards > 0, uses_legacy but legacy_encoder is None");
}
} else if let Some(encoder) = self.encoder.as_ref() {
encoder.reconstruct_data(shards)?;
} else {
warn!("parity_shards > 0, but encoder is None");
}
}
Ok(())
self.decode_shards(shards, DecodeMode::Data).map(drop)
}
/// Decode and reconstruct missing data shards, then regenerate parity shards.
///
/// # Errors
/// Returns an error for an incorrect shard count, failed reconstruction,
/// or failed parity generation.
#[hotpath::measure(impl_type = "Erasure")]
pub fn decode_data_and_parity<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
if self.parity_shards > 0 {
if self.uses_legacy {
if let Some(encoder) = self.legacy_encoder.as_ref() {
encoder.reconstruct(shards)?;
} else {
warn!("parity_shards > 0, uses_legacy but legacy_encoder is None");
}
} else if let Some(encoder) = self.encoder.as_ref() {
encoder.reconstruct(shards)?;
} else {
warn!("parity_shards > 0, but encoder is None");
}
}
Ok(())
self.decode_shards(shards, DecodeMode::All).map(drop)
}
pub(crate) fn decode_data_with_reconstruction_verification<S: ShardBytes>(&self, shards: &mut [Option<S>]) -> io::Result<()> {
self.decode_data_with_reconstruction_verification_policy(shards, false)
/// Returns whether any data shard had to be reconstructed.
#[hotpath::measure(impl_type = "Erasure")]
pub(crate) fn decode_data_with_reconstruction_verification<S: ShardBytes>(
&self,
shards: &mut [Option<S>],
) -> io::Result<bool> {
self.decode_shards(shards, DecodeMode::Verified)
}
#[hotpath::measure(impl_type = "Erasure")]
pub(crate) fn decode_data_with_reconstruction_verification_for_lockstep<S: ShardBytes>(
&self,
shards: &mut [Option<S>],
) -> io::Result<()> {
self.decode_data_with_reconstruction_verification_policy(shards, true)
) -> io::Result<bool> {
self.decode_shards(shards, DecodeMode::VerifiedLockstep)
}
fn decode_data_with_reconstruction_verification_policy<S: ShardBytes>(
&self,
shards: &mut [Option<S>],
require_surplus_source: bool,
) -> io::Result<()> {
let missing_data_source = shards.iter().take(self.data_shards).any(|shard| shard.is_none());
let available_shards = shards.iter().filter(|shard| shard.is_some()).count();
if require_surplus_source && missing_data_source && available_shards == self.data_shards {
fn decode_shards<S: ShardBytes>(&self, shards: &mut [Option<S>], mode: DecodeMode) -> io::Result<bool> {
let sources = data_reconstruction_sources(shards, self.data_shards, self.parity_shards)?;
if self.parity_shards == 0 {
return Ok(false);
}
if matches!(mode, DecodeMode::VerifiedLockstep) && sources == Some(self.data_shards) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"insufficient source shards to verify reconstructed data",
));
}
let source_parity = if missing_data_source && available_shards > self.data_shards {
shards
.iter()
.enumerate()
.skip(self.data_shards)
.filter_map(|(index, shard)| shard.as_ref().map(|shard| (index, shard.as_slice().to_vec())))
.collect::<Vec<_>>()
let verify_parity = matches!(mode, DecodeMode::Verified | DecodeMode::VerifiedLockstep)
&& sources.is_some_and(|available| available > self.data_shards);
let missing = sources.is_some();
let needs_decode = |shards: &mut [Option<S>]| missing && !recover_empty_payload_data_shards(shards, self.data_shards);
let geometry = (self.data_shards, self.parity_shards);
let mismatch = if self.uses_legacy {
let encoder = self
.legacy_encoder
.as_ref()
.ok_or_else(|| io::Error::other("missing legacy erasure encoder"))?;
validate_decoder_geometry(geometry, (encoder.data_shards, encoder.parity_shards))?;
if needs_decode(shards) {
encoder.reconstruct_missing_data(shards)?;
}
if verify_parity {
encoder.verify_and_rebuild_parity(shards)?
} else {
if matches!(mode, DecodeMode::All) {
encoder.encode_parity(shards)?;
}
None
}
} else {
Vec::new()
let encoder = self
.encoder
.as_ref()
.ok_or_else(|| io::Error::other("missing erasure encoder"))?;
validate_decoder_geometry(geometry, (encoder.data_shards, encoder.parity_shards))?;
let rs = encoder
.encoder
.as_deref()
.ok_or_else(|| io::Error::other("missing Reed-Solomon encoder"))?;
if needs_decode(shards) {
ReedSolomonEncoder::reconstruct_missing_data(rs, shards)?;
}
if verify_parity {
encoder.verify_and_rebuild_parity(rs, shards)?
} else {
if matches!(mode, DecodeMode::All) {
encoder.encode_parity(shards)?;
}
None
}
};
if source_parity.is_empty() {
return self.decode_data(shards);
if let Some(index) = mismatch {
let index = self.data_shards + index;
warn!(
shard_index = index,
data_shards = self.data_shards,
parity_shards = self.parity_shards,
"erasure decode rejected inconsistent read source shards"
);
return Err(io::Error::new(io::ErrorKind::InvalidData, "inconsistent read source shards"));
}
self.decode_data_and_parity(shards)?;
for (index, source) in source_parity {
let Some(rebuilt) = shards[index].as_ref() else {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"missing rebuilt parity shard after read verification",
));
};
if rebuilt.as_slice() != source.as_slice() {
warn!(
shard_index = index,
data_shards = self.data_shards,
parity_shards = self.parity_shards,
"erasure decode rejected inconsistent read source shards"
);
return Err(io::Error::new(io::ErrorKind::InvalidData, "inconsistent read source shards"));
}
}
Ok(())
Ok(missing)
}
pub(crate) fn verify_data_and_parity<S: ShardBytes>(&self, shards: &[Option<S>]) -> io::Result<bool> {
@@ -1341,7 +1467,7 @@ mod tests {
let mut decoded = vec![None, Some(shards[1].clone()), Some(shards[2].clone())];
let (resources, _) = test_resource_units(1);
with_optional_resource_unit(Some(resources.with_memory_budget(memory.clone())), async {
codec.reconstruct_data(&mut decoded).expect("accounted decoder");
codec.reconstruct_missing_data(&mut decoded).expect("accounted decoder");
})
.await;
assert_eq!(decoded[0].as_deref(), Some(shards[0].as_slice()));
@@ -1896,10 +2022,7 @@ mod tests {
assert!(err.to_string().contains("inconsistent shard length"));
let mut no_present_empty_payload: Vec<Option<Vec<u8>>> = vec![None, None, None];
assert!(
!recover_empty_payload_data_shards(&mut no_present_empty_payload, 2, 1)
.expect("all-missing empty payload marker should not be synthesized")
);
assert!(!recover_empty_payload_data_shards(&mut no_present_empty_payload, 2));
}
#[test]
@@ -2113,6 +2236,185 @@ mod tests {
}
}
#[test]
fn zero_parity_reconstruction_requires_exact_geometry_and_all_data() {
type Decode<'a> = (&'a str, &'a dyn Fn(&mut [Option<Vec<u8>>]) -> io::Result<()>);
for data_shards in [1, 4] {
for uses_legacy in [false, true] {
let erasure = Erasure::new_with_options(data_shards, 0, 64, uses_legacy);
let encoder = ReedSolomonEncoder::new(data_shards, 0).expect("zero parity encoder");
let decoders: [Decode<'_>; 6] = [
("data", &|shards| erasure.decode_data(shards)),
("data and parity", &|shards| erasure.decode_data_and_parity(shards)),
("verified", &|shards| {
erasure.decode_data_with_reconstruction_verification(shards).map(drop)
}),
("lockstep", &|shards| {
erasure
.decode_data_with_reconstruction_verification_for_lockstep(shards)
.map(drop)
}),
("direct data", &|shards| encoder.reconstruct_data(shards)),
("direct data and parity", &|shards| encoder.reconstruct(shards)),
];
let complete = vec![Some(vec![42]); data_shards];
let empty_payload = vec![Some(Vec::new()); data_shards];
let mut missing = complete.clone();
missing[data_shards - 1] = None;
let mut missing_from_empty = empty_payload.clone();
missing_from_empty[data_shards - 1] = None;
let mut overlong = complete.clone();
overlong.push(None);
for (name, decode) in decoders {
for malformed in [&complete[..data_shards - 1], &overlong, &missing, &missing_from_empty] {
let mut shards = malformed.to_vec();
let error = decode(&mut shards).expect_err(name);
assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{name}: {error}");
assert_eq!(shards, malformed, "{name} must reject before mutation");
}
for expected in [&complete, &empty_payload] {
let mut shards = expected.clone();
decode(&mut shards).expect(name);
assert_eq!(&shards, expected, "{name} must preserve complete data");
}
}
}
}
}
#[test]
fn complete_data_decode_does_not_read_payloads() {
struct Present;
impl AsRef<[u8]> for Present {
fn as_ref(&self) -> &[u8] {
panic!("complete data must not enter payload inspection");
}
}
impl AsMut<[u8]> for Present {
fn as_mut(&mut self) -> &mut [u8] {
panic!("complete data must not be rewritten");
}
}
impl From<Vec<u8>> for Present {
fn from(_: Vec<u8>) -> Self {
panic!("complete data must not allocate replacement shards");
}
}
impl ShardBytes for Present {
fn into_vec(self) -> Vec<u8> {
panic!("complete data must not be copied");
}
}
for uses_legacy in [false, true] {
let erasure = Erasure::new_with_options(2, 2, 64, uses_legacy);
let mut shards = [Some(Present), Some(Present), None, Some(Present)];
erasure.decode_data(&mut shards).expect("complete data");
assert!(
!erasure
.decode_data_with_reconstruction_verification(&mut shards)
.expect("complete data"),
"missing parity must not trigger data reconstruction"
);
}
}
#[test]
fn reconstruction_errors_when_selected_encoder_is_absent() {
for uses_legacy in [false, true] {
let mut erasure = Erasure::new_with_options(2, 1, 64, uses_legacy);
let mut shards = vec![Some(vec![1]); 3];
erasure.encoder = None;
erasure.legacy_encoder = None;
assert_eq!(
erasure.decode_data(&mut shards).expect_err("missing encoder").kind(),
io::ErrorKind::Other
);
assert_eq!(
erasure
.decode_data_and_parity(&mut shards)
.expect_err("missing encoder")
.kind(),
io::ErrorKind::Other
);
assert_eq!(
erasure
.decode_data_with_reconstruction_verification(&mut shards)
.expect_err("missing encoder")
.kind(),
io::ErrorKind::Other
);
}
}
#[test]
fn reconstruction_rejects_mismatched_decoder_geometry() {
for uses_legacy in [false, true] {
let mut erasure = Erasure::new_with_options(2, 2, 64, uses_legacy);
erasure.data_shards = 3;
erasure.parity_shards = 1;
let original = [Some(vec![1]), Some(vec![2]), Some(vec![3]), Some(vec![4])];
let mut shards = original.clone();
let error = erasure
.decode_data_and_parity(&mut shards)
.expect_err("encoder dimensions differ");
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(shards, original);
}
}
#[test]
fn reconstruction_requires_read_quorum_even_for_empty_shards() {
let below_quorum = [Some(Vec::new()), None, None];
let exact_quorum = [None, Some(Vec::new()), Some(Vec::new())];
for uses_legacy in [false, true] {
let erasure = Erasure::new_with_options(2, 1, 64, uses_legacy);
for mode in [
DecodeMode::Data,
DecodeMode::All,
DecodeMode::Verified,
DecodeMode::VerifiedLockstep,
] {
let mut shards = below_quorum.clone();
let error = erasure
.decode_shards(&mut shards, mode)
.expect_err("one empty source is below quorum");
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(shards, below_quorum);
}
for mode in [DecodeMode::Data, DecodeMode::All, DecodeMode::Verified] {
let mut shards = exact_quorum.clone();
assert!(
erasure
.decode_shards(&mut shards, mode)
.expect("two empty sources meet quorum")
);
assert_eq!(shards, [Some(Vec::new()), Some(Vec::new()), Some(Vec::new())]);
}
let mut shards = exact_quorum.clone();
let error = erasure
.decode_data_with_reconstruction_verification_for_lockstep(&mut shards)
.expect_err("lockstep requires a surplus source for reconstruction");
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(shards, exact_quorum);
}
let encoder = ReedSolomonEncoder::new(2, 1).expect("2+1 encoder");
let mut shards = below_quorum.clone();
let error = encoder
.reconstruct_data(&mut shards)
.expect_err("a direct reconstruction also needs quorum");
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert_eq!(shards, below_quorum);
let mut shards = exact_quorum;
encoder
.reconstruct_data(&mut shards)
.expect("direct empty reconstruction at quorum");
assert_eq!(shards, [Some(Vec::new()), Some(Vec::new()), Some(Vec::new())]);
}
#[test]
fn decode_data_and_parity_rejects_wrong_shard_count() {
for uses_legacy in [false, true] {
@@ -2132,18 +2434,44 @@ mod tests {
#[test]
fn decode_data_with_verification_rejects_corrupt_surplus_parity() {
let erasure = Erasure::new(3, 2, 128);
let data = b"verified reads must fail closed on stale surplus parity";
let encoded = erasure.encode_data(data).expect("encode should succeed");
let mut shards = optional_shards(&encoded);
shards[1] = None;
shards[erasure.data_shards].as_mut().expect("parity shard should be present")[0] ^= 0x7d;
for uses_legacy in [false, true] {
let erasure = Erasure::new_with_options(3, 3, 128, uses_legacy);
let data = b"verified reads must fail closed on stale surplus parity";
let encoded = erasure.encode_data(data).expect("encode should succeed");
let mut shards = optional_shards(&encoded);
shards[1] = None;
shards[erasure.data_shards] = None;
shards[erasure.data_shards + 1].as_mut().expect("source parity")[0] ^= 0x7d;
let source_parity = shards[erasure.data_shards..].to_vec();
let err = erasure
.decode_data_with_reconstruction_verification(&mut shards)
.expect_err("verified decode must reject inconsistent parity");
let err = erasure
.decode_data_with_reconstruction_verification(&mut shards)
.expect_err("verified decode must reject inconsistent parity");
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert_eq!(&shards[erasure.data_shards..], source_parity);
}
}
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
#[test]
fn verified_decode_restores_missing_parity_with_surplus_sources() {
for uses_legacy in [false, true] {
let erasure = Erasure::new_with_options(4, 3, 128, uses_legacy);
for payload in [b"".as_slice(), b"reconstruct both a data shard and a parity shard"] {
let encoded = erasure.encode_data(payload).expect("encode should succeed");
let expected = optional_shards(&encoded);
let mut shards = expected.clone();
shards[1] = None;
shards[erasure.data_shards + 1] = None;
assert!(
erasure
.decode_data_with_reconstruction_verification(&mut shards)
.expect("enough sources"),
"data reconstruction must be reported"
);
assert_eq!(shards, expected);
}
}
}
#[test]
+6
View File
@@ -93,6 +93,12 @@ pub fn mark_get_metadata_read_version_coalescing_service_ready() {
runtime::global::mark_get_metadata_read_version_coalescing_service_ready();
}
#[cfg(feature = "fuzzing")]
pub mod fuzz_exports {
pub use crate::erasure::coding::{BitrotReader, BitrotWriter, ShardChunkRead, ShardSource, bitrot_verify};
pub use rustfs_gateway_types::{cors_tagging, persistence};
}
#[cfg(test)]
mod rio_tests {
#[test]
+28 -8
View File
@@ -21,6 +21,7 @@ use crate::{
services::tier::tier::TierConfigMgr,
store::ECStore,
};
use arc_swap::ArcSwapOption;
use lazy_static::lazy_static;
use rustfs_lock::client::LockClient;
use std::{
@@ -64,7 +65,7 @@ pub(crate) fn get_metadata_read_version_coalescing_service_ready() -> bool {
// forward to the current instance's context.
lazy_static! {
static ref GLOBAL_RUSTFS_PORT: OnceLock<u16> = OnceLock::new();
pub static ref GLOBAL_OBJECT_API: OnceLock<Arc<ECStore>> = OnceLock::new();
pub static ref GLOBAL_OBJECT_API: ArcSwapOption<ECStore> = ArcSwapOption::empty();
pub static ref GLOBAL_ROOT_DISK_THRESHOLD: RwLock<u64> = RwLock::new(0);
pub static ref GLOBAL_LIFECYCLE_SYS: Arc<LifecycleSys> = LifecycleSys::new();
pub static ref GLOBAL_BOOT_TIME: OnceCell<SystemTime> = OnceCell::new();
@@ -72,7 +73,7 @@ lazy_static! {
pub static ref GLOBAL_LOCAL_NODE_NAME_HEX_FALLBACK: String =
rustfs_utils::crypto::hex(GLOBAL_LOCAL_NODE_NAME_FALLBACK.as_bytes());
pub static ref GLOBAL_LOCAL_LOCK_CLIENT: OnceLock<Arc<dyn LockClient>> = OnceLock::new();
pub static ref GLOBAL_LOCK_CLIENTS: OnceLock<HashMap<String, Arc<dyn LockClient>>> = OnceLock::new();
pub static ref GLOBAL_LOCK_CLIENTS: ArcSwapOption<HashMap<String, Arc<dyn LockClient>>> = ArcSwapOption::empty();
}
pub fn init_global_bucket_monitor(num_nodes: u64) {
@@ -176,7 +177,7 @@ pub fn get_global_tier_config_mgr() -> Arc<RwLock<TierConfigMgr>> {
/// * `Option<Arc<ECStore>>` - The global object layer instance, if set
///
pub fn new_object_layer_fn() -> Option<Arc<ECStore>> {
GLOBAL_OBJECT_API.get().cloned()
GLOBAL_OBJECT_API.load_full()
}
pub type ObjectStoreResolver = dyn Fn() -> Option<Arc<ECStore>> + Send + Sync + 'static;
@@ -215,9 +216,17 @@ pub(crate) fn current_ctx() -> Arc<InstanceContext> {
/// # Returns
/// * None
pub async fn set_object_layer(o: Arc<ECStore>) {
if GLOBAL_OBJECT_API.set(o).is_err() {
if GLOBAL_OBJECT_API.load().is_some() {
warn!("global object layer already initialized, ignoring re-initialization");
return;
}
GLOBAL_OBJECT_API.store(Some(o));
}
/// Atomically replace the process-global object store during a live topology
/// hot-reload, returning the previous generation if one was published.
pub fn replace_object_layer(o: Arc<ECStore>) -> Option<Arc<ECStore>> {
GLOBAL_OBJECT_API.swap(Some(o))
}
/// Check if the setup type is distributed erasure coding
@@ -348,14 +357,25 @@ pub fn get_global_lock_client() -> Option<Arc<dyn LockClient>> {
pub fn set_global_lock_clients(
clients: HashMap<String, Arc<dyn LockClient>>,
) -> Result<(), HashMap<String, Arc<dyn LockClient>>> {
GLOBAL_LOCK_CLIENTS.set(clients)
if GLOBAL_LOCK_CLIENTS.load().is_some() {
return Err(clients);
}
GLOBAL_LOCK_CLIENTS.store(Some(Arc::new(clients)));
Ok(())
}
/// Atomically replace the global lock clients map during a live topology reload.
pub fn replace_global_lock_clients(
clients: HashMap<String, Arc<dyn LockClient>>,
) -> Option<Arc<HashMap<String, Arc<dyn LockClient>>>> {
GLOBAL_LOCK_CLIENTS.swap(Some(Arc::new(clients)))
}
/// Get the global lock clients map
///
/// # Returns
/// * `Option<&HashMap<String, Arc<dyn LockClient>>>` - The global lock clients map, if set
/// * `Option<Arc<HashMap<String, Arc<dyn LockClient>>>>` - The global lock clients map, if set
///
pub fn get_global_lock_clients() -> Option<&'static HashMap<String, Arc<dyn LockClient>>> {
GLOBAL_LOCK_CLIENTS.get()
pub fn get_global_lock_clients() -> Option<Arc<HashMap<String, Arc<dyn LockClient>>>> {
GLOBAL_LOCK_CLIENTS.load_full()
}
+322 -29
View File
@@ -51,6 +51,7 @@ use crate::object_api::ObjectEncryptionResolver;
use crate::services::event_notification::EventNotifier;
use crate::services::tier::tier::TierConfigMgr;
use crate::store::delete_recovery_runtime::DeleteRecoveryHints;
use arc_swap::ArcSwapOption;
use rustfs_lock::{GlobalLockManager, get_global_lock_manager};
use rustfs_s3_types::Region;
use std::collections::{HashMap, HashSet};
@@ -263,9 +264,35 @@ pub struct InstanceContext {
deployment_id: OnceLock<Uuid>,
/// This instance's endpoint topology (Phase 5 Slice 6, backlog#939).
///
/// Write-once: storage startup publishes the server pools exactly once.
/// Replaces the process-global endpoints static.
endpoints: OnceLock<EndpointServerPools>,
/// Published once during startup via [`Self::set_endpoints`] and atomically
/// swapped on live pool topology hot-reload via [`Self::replace_endpoints`].
endpoints: ArcSwapOption<EndpointServerPools>,
/// Monotonic topology generation counter incremented on each live hot-reload.
topology_generation: AtomicU64,
/// Weak pointer to the currently active `ECStore` generation for this
/// instance context, updated on startup and on every live hot-reload so
/// long-lived background subsystems resolve the live generation without
/// pinning retired `ECStore` generations in memory.
live_store: std::sync::RwLock<std::sync::Weak<crate::store::ECStore>>,
/// Weak registry of external `DynamicECStoreHandle` cells eagerly rebound
/// to each newly published `ECStore` generation at cutover so retired
/// generations are released immediately even when subsystems are idle.
rebindable_store_cells: std::sync::Mutex<Vec<std::sync::Weak<std::sync::RwLock<Arc<crate::store::ECStore>>>>>,
/// Raw pointer address of the currently active `ECStore` generation (0 before
/// publication), used to reject deferred movement starts on retired generations.
active_store_ptr: std::sync::atomic::AtomicUsize,
/// Per-generation cancellation token cancelled and rotated on each hot-reload.
active_generation_cancel: std::sync::Mutex<Option<CancellationToken>>,
/// Shared across `ECStore` generations of this instance so rebalance,
/// decommission, and topology hot-reload starts serialize even across
/// generation retirement.
movement_start_gate: Arc<Mutex<()>>,
/// Set once startup disk format discovery/creation and local disk-ID map
/// prewarming have completed (before entering `pool_join_standby`).
startup_formats_ready: AtomicBool,
/// Instant wakeup notifier for a node waiting in `pool_join_standby` once
/// the elected pool writer commits `pool.bin`.
pool_join_wakeup: Notify,
/// Only a complete validated topology may enable native local proof origin.
multipart_proof_topology: OnceLock<([u8; 32], ProofVerificationContext)>,
/// This instance's tier configuration manager (Phase 5 Slice 7, backlog#939).
@@ -293,9 +320,9 @@ pub struct InstanceContext {
/// This instance's bucket bandwidth monitor (Phase 5 Slice 10, backlog#939).
///
/// Set once at startup with the cluster node count (see
/// [`InstanceContext::init_bucket_monitor`]); read as `None` until then.
/// Replaces the process-global bucket-monitor static.
bucket_monitor: OnceLock<Arc<Monitor>>,
/// [`InstanceContext::init_bucket_monitor`]) and atomically refreshed when
/// cluster membership changes on live topology hot-reload.
bucket_monitor: ArcSwapOption<Monitor>,
/// This instance's background replication stats (Phase 5 Slice 11, backlog#939).
///
/// Async set-once (workers are spawned during init); read as `None` until
@@ -328,6 +355,7 @@ pub struct InstanceContext {
/// their own `ECStore` without panicking. Production startup still sets
/// this exactly once.
bucket_metadata_sys: std::sync::Mutex<Option<Arc<RwLock<BucketMetadataSys>>>>,
bucket_metadata_store_cell: std::sync::Mutex<Option<Arc<std::sync::RwLock<std::sync::Weak<crate::store::ECStore>>>>>,
/// This instance's background-services cancellation token (Phase 5 Slice 13,
/// backlog#939).
///
@@ -339,6 +367,10 @@ pub struct InstanceContext {
/// Readers are held across one publication commit; movement transitions
/// take the writer at their durable state commit boundary.
data_movement_operation_gate: Arc<RwLock<()>>,
/// Serializes `CreateBucket` execution with live topology hot-reload cutover
/// so in-flight bucket creations never straddle old/new pool generations or
/// miss physical directory propagation onto newly expanded pools.
bucket_topology_gate: Arc<RwLock<()>>,
/// Set while an operator decommission start runs on this instance. A
/// start runs detached from its caller, so this keeps abandoned requests
/// and their retries from stacking concurrent starts and preflight heals.
@@ -475,21 +507,31 @@ impl InstanceContext {
region: OnceLock::new(),
additional_regions: OnceLock::new(),
deployment_id: OnceLock::new(),
endpoints: OnceLock::new(),
endpoints: ArcSwapOption::empty(),
topology_generation: AtomicU64::new(0),
live_store: std::sync::RwLock::new(std::sync::Weak::new()),
rebindable_store_cells: std::sync::Mutex::new(Vec::new()),
active_store_ptr: std::sync::atomic::AtomicUsize::new(0),
active_generation_cancel: std::sync::Mutex::new(None),
movement_start_gate: Arc::new(Mutex::new(())),
startup_formats_ready: AtomicBool::new(false),
pool_join_wakeup: Notify::new(),
multipart_proof_topology: OnceLock::new(),
tier_config_mgr: OnceLock::new(),
event_notifier: OnceLock::new(),
expiry_state: OnceLock::new(),
transition_state: OnceLock::new(),
bucket_monitor: OnceLock::new(),
bucket_monitor: ArcSwapOption::empty(),
replication_stats: OnceCell::new(),
replication_pool: OnceCell::new(),
local_disk_map: Arc::new(RwLock::new(HashMap::new())),
local_disk_id_map: Arc::new(RwLock::new(HashMap::new())),
local_disk_set_drives: Arc::new(RwLock::new(Vec::new())),
bucket_metadata_sys: std::sync::Mutex::new(None),
bucket_metadata_store_cell: std::sync::Mutex::new(None),
background_cancel_token: OnceLock::new(),
data_movement_operation_gate: Arc::new(RwLock::new(())),
bucket_topology_gate: Arc::new(RwLock::new(())),
decommission_start_in_flight: AtomicBool::new(false),
decommission_pauses: std::sync::Mutex::new(HashMap::new()),
decommission_count_ledgers: std::sync::Mutex::new(HashMap::new()),
@@ -567,6 +609,10 @@ impl InstanceContext {
Arc::clone(&self.data_movement_operation_gate)
}
pub(crate) fn bucket_topology_gate(&self) -> Arc<RwLock<()>> {
Arc::clone(&self.bucket_topology_gate)
}
/// Claim the single decommission start slot; `false` when a start is
/// already running. Release it with [`Self::end_decommission_start`].
pub(crate) fn try_begin_decommission_start(&self) -> bool {
@@ -629,6 +675,36 @@ impl InstanceContext {
.cloned()
}
/// Remap positional per-pool decommission pauses and count ledgers across a
/// committed topology hot-reload (`old_pool_idx -> new_pool_idx`), pruning
/// removed pools and shifting retained pools when an earlier pool is removed.
pub(crate) fn reconcile_positional_pool_state(&self, old_to_new_pool: &HashMap<usize, usize>) {
{
let mut pauses = self
.decommission_pauses
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let old_pauses = std::mem::take(&mut *pauses);
for (old_idx, record) in old_pauses {
if let Some(&new_idx) = old_to_new_pool.get(&old_idx) {
pauses.insert(new_idx, record);
}
}
}
{
let mut ledgers = self
.decommission_count_ledgers
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let old_ledgers = std::mem::take(&mut *ledgers);
for (old_idx, ledger) in old_ledgers {
if let Some(&new_idx) = old_to_new_pool.get(&old_idx) {
ledgers.insert(new_idx, ledger);
}
}
}
}
pub(crate) async fn install_scanner_publication_lease(
&self,
token: Uuid,
@@ -940,17 +1016,135 @@ impl InstanceContext {
/// Set this instance's endpoint topology.
///
/// Write-once: panics on a second write, preserving the startup fail-fast
/// contract of the process global it replaces.
/// Write-once during startup: panics on a second write, preserving the
/// startup fail-fast contract. Live topology hot-reload uses
/// [`Self::replace_endpoints`].
pub fn set_endpoints(&self, endpoints: EndpointServerPools) {
assert!(
self.endpoints.load().is_none(),
"instance endpoints should be initialized once during storage startup"
);
self.endpoints.store(Some(Arc::new(endpoints)));
}
/// Atomically replace this instance's endpoint topology during a live
/// hot-reload, returning the previous topology if one was set.
pub fn replace_endpoints(&self, endpoints: EndpointServerPools) -> Option<EndpointServerPools> {
self.endpoints
.set(endpoints)
.expect("instance endpoints should be initialized once during storage startup");
.swap(Some(Arc::new(endpoints)))
.map(|prev| prev.as_ref().clone())
}
/// Current topology reload generation (0 at initial boot, incremented per hot-reload).
pub fn topology_generation(&self) -> u64 {
self.topology_generation.load(Ordering::Acquire)
}
/// Increment and return the new topology generation after a live hot-reload commit.
pub(crate) fn advance_topology_generation(&self) -> u64 {
self.topology_generation.fetch_add(1, Ordering::AcqRel).saturating_add(1)
}
pub(crate) fn sync_topology_generation_at_least(&self, min_generation: u64) -> u64 {
let mut current = self.topology_generation.load(Ordering::Acquire);
while current < min_generation {
match self
.topology_generation
.compare_exchange_weak(current, min_generation, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => return min_generation,
Err(observed) => current = observed,
}
}
current
}
/// Publish the currently active `ECStore` generation for this instance context.
pub(crate) fn set_live_store(&self, store: &Arc<crate::store::ECStore>) {
let new_ptr = Arc::as_ptr(store) as usize;
self.active_store_ptr.store(new_ptr, Ordering::Release);
*self.live_store.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::downgrade(store);
let mut cells = self
.rebindable_store_cells
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
cells.retain(|weak_cell| {
let Some(cell) = weak_cell.upgrade() else {
return false;
};
*cell.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::clone(store);
true
});
}
pub(crate) fn register_rebindable_store_cell(&self, cell: &Arc<std::sync::RwLock<Arc<crate::store::ECStore>>>) {
if let Some(live) = self.live_store() {
*cell.write().unwrap_or_else(std::sync::PoisonError::into_inner) = live;
}
self.rebindable_store_cells
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(Arc::downgrade(cell));
}
pub(crate) fn active_store_ptr(&self) -> usize {
self.active_store_ptr.load(Ordering::Acquire)
}
/// Cancel any previous generation's background worker token and install a
/// fresh child token of `parent` for the newly active generation.
pub(crate) fn rotate_generation_cancel(&self, parent: &CancellationToken) -> CancellationToken {
let next = parent.child_token();
let prev = self
.active_generation_cancel
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.replace(next.clone());
if let Some(prev) = prev {
prev.cancel();
}
next
}
/// Resolve the currently active `ECStore` generation for this instance context,
/// if still alive.
pub fn live_store(&self) -> Option<Arc<crate::store::ECStore>> {
self.live_store
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.upgrade()
}
/// Shared start-gate mutex serializing rebalance, decommission, and topology
/// hot-reload start transitions across `ECStore` generations.
pub(crate) fn movement_start_gate(&self) -> Arc<Mutex<()>> {
Arc::clone(&self.movement_start_gate)
}
/// Record that local disk formats and disk-ID maps are initialized and ready
/// to serve remote I/O during standby pool join.
pub(crate) fn mark_startup_formats_ready(&self) {
self.startup_formats_ready.store(true, Ordering::Release);
}
/// Whether startup disk format discovery and disk-ID prewarming have completed.
pub fn is_startup_formats_ready(&self) -> bool {
self.startup_formats_ready.load(Ordering::Acquire)
}
/// Wake a standby joining node immediately after the elected writer commits `pool.bin`.
pub fn notify_pool_join_wakeup(&self) {
self.pool_join_wakeup.notify_one();
}
/// Wait until notified that `pool.bin` was committed during standby pool join.
pub(crate) async fn wait_pool_join_wakeup(&self) {
self.pool_join_wakeup.notified().await;
}
/// This instance's endpoint topology, if it has been set.
pub fn endpoints(&self) -> Option<EndpointServerPools> {
self.endpoints.get().cloned()
self.endpoints.load_full().map(|eps| eps.as_ref().clone())
}
/// Keep one authority identity across complete local registry reinitializations.
@@ -978,6 +1172,27 @@ impl InstanceContext {
Ok(stored.1.clone())
}
/// Atomically replace the multipart proof topology's active endpoint set
/// during a committed live hot-reload (pruning removed local endpoints).
pub(crate) fn replace_multipart_proof_topology(
&self,
endpoints: &EndpointServerPools,
) -> crate::disk::error::Result<ProofVerificationContext> {
if endpoints.as_ref().iter().enumerate().any(|(pool, entry)| {
entry
.endpoints
.as_ref()
.iter()
.any(|endpoint| usize::try_from(endpoint.pool_idx).ok() != Some(pool))
}) {
return Err(crate::disk::error::DiskError::InconsistentDisk);
}
let (identity, authority) = ProofVerificationContext::for_topology(endpoints)?;
let stored = self.multipart_proof_topology.get_or_init(|| (identity, authority.clone()));
stored.1.replace_topology(&authority)?;
Ok(stored.1.clone())
}
pub(crate) fn multipart_proof_verification_context(&self) -> ProofVerificationContext {
self.multipart_proof_topology
.get()
@@ -1013,12 +1228,31 @@ impl InstanceContext {
/// node count. Returns `false` if it was already initialized (the caller
/// logs; matches the process global's ignore-and-warn behavior).
pub fn init_bucket_monitor(&self, num_nodes: u64) -> bool {
self.bucket_monitor.set(Monitor::new(num_nodes)).is_ok()
if self.bucket_monitor.load().is_some() {
return false;
}
self.bucket_monitor.store(Some(Monitor::new(num_nodes)));
true
}
/// Atomically replace this instance's bucket bandwidth monitor for a live
/// topology reload with an updated node count, preserving configured bucket
/// bandwidth limits.
pub fn replace_bucket_monitor(&self, num_nodes: u64) {
let normalized = num_nodes.max(1);
if let Some(existing) = self.bucket_monitor.load_full() {
if existing.node_count == normalized {
return;
}
self.bucket_monitor.store(Some(existing.with_inherited_limits(normalized)));
} else {
self.bucket_monitor.store(Some(Monitor::new(normalized)));
}
}
/// This instance's bucket bandwidth monitor, if it has been initialized.
pub fn bucket_monitor(&self) -> Option<Arc<Monitor>> {
self.bucket_monitor.get().cloned()
self.bucket_monitor.load_full()
}
/// This instance's background replication stats, if initialized.
@@ -1078,6 +1312,25 @@ impl InstanceContext {
let mut guard = self.bucket_metadata_sys.lock().expect("bucket_metadata_sys lock poisoned");
let is_first = guard.is_none();
*guard = Some(sys);
*self
.bucket_metadata_store_cell
.lock()
.expect("bucket_metadata_store_cell lock poisoned") = None;
is_first
}
pub(crate) fn init_bucket_metadata_sys_with_store_cell(
&self,
sys: Arc<RwLock<BucketMetadataSys>>,
store_cell: Arc<std::sync::RwLock<std::sync::Weak<crate::store::ECStore>>>,
) -> bool {
let mut guard = self.bucket_metadata_sys.lock().expect("bucket_metadata_sys lock poisoned");
let is_first = guard.is_none();
*guard = Some(sys);
*self
.bucket_metadata_store_cell
.lock()
.expect("bucket_metadata_store_cell lock poisoned") = Some(store_cell);
is_first
}
@@ -1089,28 +1342,68 @@ impl InstanceContext {
.clone()
}
/// Rebind this instance's bucket metadata system to a newly hot-reloaded
/// `ECStore` generation wait-free without contending on outer async
/// `BucketMetadataSys` read/write locks.
pub fn rebind_bucket_metadata_store_sync(&self, store: &Arc<crate::store::ECStore>) {
if let Some(cell) = self
.bucket_metadata_store_cell
.lock()
.expect("bucket_metadata_store_cell lock poisoned")
.clone()
{
*cell.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::downgrade(store);
return;
}
if let Some(sys) = self.bucket_metadata_sys()
&& let Ok(guard) = sys.try_read()
{
guard.rebind_store(store.clone());
}
}
/// Async-compatible wrapper around [`Self::rebind_bucket_metadata_store_sync`].
pub async fn rebind_bucket_metadata_store(&self, store: Arc<crate::store::ECStore>) {
if let Some(cell) = self
.bucket_metadata_store_cell
.lock()
.expect("bucket_metadata_store_cell lock poisoned")
.clone()
{
*cell.write().unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::downgrade(&store);
return;
}
if let Some(sys) = self.bucket_metadata_sys() {
sys.read().await.rebind_store(store);
}
}
/// Remove the `BucketMetadataSys` when its backing `ECStore` is gone.
///
/// Called from `ECStore::drop`. When test fixtures share the bootstrap
/// context, the `BucketMetadataSys` stores a `Weak<ECStore>` to prevent a
/// reference cycle; once the store drops the weak is dangling and any
/// `object_store()` call panics. Clearing the slot here lets the next
/// fixture install a fresh `BucketMetadataSys` without hitting the stale one.
pub fn clear_bucket_metadata_sys_if_stale(&self) {
let mut guard = self.bucket_metadata_sys.lock().expect("bucket_metadata_sys lock poisoned");
if let Some(sys) = guard.as_ref() {
// `read()` may block briefly; the async RwLock is acceptable here
// because Drop is sync and the lock is held only long enough to
// check the weak reference.
let is_stale = {
let s = sys.try_read();
match s {
let cell_opt = self
.bucket_metadata_store_cell
.lock()
.expect("bucket_metadata_store_cell lock poisoned")
.clone();
let is_stale = if let Some(cell) = cell_opt {
cell.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.upgrade()
.is_none()
} else {
match sys.try_read() {
Ok(s) => s.is_store_stale(),
Err(_) => true, // contended: treat as stale-safe to clear
Err(_) => false,
}
};
if is_stale {
*guard = None;
*self
.bucket_metadata_store_cell
.lock()
.expect("bucket_metadata_store_cell lock poisoned") = None;
}
}
}
@@ -1209,7 +1502,7 @@ impl std::fmt::Debug for InstanceContext {
.field("event_notifier_set", &self.event_notifier.get().is_some())
.field("expiry_state_set", &self.expiry_state.get().is_some())
.field("transition_state_set", &self.transition_state.get().is_some())
.field("bucket_monitor_set", &self.bucket_monitor.get().is_some())
.field("bucket_monitor_set", &self.bucket_monitor.load().is_some())
.field(
"bucket_metadata_sys_set",
&self.bucket_metadata_sys.lock().map(|g| g.is_some()).unwrap_or(false),
+235 -2
View File
@@ -34,7 +34,8 @@ use crate::{
get_background_services_cancel_token, get_global_bucket_monitor, get_global_deployment_id, get_global_endpoints,
get_global_endpoints_opt, get_global_lock_client, get_global_lock_clients, get_global_region, get_global_tier_config_mgr,
global_rustfs_port, init_global_bucket_monitor, is_dist_erasure, is_erasure, is_erasure_sd, is_first_cluster_node_local,
resolve_object_store_handle, set_global_lock_client, set_global_lock_clients, set_object_layer, update_erasure_type,
replace_global_lock_clients, replace_object_layer, resolve_object_store_handle, set_global_lock_client,
set_global_lock_clients, set_object_layer, update_erasure_type,
},
services::batch_processor::{GlobalBatchProcessors, get_global_processors},
services::notification_sys::{NotificationSys, get_global_notification_sys},
@@ -307,7 +308,7 @@ pub fn global_lock_client() -> Option<Arc<dyn LockClient>> {
get_global_lock_client()
}
pub fn global_lock_clients() -> Option<&'static HashMap<String, Arc<dyn LockClient>>> {
pub fn global_lock_clients() -> Option<Arc<HashMap<String, Arc<dyn LockClient>>>> {
get_global_lock_clients()
}
@@ -326,10 +327,20 @@ pub(crate) fn set_lock_clients(
set_global_lock_clients(clients)
}
pub(crate) fn replace_lock_clients(
clients: HashMap<String, Arc<dyn LockClient>>,
) -> Option<Arc<HashMap<String, Arc<dyn LockClient>>>> {
replace_global_lock_clients(clients)
}
pub(crate) async fn publish_object_store(store: Arc<ECStore>) {
set_object_layer(store).await;
}
pub(crate) fn replace_object_store(store: Arc<ECStore>) -> Option<Arc<ECStore>> {
replace_object_layer(store)
}
pub(crate) fn notification_sys() -> Option<Arc<NotificationSys>> {
get_global_notification_sys()
}
@@ -631,6 +642,228 @@ pub(crate) async fn initialize_local_disk_maps(
Ok(())
}
pub(crate) struct StagedLocalDiskTopology {
pub(crate) set_drives: crate::runtime::global::TypeLocalDiskSetDrives,
pub(crate) local_disk_map: HashMap<String, Option<DiskStore>>,
pub(crate) newly_opened: Vec<DiskStore>,
pub(crate) pool_index_updates: Vec<(DiskStore, i32)>,
pub(crate) removed_local_disks: Vec<DiskStore>,
pub(crate) endpoint_pools: EndpointServerPools,
}
fn canonical_local_disk_path(ep: &Endpoint) -> std::path::PathBuf {
let raw = std::path::PathBuf::from(ep.get_file_path());
std::fs::canonicalize(&raw).unwrap_or(raw)
}
/// Stage local disk handles for a candidate topology WITHOUT mutating any live
/// registry (`local_disk_map`, `local_disk_set_drives`, `local_disk_id_map`)
/// or live `LocalDisk` pool indices until atomic cutover.
pub(crate) async fn prepare_staged_local_disks_for_reload(
instance_ctx: &Arc<InstanceContext>,
endpoint_pools: EndpointServerPools,
) -> Result<StagedLocalDiskTopology> {
let reload_opt = DiskOption {
cleanup: false,
health_check: true,
};
let existing_by_endpoint = instance_ctx.local_disk_map().read().await.clone();
let mut existing_by_path: HashMap<std::path::PathBuf, DiskStore> = HashMap::new();
let mut all_existing_disks: Vec<DiskStore> = Vec::new();
for disk in existing_by_endpoint.values().flatten() {
existing_by_path.insert(canonical_local_disk_path(&disk.endpoint()), disk.clone());
all_existing_disks.push(disk.clone());
}
let mut next_set_drives = Vec::with_capacity(endpoint_pools.as_ref().len());
for pool_eps in endpoint_pools.as_ref().iter() {
let mut set_count_drives = Vec::with_capacity(pool_eps.set_count);
for _ in 0..pool_eps.set_count {
set_count_drives.push(vec![None; pool_eps.drives_per_set]);
}
next_set_drives.push(set_count_drives);
}
let mut next_local_disk_map = HashMap::new();
let mut newly_opened = Vec::new();
let mut pool_index_updates = Vec::new();
let mut retained_ptrs: HashSet<usize> = HashSet::new();
for pool_eps in endpoint_pools.as_ref().iter() {
for ep in pool_eps.endpoints.as_ref().iter() {
if !ep.is_local {
continue;
}
let ep_key = ep.to_string();
let existing = existing_by_endpoint
.get(&ep_key)
.cloned()
.flatten()
.or_else(|| existing_by_path.get(&canonical_local_disk_path(ep)).cloned());
let disk = if let Some(live_disk) = existing {
retained_ptrs.insert(Arc::as_ptr(&live_disk) as usize);
if live_disk.endpoint().pool_idx != ep.pool_idx {
pool_index_updates.push((live_disk.clone(), ep.pool_idx));
}
live_disk
} else {
match new_disk(ep, &reload_opt).await {
Ok(disk) => {
newly_opened.push(disk.clone());
disk
}
Err(crate::disk::error::DiskError::FileAccessDenied | crate::disk::error::DiskError::VolumeNotFound) => {
next_local_disk_map.insert(ep_key, None);
continue;
}
Err(err) => {
for opened in newly_opened {
if let crate::disk::Disk::Local(wrapper) = opened.as_ref() {
wrapper.retire_handle();
}
let _ = opened.close().await;
}
return Err(err.into());
}
}
};
let pool_idx = usize::try_from(ep.pool_idx).map_err(|err| {
crate::error::Error::other_with_context(
"topology reload failed to convert pool index",
format!("pool_idx={}: {err}", ep.pool_idx),
)
})?;
let set_idx = usize::try_from(ep.set_idx).map_err(|err| {
crate::error::Error::other_with_context(
"topology reload failed to convert set index",
format!("set_idx={}: {err}", ep.set_idx),
)
})?;
let disk_idx = usize::try_from(ep.disk_idx).map_err(|err| {
crate::error::Error::other_with_context(
"topology reload failed to convert disk index",
format!("disk_idx={}: {err}", ep.disk_idx),
)
})?;
next_local_disk_map.insert(ep_key, Some(disk.clone()));
next_set_drives[pool_idx][set_idx][disk_idx] = Some(disk);
}
}
let removed_local_disks = all_existing_disks
.into_iter()
.filter(|d| !retained_ptrs.contains(&(Arc::as_ptr(d) as usize)))
.collect();
Ok(StagedLocalDiskTopology {
set_drives: next_set_drives,
local_disk_map: next_local_disk_map,
newly_opened,
pool_index_updates,
removed_local_disks,
endpoint_pools,
})
}
/// Synchronize post-quorum format quarantine decisions into the staged local
/// disk structures before atomic cutover.
pub(crate) fn sync_staged_local_disks_with_quorum(
staged: &mut StagedLocalDiskTopology,
pool_idx: usize,
pool_eps: &crate::layout::endpoints::PoolEndpoints,
quorum_disks: &[Option<DiskStore>],
) {
if pool_eps.drives_per_set == 0 {
return;
}
for (flat_idx, ep) in pool_eps.endpoints.as_ref().iter().enumerate() {
if !ep.is_local {
continue;
}
let set_idx = flat_idx / pool_eps.drives_per_set;
let disk_idx = flat_idx % pool_eps.drives_per_set;
let selected = quorum_disks.get(flat_idx).cloned().flatten();
staged.local_disk_map.insert(ep.to_string(), selected.clone());
if let Some(slot) = staged
.set_drives
.get_mut(pool_idx)
.and_then(|sets| sets.get_mut(set_idx))
.and_then(|drives| drives.get_mut(disk_idx))
{
*slot = selected;
}
}
}
/// Discard newly opened candidate local disks when a staged reload aborts before cutover.
pub(crate) async fn abort_staged_local_disks_for_reload(staged: StagedLocalDiskTopology) {
for disk in staged.newly_opened {
if let crate::disk::Disk::Local(wrapper) = disk.as_ref() {
wrapper.retire_handle();
}
let _ = disk.close().await;
}
}
/// Commit staged local disk registries, updated `pool_idx` locations, multipart
/// proof topology, and pruned `local_disk_id_map` atomically at cutover.
pub(crate) async fn commit_staged_local_disks_for_reload(
instance_ctx: &Arc<InstanceContext>,
staged: StagedLocalDiskTopology,
) -> Result<Vec<DiskStore>> {
let multipart_authority = instance_ctx.replace_multipart_proof_topology(&staged.endpoint_pools)?;
for (disk, new_pool_idx) in &staged.pool_index_updates {
if let crate::disk::Disk::Local(wrapper) = disk.as_ref() {
wrapper.get_disk().set_pool_index(*new_pool_idx);
}
}
let mut active_disk_ids: HashMap<Uuid, String> = HashMap::new();
for (ep_key, maybe_disk) in &staged.local_disk_map {
let Some(disk) = maybe_disk else { continue };
if let crate::disk::Disk::Local(wrapper) = disk.as_ref() {
wrapper.get_disk().usage_watch_binding.bind(&instance_ctx.usage_watches);
wrapper.get_disk().bind_multipart_proof_authority(&multipart_authority)?;
}
if let Ok(Some(disk_id)) = disk.get_disk_id().await {
active_disk_ids.insert(disk_id, ep_key.clone());
}
}
let set_drives = instance_ctx.local_disk_set_drives();
let map = instance_ctx.local_disk_map();
let id_map = instance_ctx.local_disk_id_map();
let mut global_set_drives = set_drives.write().await;
let mut global_local_disk_map = map.write().await;
let mut global_id_map = id_map.write().await;
*global_set_drives = staged.set_drives;
*global_local_disk_map = staged.local_disk_map;
*global_id_map = active_disk_ids;
Ok(staged.removed_local_disks)
}
/// Refresh local disk registries for a live topology hot-reload.
///
/// Retains existing live `DiskStore` handles for unchanged local paths without
/// running destructive startup `cleanup`, opens only newly added local disks
/// with `cleanup = false`, and re-indexes `(pool_idx, set_idx, disk_idx)` to
/// match `endpoint_pools`.
pub(crate) async fn refresh_local_disk_maps_for_reload(
instance_ctx: &Arc<InstanceContext>,
endpoint_pools: EndpointServerPools,
) -> Result<()> {
let staged = prepare_staged_local_disks_for_reload(instance_ctx, endpoint_pools).await?;
let removed = commit_staged_local_disks_for_reload(instance_ctx, staged).await?;
for disk in removed {
if let crate::disk::Disk::Local(wrapper) = disk.as_ref() {
wrapper.retire_handle();
}
let _ = disk.close().await;
}
Ok(())
}
pub(crate) async fn init_tier_config_mgr(store: Arc<ECStore>) -> Result<()> {
init_tier_config_mgr_handle(get_global_tier_config_mgr(), store).await
}
+157 -88
View File
@@ -24,6 +24,7 @@ use crate::layout::endpoints::EndpointServerPools;
use crate::runtime::sources as runtime_sources;
use crate::services::metrics_realtime::{CollectMetricsOpts, MetricType};
use crate::storage_api_contracts::admin::StorageAdminApi;
use arc_swap::ArcSwapOption;
use bytes::Bytes;
use futures::future::join_all;
use lazy_static::lazy_static;
@@ -202,7 +203,7 @@ const SERVER_INFO_CACHE_MAX_AGE: Duration = Duration::from_secs(60);
const STORAGE_INFO_CACHE_MAX_AGE: Duration = Duration::from_secs(60);
lazy_static! {
pub static ref GLOBAL_NOTIFICATION_SYS: OnceLock<Arc<NotificationSys>> = OnceLock::new();
pub static ref GLOBAL_NOTIFICATION_SYS: ArcSwapOption<NotificationSys> = ArcSwapOption::empty();
}
#[derive(Clone)]
@@ -361,7 +362,32 @@ static ILM_RECOVERY_EXPORT_FLEET_PROOF: OnceLock<std::sync::RwLock<FleetCapabili
static TRANSITION_TRANSACTION_COMPACTION_FLEET_PROOF: OnceLock<std::sync::RwLock<FleetCapabilityProofState>> = OnceLock::new();
static MRF_LIFECYCLE_WRITER_FLEET_PROOF: OnceLock<std::sync::RwLock<FleetCapabilityProofState>> = OnceLock::new();
static MRF_LIFECYCLE_READER_LOCAL_PROCESS_EPOCH: LazyLock<Uuid> = LazyLock::new(Uuid::new_v4);
static REMOTE_VERSION_STATE_PROBE_TOPOLOGY: OnceLock<String> = OnceLock::new();
static REMOTE_VERSION_STATE_PROBE_TOPOLOGY: LazyLock<ArcSwapOption<String>> = LazyLock::new(ArcSwapOption::empty);
fn current_probe_topology() -> Option<Arc<String>> {
REMOTE_VERSION_STATE_PROBE_TOPOLOGY.load_full()
}
fn set_probe_topology_once(topology_fingerprint: String) -> std::result::Result<(), String> {
if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.load().is_some() {
return Err(topology_fingerprint);
}
REMOTE_VERSION_STATE_PROBE_TOPOLOGY.store(Some(Arc::new(topology_fingerprint)));
Ok(())
}
/// Atomically replace the active fleet probe topology during a live pool
/// topology hot-reload, revoking stale generation proofs and waking the probe
/// loop to re-establish fleet proofs for the new membership immediately.
pub fn replace_remote_version_state_probe_topology(topology_fingerprint: String) {
REMOTE_VERSION_STATE_PROBE_TOPOLOGY.store(Some(Arc::new(topology_fingerprint)));
for slot in all_fleet_capability_proof_slots() {
let mut state = slot.write().unwrap_or_else(std::sync::PoisonError::into_inner);
state.topology_conflict = false;
revoke_fleet_capability_proof_state(&mut state);
}
NOTIFICATION_SYS_PUBLISHED.notify_one();
}
/// Signalled once `GLOBAL_NOTIFICATION_SYS` is published so the fleet probe can
/// run its first real pass without waiting for the bootstrap poll.
static NOTIFICATION_SYS_PUBLISHED: Notify = Notify::const_new();
@@ -494,11 +520,11 @@ fn publish_fleet_capability_probe_result(
}
pub(crate) fn acquire_remote_version_state_fleet_proof() -> Option<RemoteVersionStateFleetProofToken> {
let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?;
let expected_topology = current_probe_topology()?;
let state = remote_version_state_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now()).map(RemoteVersionStateFleetProofToken)
acquire_fleet_capability_proof_from(&state, expected_topology.as_str(), Instant::now()).map(RemoteVersionStateFleetProofToken)
}
pub(crate) fn acquire_remote_version_state_writer_fleet_proof() -> Option<RemoteVersionStateFleetProofToken> {
@@ -531,11 +557,11 @@ pub(crate) fn remote_version_state_fleet_proof_matches(proof: &RemoteVersionStat
}
pub(crate) fn acquire_transition_transaction_compaction_fleet_proof() -> Option<TransitionTransactionCompactionFleetProofToken> {
let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?;
let expected_topology = current_probe_topology()?;
let state = transition_transaction_compaction_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let token = acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now())?;
let token = acquire_fleet_capability_proof_from(&state, expected_topology.as_str(), Instant::now())?;
let permit = state.proof.as_ref()?.generation.try_acquire()?;
Some(TransitionTransactionCompactionFleetProofToken { token, _permit: permit })
}
@@ -543,14 +569,14 @@ pub(crate) fn acquire_transition_transaction_compaction_fleet_proof() -> Option<
pub(crate) fn transition_transaction_compaction_fleet_proof_matches(
proof: &TransitionTransactionCompactionFleetProofToken,
) -> bool {
let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else {
let Some(expected_topology) = current_probe_topology() else {
return false;
};
let state = transition_transaction_compaction_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
proof._permit.generation.is_accepting()
&& fleet_capability_proof_matches_at(&state, &proof.token, expected_topology, Instant::now())
&& fleet_capability_proof_matches_at(&state, &proof.token, expected_topology.as_str(), Instant::now())
&& state
.proof
.as_ref()
@@ -558,11 +584,11 @@ pub(crate) fn transition_transaction_compaction_fleet_proof_matches(
}
pub fn acquire_cross_pool_fence_fleet_proof() -> Option<CrossPoolFenceFleetProofToken> {
let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?;
let expected_topology = current_probe_topology()?;
let state = cross_pool_fence_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now()).map(CrossPoolFenceFleetProofToken)
acquire_fleet_capability_proof_from(&state, expected_topology.as_str(), Instant::now()).map(CrossPoolFenceFleetProofToken)
}
async fn wait_for_fleet_capability_proof(
@@ -603,14 +629,14 @@ pub(crate) async fn wait_for_cross_pool_fence_fleet_proof(rx: CancellationToken)
}
/// Startup layout identity remains available when peers or the live fleet proof are unavailable.
pub fn configured_fleet_topology_fingerprint() -> Option<&'static str> {
pub fn configured_fleet_topology_fingerprint() -> Option<String> {
let state = cross_pool_fence_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if state.topology_conflict {
return None;
}
REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get().map(String::as_str)
current_probe_topology().map(|topology| topology.as_ref().clone())
}
pub fn cross_pool_fence_fleet_proof_matches(proof: &CrossPoolFenceFleetProofToken) -> bool {
@@ -618,11 +644,12 @@ pub fn cross_pool_fence_fleet_proof_matches(proof: &CrossPoolFenceFleetProofToke
}
pub(crate) fn acquire_decommission_target_fence_fleet_proof() -> Option<DecommissionTargetFenceFleetProofToken> {
let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?;
let expected_topology = current_probe_topology()?;
let state = decommission_target_fence_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
acquire_fleet_capability_proof_from(&state, expected_topology, Instant::now()).map(DecommissionTargetFenceFleetProofToken)
acquire_fleet_capability_proof_from(&state, expected_topology.as_str(), Instant::now())
.map(DecommissionTargetFenceFleetProofToken)
}
pub(crate) fn decommission_target_fence_fleet_proof_matches(proof: &DecommissionTargetFenceFleetProofToken) -> bool {
@@ -630,11 +657,11 @@ pub(crate) fn decommission_target_fence_fleet_proof_matches(proof: &Decommission
}
pub(crate) fn acquire_tier_delete_journal_fleet_proof() -> Option<TierDeleteJournalFleetProofToken> {
let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?;
let expected_topology = current_probe_topology()?;
let state = tier_delete_journal_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
acquire_tier_delete_journal_fleet_proof_from(&state, expected_topology, Instant::now())
acquire_tier_delete_journal_fleet_proof_from(&state, expected_topology.as_str(), Instant::now())
}
fn acquire_tier_delete_journal_fleet_proof_from(
@@ -648,13 +675,13 @@ fn acquire_tier_delete_journal_fleet_proof_from(
}
pub(crate) fn tier_delete_journal_fleet_proof_matches(proof: &TierDeleteJournalFleetProofToken) -> bool {
let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else {
let Some(expected_topology) = current_probe_topology() else {
return false;
};
let state = tier_delete_journal_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
tier_delete_journal_fleet_proof_matches_at(&state, proof, expected_topology, Instant::now())
tier_delete_journal_fleet_proof_matches_at(&state, proof, expected_topology.as_str(), Instant::now())
}
fn tier_delete_journal_fleet_proof_matches_at(
@@ -682,21 +709,21 @@ pub(crate) fn cross_pool_fence_topology_generation(proof: &CrossPoolFenceFleetPr
/// Acquire one non-cloneable authority that must span the complete reconcile
/// effect window, including its final strong readback.
pub async fn acquire_legacy_transition_state_reconcile_fleet_proof() -> Option<LegacyTransitionStateReconcileFleetProofToken> {
let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?;
let expected_topology = current_probe_topology()?;
let proof = {
let state = legacy_transition_state_reconcile_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
acquire_legacy_transition_state_reconcile_fleet_proof_from(&state, expected_topology, Instant::now())?
acquire_legacy_transition_state_reconcile_fleet_proof_from(&state, expected_topology.as_str(), Instant::now())?
};
let observed_peer_epochs = observe_legacy_transition_state_reconcile_fleet(expected_topology).await?;
let observed_peer_epochs = observe_legacy_transition_state_reconcile_fleet(expected_topology.as_str()).await?;
let state = legacy_transition_state_reconcile_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
legacy_transition_state_reconcile_fleet_proof_matches_observation_at(
&state,
&proof,
expected_topology,
expected_topology.as_str(),
&observed_peer_epochs,
Instant::now(),
)
@@ -704,7 +731,7 @@ pub async fn acquire_legacy_transition_state_reconcile_fleet_proof() -> Option<L
}
pub async fn require_restore_copyback_fleet_capability() -> Result<()> {
let Some(topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else {
let Some(topology) = current_probe_topology() else {
#[cfg(any(test, feature = "test-util"))]
return Ok(());
#[cfg(not(any(test, feature = "test-util")))]
@@ -718,7 +745,7 @@ pub async fn require_restore_copyback_fleet_capability() -> Result<()> {
};
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_restore_copyback_fleet(topology),
notification_sys.probe_restore_copyback_fleet(topology.as_str()),
)
.await
.map_err(|_| Error::other("restore copy-back capability fleet probe timed out"))??;
@@ -765,11 +792,11 @@ pub(crate) async fn with_legacy_transition_state_fleet_proof_for_test<F: std::fu
revoke_fleet_capability_proof(legacy_transition_state_reconcile_fleet_proof_slot());
}
}
let topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get().expect("test store topology");
let topology = current_probe_topology().expect("test store topology");
assert!(
publish_fleet_capability_probe_result(
legacy_transition_state_reconcile_fleet_proof_slot(),
topology,
topology.as_str(),
Ok(BTreeMap::new()),
Instant::now(),
)
@@ -786,14 +813,14 @@ pub(crate) async fn with_legacy_transition_state_fleet_proof_for_test<F: std::fu
pub async fn legacy_transition_state_reconcile_fleet_proof_matches(
proof: &LegacyTransitionStateReconcileFleetProofToken,
) -> bool {
let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else {
let Some(expected_topology) = current_probe_topology() else {
return false;
};
legacy_transition_state_reconcile_fleet_proof_matches_with_observer(
legacy_transition_state_reconcile_fleet_proof_slot(),
proof,
expected_topology,
|| observe_legacy_transition_state_reconcile_fleet(expected_topology),
expected_topology.as_str(),
|| observe_legacy_transition_state_reconcile_fleet(expected_topology.as_str()),
)
.await
}
@@ -803,26 +830,26 @@ pub async fn legacy_transition_state_reconcile_fleet_proof_matches(
pub(crate) fn legacy_transition_state_reconcile_fleet_proof_current(
proof: &LegacyTransitionStateReconcileFleetProofToken,
) -> bool {
let Some(topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else { return false };
let Some(topology) = current_probe_topology() else { return false };
let state = legacy_transition_state_reconcile_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
legacy_transition_state_reconcile_fleet_proof_matches_at(&state, proof, topology, Instant::now())
legacy_transition_state_reconcile_fleet_proof_matches_at(&state, proof, topology.as_str(), Instant::now())
}
pub async fn acquire_ilm_recovery_export_fleet_proof() -> Option<IlmRecoveryExportFleetProofToken> {
let expected_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get()?;
let expected_topology = current_probe_topology()?;
let proof = {
let state = ilm_recovery_export_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
acquire_ilm_recovery_export_fleet_proof_from(&state, expected_topology, Instant::now())?
acquire_ilm_recovery_export_fleet_proof_from(&state, expected_topology.as_str(), Instant::now())?
};
let observed = observe_ilm_recovery_export_fleet(expected_topology).await?;
let observed = observe_ilm_recovery_export_fleet(expected_topology.as_str()).await?;
let state = ilm_recovery_export_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
ilm_recovery_export_fleet_proof_matches_observation_at(&state, &proof, expected_topology, &observed, Instant::now())
ilm_recovery_export_fleet_proof_matches_observation_at(&state, &proof, expected_topology.as_str(), &observed, Instant::now())
.then_some(proof)
}
@@ -837,24 +864,24 @@ fn acquire_ilm_recovery_export_fleet_proof_from(
}
pub async fn ilm_recovery_export_fleet_proof_matches(proof: &IlmRecoveryExportFleetProofToken) -> bool {
let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else {
let Some(expected_topology) = current_probe_topology() else {
return false;
};
{
let state = ilm_recovery_export_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !ilm_recovery_export_fleet_proof_matches_at(&state, proof, expected_topology, Instant::now()) {
if !ilm_recovery_export_fleet_proof_matches_at(&state, proof, expected_topology.as_str(), Instant::now()) {
return false;
}
}
let Some(observed) = observe_ilm_recovery_export_fleet(expected_topology).await else {
let Some(observed) = observe_ilm_recovery_export_fleet(expected_topology.as_str()).await else {
return false;
};
let state = ilm_recovery_export_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
ilm_recovery_export_fleet_proof_matches_observation_at(&state, proof, expected_topology, &observed, Instant::now())
ilm_recovery_export_fleet_proof_matches_observation_at(&state, proof, expected_topology.as_str(), &observed, Instant::now())
}
pub fn ilm_recovery_export_topology_generation(proof: &IlmRecoveryExportFleetProofToken) -> String {
@@ -996,11 +1023,10 @@ fn stable_tier_delete_journal_topology_generation(topology_fingerprint: &str) ->
#[cfg(any(test, feature = "test-util"))]
pub(crate) fn install_cross_pool_fence_fleet_proof_for_test() {
let topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY
.get()
.cloned()
let topology = current_probe_topology()
.map(|value| value.as_ref().clone())
.unwrap_or_else(|| "pool-activation-test-topology".to_string());
let _ = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology.clone());
let _ = set_probe_topology_once(topology.clone());
let mut state = cross_pool_fence_fleet_proof_slot()
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
@@ -1250,11 +1276,11 @@ fn fleet_capability_proof_matches(
slot: &std::sync::RwLock<FleetCapabilityProofState>,
proof: &FleetCapabilityProofToken,
) -> bool {
let Some(expected_topology) = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() else {
let Some(expected_topology) = current_probe_topology() else {
return false;
};
let state = slot.read().unwrap_or_else(std::sync::PoisonError::into_inner);
fleet_capability_proof_matches_at(&state, proof, expected_topology, Instant::now())
fleet_capability_proof_matches_at(&state, proof, expected_topology.as_str(), Instant::now())
}
fn fleet_capability_proof_matches_at(
@@ -1288,12 +1314,9 @@ impl Drop for RemoteVersionStateFleetProofGuard {
#[cfg(test)]
pub(crate) fn install_remote_version_state_fleet_proof_for_test(topology_fingerprint: &str) -> RemoteVersionStateFleetProofGuard {
match REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology_fingerprint.to_string()) {
match set_probe_topology_once(topology_fingerprint.to_string()) {
Ok(()) => {}
Err(_)
if REMOTE_VERSION_STATE_PROBE_TOPOLOGY
.get()
.is_some_and(|current| current == topology_fingerprint) => {}
Err(_) if current_probe_topology().is_some_and(|current| current.as_str() == topology_fingerprint) => {}
Err(_) => panic!("remote version state test topology is already bound to another fingerprint"),
}
let peer_epochs = BTreeMap::new();
@@ -1310,10 +1333,9 @@ pub(crate) fn install_remote_version_state_fleet_proof_for_test(topology_fingerp
#[cfg(all(test, feature = "test-util"))]
pub(crate) fn install_current_remote_version_state_fleet_proof_for_test() -> RemoteVersionStateFleetProofGuard {
let topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY
.get()
.expect("the test store must bind its fleet topology before installing a writer proof");
install_remote_version_state_fleet_proof_for_test(topology)
let topology =
current_probe_topology().expect("the test store must bind its fleet topology before installing a writer proof");
install_remote_version_state_fleet_proof_for_test(topology.as_str())
}
#[cfg(all(test, feature = "test-util"))]
@@ -1330,13 +1352,12 @@ impl Drop for TransitionTransactionCompactionFleetProofGuard {
pub(crate) fn install_transition_transaction_compaction_fleet_proof_for_test(
topology_fingerprint: &str,
) -> TransitionTransactionCompactionFleetProofGuard {
let _ = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology_fingerprint.to_string());
let effective_topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY
.get()
.expect("transition transaction compaction test topology should be initialized");
let _ = set_probe_topology_once(topology_fingerprint.to_string());
let effective_topology =
current_probe_topology().expect("transition transaction compaction test topology should be initialized");
if let Some(err) = publish_fleet_capability_probe_result(
transition_transaction_compaction_fleet_proof_slot(),
effective_topology,
effective_topology.as_str(),
Ok(BTreeMap::new()),
Instant::now(),
) {
@@ -1385,7 +1406,7 @@ pub fn mrf_lifecycle_writer_fleet_proof_current(proof: &MrfLifecycleWriterFleetP
let state = mrf_lifecycle_writer_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, topology, Instant::now())
mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, &topology, Instant::now())
}
fn mrf_lifecycle_writer_fleet_proof_slot() -> &'static std::sync::RwLock<FleetCapabilityProofState> {
@@ -1401,8 +1422,8 @@ pub fn mrf_lifecycle_reader_local_process_epoch() -> Uuid {
pub async fn acquire_mrf_lifecycle_writer_fleet_proof(local_reader_max_format: u8) -> Option<MrfLifecycleWriterFleetProofToken> {
let expected_topology = configured_fleet_topology_fingerprint()?;
let observed_at = Instant::now();
let observed = observe_mrf_lifecycle_reader_fleet(expected_topology, local_reader_max_format).await;
if publish_fleet_capability_probe_result(mrf_lifecycle_writer_fleet_proof_slot(), expected_topology, observed, observed_at)
let observed = observe_mrf_lifecycle_reader_fleet(&expected_topology, local_reader_max_format).await;
if publish_fleet_capability_probe_result(mrf_lifecycle_writer_fleet_proof_slot(), &expected_topology, observed, observed_at)
.is_some()
{
return None;
@@ -1410,7 +1431,7 @@ pub async fn acquire_mrf_lifecycle_writer_fleet_proof(local_reader_max_format: u
let state = mrf_lifecycle_writer_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
acquire_mrf_lifecycle_writer_fleet_proof_from(&state, expected_topology, local_reader_max_format, Instant::now())
acquire_mrf_lifecycle_writer_fleet_proof_from(&state, &expected_topology, local_reader_max_format, Instant::now())
}
fn acquire_mrf_lifecycle_writer_fleet_proof_from(
@@ -1457,11 +1478,11 @@ pub async fn mrf_lifecycle_writer_fleet_proof_matches(proof: &MrfLifecycleWriter
let state = mrf_lifecycle_writer_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, expected_topology, Instant::now()) {
if !mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, &expected_topology, Instant::now()) {
return false;
}
}
let observed = observe_mrf_lifecycle_reader_fleet(expected_topology, proof.local_reader_max_format).await;
let observed = observe_mrf_lifecycle_reader_fleet(&expected_topology, proof.local_reader_max_format).await;
let mut state = mrf_lifecycle_writer_fleet_proof_slot()
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
@@ -1469,7 +1490,7 @@ pub async fn mrf_lifecycle_writer_fleet_proof_matches(proof: &MrfLifecycleWriter
revoke_fleet_capability_proof_state(&mut state);
return false;
}
mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, expected_topology, Instant::now())
mrf_lifecycle_writer_fleet_proof_matches_at(&state, proof, &expected_topology, Instant::now())
}
async fn observe_mrf_lifecycle_reader_fleet(
@@ -1508,8 +1529,8 @@ fn mrf_lifecycle_reader_epoch_map(
}
pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.set(topology_fingerprint.clone()).is_err() {
if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get() != Some(&topology_fingerprint) {
if set_probe_topology_once(topology_fingerprint.clone()).is_err() {
if current_probe_topology().as_deref().map(String::as_str) != Some(topology_fingerprint.as_str()) {
for slot in all_fleet_capability_proof_slots() {
mark_fleet_capability_topology_conflict(slot);
}
@@ -1520,6 +1541,12 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
tokio::spawn(async move {
let mut notification_sys_unavailable_logged = false;
loop {
let Some(active_topology) = current_probe_topology() else {
revoke_all_fleet_capability_proofs();
let _ = timeout(REMOTE_VERSION_STATE_PROBE_BOOTSTRAP_INTERVAL, NOTIFICATION_SYS_PUBLISHED.notified()).await;
continue;
};
let topology_fingerprint = active_topology.as_ref();
let Some(notification_sys) = get_global_notification_sys() else {
// Startup publishes the notification system after this probe
// is started. Stay failed closed, but retry on the bootstrap
@@ -1543,7 +1570,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
let remote_version_state_probe = async {
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_remote_version_state_fleet(&topology_fingerprint),
notification_sys.probe_remote_version_state_fleet(topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("remote version state fleet capability probe timed out")))
@@ -1551,7 +1578,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
let cross_pool_fence_probe = async {
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_cross_pool_fence_fleet(&topology_fingerprint),
notification_sys.probe_cross_pool_fence_fleet(topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("cross-pool fence fleet capability probe timed out")))
@@ -1559,7 +1586,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
let recovery_export_probe = async {
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_ilm_recovery_export_fleet(&topology_fingerprint),
notification_sys.probe_ilm_recovery_export_fleet(topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("ILM recovery export fleet capability probe timed out")))
@@ -1567,7 +1594,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
let transition_transaction_compaction_probe = async {
timeout(
REMOTE_VERSION_STATE_PROBE_TIMEOUT,
notification_sys.probe_transition_transaction_compaction_fleet(&topology_fingerprint),
notification_sys.probe_transition_transaction_compaction_fleet(topology_fingerprint),
)
.await
.unwrap_or_else(|_| Err(Error::other("transition transaction compaction fleet capability probe timed out")))
@@ -1598,7 +1625,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
revoke_all_fleet_capability_proofs();
} else if let Some(err) = publish_fleet_capability_probe_result(
remote_version_state_fleet_proof_slot(),
&topology_fingerprint,
topology_fingerprint,
result,
Instant::now(),
) {
@@ -1607,7 +1634,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
if !topology_conflict
&& let Some(err) = publish_fleet_capability_probe_result(
cross_pool_fence_fleet_proof_slot(),
&topology_fingerprint,
topology_fingerprint,
fence_result,
Instant::now(),
)
@@ -1625,7 +1652,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
if !topology_conflict
&& let Some(err) = publish_fleet_capability_probe_result(
ilm_recovery_export_fleet_proof_slot(),
&topology_fingerprint,
topology_fingerprint,
recovery_export_result,
Instant::now(),
)
@@ -1643,7 +1670,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
if !topology_conflict
&& let Some(err) = publish_fleet_capability_probe_result(
transition_transaction_compaction_fleet_proof_slot(),
&topology_fingerprint,
topology_fingerprint,
transition_transaction_compaction_result,
Instant::now(),
)
@@ -1661,7 +1688,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
if !topology_conflict
&& let Some(err) = publish_fleet_capability_probe_result(
tier_delete_journal_fleet_proof_slot(),
&topology_fingerprint,
topology_fingerprint,
journal_result,
Instant::now(),
)
@@ -1679,7 +1706,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
if !topology_conflict
&& let Some(err) = publish_fleet_capability_probe_result(
decommission_target_fence_fleet_proof_slot(),
&topology_fingerprint,
topology_fingerprint,
decommission_target_fence_result,
Instant::now(),
)
@@ -1697,7 +1724,7 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
if !topology_conflict
&& let Some(err) = publish_fleet_capability_probe_result(
legacy_transition_state_reconcile_fleet_proof_slot(),
&topology_fingerprint,
topology_fingerprint,
reconcile_result,
Instant::now(),
)
@@ -1712,13 +1739,37 @@ pub fn start_remote_version_state_fleet_probe(topology_fingerprint: String) {
"notification capability probe"
);
}
sleep(REMOTE_VERSION_STATE_PROBE_INTERVAL).await;
let probe_degraded = topology_conflict
|| decommission_target_fence_fleet_proof_slot()
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.proof
.is_none();
let sleep_interval = if probe_degraded {
Duration::from_millis(250)
} else {
REMOTE_VERSION_STATE_PROBE_INTERVAL
};
let _ = timeout(sleep_interval, NOTIFICATION_SYS_PUBLISHED.notified()).await;
}
});
}
/// Immediately wake the fleet capability probe loop (for example, once all peers
/// have committed a live pool topology hot-reload).
pub fn trigger_fleet_capability_probe_refresh() {
NOTIFICATION_SYS_PUBLISHED.notify_one();
}
/// Returns whether this node currently holds a valid fleet capability proof for
/// cross-pool decommission target fencing on the active topology.
pub fn has_decommission_target_fence_fleet_proof() -> bool {
acquire_decommission_target_fence_fleet_proof().is_some()
}
pub async fn new_global_notification_sys(eps: EndpointServerPools) -> Result<()> {
if GLOBAL_NOTIFICATION_SYS.set(Arc::new(NotificationSys::new(eps).await)).is_ok() {
if GLOBAL_NOTIFICATION_SYS.load().is_none() {
GLOBAL_NOTIFICATION_SYS.store(Some(Arc::new(NotificationSys::new(eps).await)));
// `notify_one` stores a permit, so a probe that checks availability
// just before this publication still wakes without losing the signal.
NOTIFICATION_SYS_PUBLISHED.notify_one();
@@ -1726,11 +1777,28 @@ pub async fn new_global_notification_sys(eps: EndpointServerPools) -> Result<()>
Ok(())
}
/// Atomically replace the global notification system during a live pool
/// topology hot-reload, optionally updating the active fleet probe topology
/// fingerprint and waking the fleet capability probe immediately.
pub async fn replace_global_notification_sys(
eps: EndpointServerPools,
topology_fingerprint: Option<String>,
) -> Arc<NotificationSys> {
let next = Arc::new(NotificationSys::new(eps).await);
GLOBAL_NOTIFICATION_SYS.store(Some(next.clone()));
if let Some(fingerprint) = topology_fingerprint {
replace_remote_version_state_probe_topology(fingerprint);
} else {
NOTIFICATION_SYS_PUBLISHED.notify_one();
}
next
}
// Owned handle rather than `&'static` (backlog#1052 S3): per-server contexts
// need to hold their own notification system, which a process-lifetime
// borrow cannot express.
pub fn get_global_notification_sys() -> Option<Arc<NotificationSys>> {
GLOBAL_NOTIFICATION_SYS.get().cloned()
GLOBAL_NOTIFICATION_SYS.load_full()
}
pub struct NotificationSys {
@@ -4383,7 +4451,7 @@ mod tests {
/// to publish the notification system.
#[tokio::test]
async fn fleet_probe_publishes_promptly_once_the_notification_system_appears() {
if REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get().is_some() || GLOBAL_NOTIFICATION_SYS.get().is_some() {
if current_probe_topology().is_some() || GLOBAL_NOTIFICATION_SYS.load().is_some() {
// Process-wide state was bound by another test in this binary. The
// startup ordering under test needs a fresh process; nextest
// (the authoritative runner) always provides one.
@@ -4634,7 +4702,8 @@ mod tests {
use crate::layout::endpoint::Endpoint;
temp_env::async_with_vars([(rustfs_config::ENV_DRIVE_MAX_TIMEOUT_DURATION, Some("60"))], async {
let topology = REMOTE_VERSION_STATE_PROBE_TOPOLOGY.get_or_init(|| "mrf-cas-test".to_owned());
let _ = set_probe_topology_once("mrf-cas-test".to_owned());
let topology = current_probe_topology().expect("mrf-cas-test topology should be initialized");
let slot = mrf_lifecycle_writer_fleet_proof_slot();
for cancel_waiter in [true, false] {
let root = tempfile::tempdir().expect("isolated CAS fixture");
@@ -4651,11 +4720,11 @@ mod tests {
.expect("native CAS publication path");
std::fs::write(&path, b"old").expect("old committed file");
let peers = BTreeMap::from([("local".to_owned(), Uuid::new_v4())]);
assert!(publish_fleet_capability_probe_result(slot, topology, Ok(peers), Instant::now()).is_none());
assert!(publish_fleet_capability_probe_result(slot, topology.as_str(), Ok(peers), Instant::now()).is_none());
let proof = Arc::new(
acquire_mrf_lifecycle_writer_fleet_proof_from(
&slot.read().expect("proof state"),
topology,
&topology,
2,
Instant::now(),
)
@@ -4700,7 +4769,7 @@ mod tests {
}
assert!(weak.upgrade().is_some(), "the native worker still owns the permit");
let restarted = BTreeMap::from([("local".to_owned(), Uuid::new_v4())]);
assert!(publish_fleet_capability_probe_result(slot, topology, Ok(restarted.clone()), Instant::now()).is_some());
assert!(publish_fleet_capability_probe_result(slot, &topology, Ok(restarted.clone()), Instant::now()).is_some());
assert_eq!(std::fs::read(&path).expect("old file retained while blocked"), b"old");
drop(release_tx);
timeout(Duration::from_secs(5), async {
@@ -4711,7 +4780,7 @@ mod tests {
.await
.expect("native worker drains");
assert_eq!(std::fs::read(&path).expect("revoked writer cannot publish"), b"old");
assert!(publish_fleet_capability_probe_result(slot, topology, Ok(restarted), Instant::now()).is_none());
assert!(publish_fleet_capability_probe_result(slot, &topology, Ok(restarted), Instant::now()).is_none());
revoke_fleet_capability_proof(slot);
}
})
@@ -1080,7 +1080,10 @@ impl ECStore {
#[tracing::instrument(skip(self, bucktes))]
pub async fn init_rebalance_start(self: &Arc<Self>, bucktes: Vec<String>) -> Result<String> {
let movement_start_gate = self.ctx.movement_start_gate();
let _instance_start_guard = movement_start_gate.lock().await;
let _start_guard = self.start_gate.lock().await;
self.ensure_not_retired()?;
{
let decommission_running = self.is_decommission_running().await;
let rebalance_meta = self.rebalance_meta.read().await;
@@ -1099,7 +1102,10 @@ impl ECStore {
#[tracing::instrument(skip(self))]
pub async fn start_rebalance_for_id(self: &Arc<Self>, expected_id: &str) -> Result<()> {
let movement_start_gate = self.ctx.movement_start_gate();
let _instance_start_guard = movement_start_gate.lock().await;
let _start_guard = self.start_gate.lock().await;
self.ensure_not_retired()?;
let _activation_guard = self
.rebalance_activation_write_guard(Some(expected_id), "start rebalance")
.await?;
@@ -177,7 +177,10 @@ pub(super) fn rollback_local_rebalance_worker_activation(
impl ECStore {
#[tracing::instrument(skip_all)]
pub async fn start_rebalance(self: &Arc<Self>) -> Result<()> {
let movement_start_gate = self.ctx.movement_start_gate();
let _instance_start_guard = movement_start_gate.lock().await;
let _start_guard = self.start_gate.lock().await;
self.ensure_not_retired()?;
let _activation_guard = self.rebalance_activation_write_guard(None, "start rebalance").await?;
let movement_gate = self.ctx.data_movement_operation_gate();
let _movement_guard = movement_gate.write().await;
+13 -5
View File
@@ -6898,10 +6898,15 @@ impl TierConfigMgr {
}
pub(crate) async fn refresh_tier_config_handle(handle: Arc<RwLock<Self>>, api: Arc<ECStore>) {
Self::refresh_tier_config_handle_with_weak(handle, Arc::downgrade(&api)).await;
let instance_ctx = api.ctx.clone();
Self::refresh_tier_config_handle_with_weak(handle, instance_ctx, Arc::downgrade(&api)).await;
}
async fn refresh_tier_config_handle_with_weak(handle: Arc<RwLock<Self>>, api: Weak<ECStore>) {
async fn refresh_tier_config_handle_with_weak(
handle: Arc<RwLock<Self>>,
instance_ctx: Arc<crate::runtime::instance::InstanceContext>,
api: Weak<ECStore>,
) {
// The periodic refresh remains the recovery fallback; committed mutations
// notify this worker so a successful peer commit converges immediately.
let mutation_refresh = Self::mutation_refresh_notifier(&handle).await;
@@ -6913,7 +6918,7 @@ impl TierConfigMgr {
loop {
select! {
_ = t.tick() => {
let Some(api) = Weak::upgrade(&api) else {
let Some(api) = instance_ctx.live_store().or_else(|| Weak::upgrade(&api)) else {
return;
};
if let Err(err) = Self::reload_handle_with(&handle, api).await {
@@ -6929,7 +6934,7 @@ impl TierConfigMgr {
}
}
_ = mutation_refresh.notified() => {
let Some(api) = Weak::upgrade(&api) else {
let Some(api) = instance_ctx.live_store().or_else(|| Weak::upgrade(&api)) else {
return;
};
Self::reload_after_committed_mutation(&handle, api).await;
@@ -7625,7 +7630,10 @@ mod tests {
Ok(_) => panic!("an older generic S3 driver must not operate a Wasabi compatibility envelope"),
Err(err) => err,
};
assert!(err.to_string().contains("missing a host"), "{err}");
assert_eq!(
err.to_string(),
format!("tier endpoint is not allowed: outbound URL scheme '{EXTERNAL_TIER_VERSION_WASABI_V1}' is not allowed")
);
let mut generic_s3 = old_node_rewrite.clone();
generic_s3
@@ -5015,6 +5015,8 @@ impl SetDisks {
.await
}
Disk::Local(_) => Err(RenameBatchStartError::NotDispatched(DiskError::Unexpected)),
#[cfg(feature = "dst")]
Disk::Sim(_) => Err(RenameBatchStartError::NotDispatched(DiskError::Unexpected)),
}
};
match start {
@@ -60,6 +60,11 @@ async fn recover_on_disk(
let _namespace_owner = namespace_owner;
remote.recover_multipart_source(request).await
}
#[cfg(feature = "dst")]
crate::disk::Disk::Sim(sim) => {
let _namespace_owner = namespace_owner;
sim.recover_multipart_source(request).await
}
}
}
+27 -7
View File
@@ -301,6 +301,17 @@ fn rename_tail_heal_suppressed_for_e2e(bucket: &str, object: Option<&str>) -> bo
}
impl SetDisks {
#[cfg(feature = "dst")]
pub fn invalidate_metadata_cache_for_dst(&self) {
self.get_object_metadata_cache.invalidate_all();
for g in self.get_object_metadata_cache_generations.iter() {
g.fetch_add(1, Ordering::AcqRel);
}
if let Ok(mut hc) = self.disk_health_cache.try_write() {
hc.clear();
}
}
pub(super) async fn require_current_restore_operation_id(
&self,
bucket: &str,
@@ -4816,7 +4827,10 @@ pub struct SetDisks {
/// Hermetic sets may retain shared services while owning isolated proof scopes.
#[cfg(test)]
multipart_proof_authority_override: Arc<std::sync::RwLock<Option<crate::disk::multipart_source::ProofVerificationContext>>>,
#[cfg(test)]
/// Optional per-set storage class override used during live topology
/// hot-reload staging (so the candidate generation validates/writes metadata
/// against its own pool layout while the previous generation serves traffic)
/// and in hermetic unit tests.
storage_class_config_override: Arc<std::sync::RwLock<Option<Arc<storageclass::Config>>>>,
#[cfg(test)]
rename_tail_heal_capture: Arc<
@@ -5461,11 +5475,10 @@ impl SetDisks {
}
fn storage_class_config_snapshot(&self) -> Arc<storageclass::Config> {
#[cfg(test)]
if let Some(config) = self
.storage_class_config_override
.read()
.expect("test storage class override lock should not be poisoned")
.unwrap_or_else(std::sync::PoisonError::into_inner)
.as_ref()
{
return config.clone();
@@ -5474,12 +5487,20 @@ impl SetDisks {
runtime_sources::storage_class_config_snapshot()
}
#[cfg(test)]
pub(crate) fn set_test_storage_class_config(&self, config: storageclass::Config) {
/// Pin or clear an explicit storage class snapshot on this erasure set.
/// Used during zero-downtime topology hot-reload so candidate sets write
/// pool metadata against the target pool layout and retiring sets keep
/// serving in-flight requests against the previous layout.
pub(crate) fn set_storage_class_config_override(&self, config: Option<Arc<storageclass::Config>>) {
*self
.storage_class_config_override
.write()
.expect("test storage class override lock should not be poisoned") = Some(Arc::new(config));
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
}
#[cfg(test)]
pub(crate) fn set_test_storage_class_config(&self, config: storageclass::Config) {
self.set_storage_class_config_override(Some(Arc::new(config)));
}
fn get_object_metadata_cache_hash(&self, bucket: &str, object: &str) -> u64 {
@@ -5776,7 +5797,6 @@ impl SetDisks {
orphan_purge_backoff: Arc::new(std::sync::Mutex::new(HashMap::new())),
#[cfg(test)]
multipart_proof_authority_override: Arc::new(std::sync::RwLock::new(None)),
#[cfg(test)]
storage_class_config_override: Arc::new(std::sync::RwLock::new(None)),
#[cfg(test)]
rename_tail_heal_capture: Arc::new(std::sync::Mutex::new(None)),
@@ -139,6 +139,12 @@ impl WrittenBitrotShards<'_> {
let reader = local.read_file(RUSTFS_META_TMP_BUCKET, &path).await?;
coding::bitrot_verify(reader, encoded_size, target.logical_shard_size, algo, target.shard_size).await?;
}
#[cfg(feature = "dst")]
Disk::Sim(sim) => {
let path = format!("{directory}/part.{number}");
let reader = sim.read_file(RUSTFS_META_TMP_BUCKET, &path).await?;
coding::bitrot_verify(reader, encoded_size, target.logical_shard_size, algo, target.shard_size).await?;
}
Disk::Remote(peer) => {
let fi = staged_part_file_info(layout, index + 1, number, *part_size, target.shard_size)?;
let response = peer.verify_staged_part(directory, &fi, encoded_size).await?;
@@ -25944,6 +25944,8 @@ mod put_object_tmp_cleanup_tests {
.map(|disk| match disk.as_ref() {
disk::Disk::Local(local) => local,
disk::Disk::Remote(_) => panic!("hermetic fixture must use local disks"),
#[cfg(feature = "dst")]
disk::Disk::Sim(_) => panic!("hermetic fixture must use local disks"),
})
.collect();
let before: Vec<_> = local_disks
+31 -7
View File
@@ -521,6 +521,16 @@ async fn bucket_delete_local_blocker(
Ok(None)
}
// Keep the large `handle_make_bucket_inner` state machine out of unoptimized
// caller poll frames when both `live_store()` and `self` branches are present.
#[inline(never)]
fn box_make_bucket_future<F>(make_future: impl FnOnce() -> F) -> std::pin::Pin<Box<F>>
where
F: Future,
{
Box::pin(make_future())
}
impl ECStore {
/// Fail the next real creation of this bucket after persisting its intent.
#[cfg(any(test, feature = "test-util"))]
@@ -1686,9 +1696,19 @@ impl ECStore {
#[instrument(level = "trace", skip(self))]
pub(super) async fn handle_make_bucket(&self, bucket: &str, opts: &MakeBucketOptions) -> Result<()> {
// Serialize against live topology hot-reload cutover so a concurrent
// `CreateBucket` never straddles two store generations or misses physical
// bucket directory propagation onto newly expanded pools.
let gate = self.ctx.bucket_topology_gate();
let _topology_guard = gate.read().await;
if let Some(live) = self.ctx.live_store()
&& !std::ptr::eq(Arc::as_ptr(&live), self as *const Self)
{
return box_make_bucket_future(|| live.handle_make_bucket_inner(bucket, opts, None)).await;
}
// Metadata persistence re-enters native PUT/GET. Keep its full state
// out of the tracing wrapper's poll frame on bounded runtime stacks.
Box::pin(self.handle_make_bucket_inner(bucket, opts, None)).await
box_make_bucket_future(|| self.handle_make_bucket_inner(bucket, opts, None)).await
}
/// Create a managed bucket with its complete identity and encryption in the creation intent.
@@ -1710,12 +1730,16 @@ impl ECStore {
{
return Err(Error::PreconditionFailed);
}
Box::pin(self.handle_make_bucket_inner(
identity.storage_bucket_id().as_str(),
opts,
Some((identity, encryption_config_xml, tagging_config_xml)),
))
.await
let gate = self.ctx.bucket_topology_gate();
let _topology_guard = gate.read().await;
let managed = Some((identity, encryption_config_xml, tagging_config_xml));
let bucket = identity.storage_bucket_id().as_str();
if let Some(live) = self.ctx.live_store()
&& !std::ptr::eq(Arc::as_ptr(&live), self as *const Self)
{
return box_make_bucket_future(|| live.handle_make_bucket_inner(bucket, opts, managed)).await;
}
box_make_bucket_future(|| self.handle_make_bucket_inner(bucket, opts, managed)).await
}
async fn handle_make_bucket_inner(
@@ -410,6 +410,54 @@ impl DeleteRecoveryHints {
.started
.insert(store)
}
/// Remap positional `(pool, set)` delete recovery hints across a committed
/// topology hot-reload (`old_pool_idx -> new_pool_idx`), pruning removed
/// pools, resetting worker start registration so the successor generation
/// spawns its recovery task, and scheduling a rescan for added pools.
pub(crate) fn reset_on_topology_reload(&self, old_to_new_pool: &HashMap<usize, usize>) {
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
state.started.clear();
state.rescan = Some(Uuid::new_v4());
let old_drive_returns = std::mem::take(&mut state.drive_returns);
for ((old_pool, set), gen_id) in old_drive_returns {
if let Some(&new_pool) = old_to_new_pool.get(&old_pool) {
state.drive_returns.insert((new_pool, set), gen_id);
}
}
let old_evicted = std::mem::take(&mut state.evicted_retries);
for (old_key, retry) in old_evicted {
if let Some(&new_pool) = old_to_new_pool.get(&old_key.pool) {
let mut remapped = (*old_key).clone();
remapped.pool = new_pool;
state.evicted_retries.insert(Arc::new(remapped), retry);
}
}
let old_pending = std::mem::take(&mut state.pending);
let old_order = std::mem::take(&mut state.order);
let mut key_map: HashMap<Arc<DeleteRecoveryKey>, Arc<DeleteRecoveryKey>> = HashMap::with_capacity(old_pending.len());
for (old_key, entry) in old_pending {
if let Some(&new_pool) = old_to_new_pool.get(&old_key.pool) {
let new_key = if new_pool == old_key.pool {
old_key.clone()
} else {
let mut remapped = (*old_key).clone();
remapped.pool = new_pool;
Arc::new(remapped)
};
key_map.insert(old_key, new_key.clone());
state.pending.insert(new_key, entry);
}
}
for (old_key, slot) in old_order {
if let Some(new_key) = key_map.get(&old_key) {
state.order.push_back((new_key.clone(), slot));
}
}
}
}
#[derive(Clone)]
@@ -660,6 +708,8 @@ impl RecoveryPass {
let renewed = match scan.source.disk.as_ref() {
crate::disk::Disk::Local(local) => local.get_disk().renew_delete_recovery_cursor(&bucket.bucket, cursor),
crate::disk::Disk::Remote(_) => false,
#[cfg(feature = "dst")]
crate::disk::Disk::Sim(_) => false,
};
if !renewed {
bucket.cursor = None;
+4 -2
View File
@@ -14,7 +14,7 @@
use super::init_format::{
check_format_erasure_values, formats_match_reference_slots, legacy_format_max_bytes, read_legacy_format_bytes,
retain_format_quorum_members, write_format_file,
retain_format_quorum_members_with_mode, write_format_file,
};
use crate::disk::{DiskAPI, DiskStore, RUSTFS_META_BUCKET, error::DiskError, format::FormatV3};
use crate::error::{Error, Result};
@@ -105,6 +105,7 @@ pub(super) async fn write_format_bootstrap_intents(disks: &[Option<DiskStore>],
/// Completes an anchored plan before its first format publication, or restores
/// explicitly unformatted slots from a complete durable intent set. Partial
/// intent sets grant no authority once any format has been published.
#[allow(clippy::too_many_arguments)]
pub(super) async fn resume_format_bootstrap(
instance_ctx: &Arc<InstanceContext>,
disks: &mut [Option<DiskStore>],
@@ -113,6 +114,7 @@ pub(super) async fn resume_format_bootstrap(
set_count: usize,
set_drive_count: usize,
deployment_id: Option<Uuid>,
staged_mode: bool,
) -> Result<Option<FormatV3>> {
if disks.is_empty()
|| disks.len() != formats.len()
@@ -220,7 +222,7 @@ pub(super) async fn resume_format_bootstrap(
format.erasure.this = Uuid::nil();
format.disk_info = None;
let members = vec![true; disks.len()];
retain_format_quorum_members(instance_ctx, disks, &format, &members, None, set_drive_count).await?;
retain_format_quorum_members_with_mode(instance_ctx, disks, &format, &members, None, set_drive_count, staged_mode).await?;
Ok(Some(format))
}
+295 -32
View File
@@ -32,7 +32,7 @@ const EVENT_STORE_FORMAT_RETRY: &str = "store_format_retry";
const EVENT_ECSTORE_INIT_STATUS: &str = "ecstore_init_status";
const EVENT_STORE_RPC_SECRET_PREFLIGHT_FAILED: &str = "store_rpc_secret_preflight_failed";
fn pool_first_endpoint_is_local(pool: &crate::layout::endpoints::PoolEndpoints) -> bool {
pub(super) fn pool_first_endpoint_is_local(pool: &crate::layout::endpoints::PoolEndpoints) -> bool {
pool.endpoints.as_ref().first().is_some_and(|endpoint| endpoint.is_local)
}
@@ -40,7 +40,7 @@ fn startup_pool_drive_counts(endpoint_pools: &EndpointServerPools) -> Vec<usize>
endpoint_pools.as_ref().iter().map(|pool| pool.drives_per_set).collect()
}
fn resolve_startup_pool_defaults(endpoint_pools: &EndpointServerPools) -> Result<Vec<usize>> {
pub(super) fn resolve_startup_pool_defaults(endpoint_pools: &EndpointServerPools) -> Result<Vec<usize>> {
resolve_startup_pool_defaults_with(endpoint_pools, ECStore::validate_startup_storage_class)
}
@@ -57,7 +57,7 @@ fn resolve_startup_pool_defaults_with(
/// resolves. Every remote format read would otherwise fail client-side with
/// "No valid auth token" and startup would retry for minutes before dying with
/// a misleading "erasure read quorum" error (issues #4939, #5153).
fn preflight_startup_rpc_secret(endpoint_pools: &EndpointServerPools) -> Result<()> {
pub(super) fn preflight_startup_rpc_secret(endpoint_pools: &EndpointServerPools) -> Result<()> {
preflight_startup_rpc_secret_with(endpoint_pools, try_get_rpc_token)
}
@@ -101,14 +101,14 @@ const LOCAL_DECOMMISSION_WATCHDOG_MAX_RETRY_DELAY: Duration = Duration::from_sec
const REBALANCE_INITIAL_RESUME_DELAY: Duration = Duration::from_secs(10);
const REBALANCE_RESUME_RETRY_DELAY: Duration = Duration::from_secs(10);
fn should_retry_format_load(err: &Error) -> bool {
pub(super) fn should_retry_format_load(err: &Error) -> bool {
!matches!(
err,
Error::CorruptedFormat | Error::UnsupportedSnsdExpansion { .. } | Error::PoolTopologyMismatch { .. }
)
}
fn format_load_retry_exhausted(err: &Error, retries: u32) -> bool {
pub(super) fn format_load_retry_exhausted(err: &Error, retries: u32) -> bool {
retries >= 10 && !matches!(err, Error::ErasureReadQuorum | Error::FirstDiskWait | Error::NotFirstDisk)
}
@@ -480,8 +480,64 @@ impl ECStore {
/// Validate topology and process storage-class overrides before any disk is opened.
pub fn validate_startup_storage_class(endpoint_pools: &EndpointServerPools) -> Result<()> {
Self::validate_storage_class_with_kvs(endpoint_pools, None).map(|_| ())
}
/// Validate storage-class parity settings against `endpoint_pools`, merging
/// persisted `server_config` storage-class KVS with optional candidate overrides.
pub fn validate_storage_class_with_kvs(
endpoint_pools: &EndpointServerPools,
extra_kvs: Option<&KVS>,
) -> Result<storageclass::Config> {
let drive_counts = startup_pool_drive_counts(endpoint_pools);
storageclass::lookup_config_for_pools(&KVS::new(), &drive_counts).map(|_| ())
let mut merged = runtime_sources::server_config()
.and_then(|cfg| cfg.get_value(crate::config::com::STORAGE_CLASS_SUB_SYS, rustfs_config::DEFAULT_DELIMITER))
.unwrap_or_default();
if let Some(extra) = extra_kvs {
for kv in &extra.0 {
merged.insert(kv.key.clone(), kv.value.clone());
}
}
storageclass::lookup_config_for_pools(&merged, &drive_counts)
}
/// Validate storage-class parity settings against `endpoint_pools`, applying
/// optional staged `STANDARD` and `RRS` overrides from a candidate env file.
pub fn validate_storage_class_with_overrides(
endpoint_pools: &EndpointServerPools,
standard_override: Option<&str>,
rrs_override: Option<&str>,
) -> Result<()> {
let drive_counts = startup_pool_drive_counts(endpoint_pools);
let merged = runtime_sources::server_config()
.and_then(|cfg| cfg.get_value(crate::config::com::STORAGE_CLASS_SUB_SYS, rustfs_config::DEFAULT_DELIMITER))
.unwrap_or_default();
storageclass::lookup_config_for_pools_with_overrides(
&merged,
&drive_counts,
standard_override
.map(str::trim)
.filter(|s| !s.is_empty())
.map(ToOwned::to_owned),
rrs_override.map(str::trim).filter(|s| !s.is_empty()).map(ToOwned::to_owned),
)
.map(|_| ())
}
/// Whether this `ECStore` generation has been superseded by a newer live
/// topology hot-reload generation on the same [`InstanceContext`].
pub fn is_retired(&self) -> bool {
let active = self.ctx.active_store_ptr();
active != 0 && active != std::ptr::from_ref(self) as usize
}
pub(crate) fn ensure_not_retired(&self) -> Result<()> {
if self.is_retired() {
return Err(Error::other(
"storage topology generation has been hot-reloaded; retry against active store",
));
}
Ok(())
}
#[allow(clippy::new_ret_no_self)]
@@ -690,6 +746,11 @@ impl ECStore {
if !instance_ctx.is_dist_erasure().await {
runtime_sources::record_local_disks(&instance_ctx, local_disks).await;
}
// Populate the local disk-ID lookup map now that all pools have loaded or
// created their `format.json`, so standby joining nodes immediately accept
// disk-ID-addressed RPCs without missing-disk races during hot-reload.
crate::store::peer::prewarm_local_disk_id_map_with_instance_ctx(&instance_ctx).await;
instance_ctx.mark_startup_formats_ready();
let deployment_id = deployment_id.ok_or_else(|| Error::other("store init failed: deployment id is not initialized"))?;
let peer_sys = S3PeerSys::new_with_instance_ctx(&endpoint_pools, instance_ctx.clone());
@@ -726,14 +787,62 @@ impl ECStore {
if instance_ctx.deployment_id().is_none() {
instance_ctx.set_deployment_id(deployment_id);
}
instance_ctx.set_live_store(&ec);
let wait_sec = 5;
let join_wait_timeout = Duration::from_secs(rustfs_utils::get_env_u64("RUSTFS_POOL_JOIN_WAIT_TIMEOUT_SECS", 1800));
let join_wait_started = tokio::time::Instant::now();
let mut exit_count = 0;
let mut standby_iters = 0_u64;
loop {
if let Err(err) = ec.init(ctx.clone()).await {
let bootstrap_pending = err.to_string().contains("pool metadata bootstrap pending");
if bootstrap_pending && join_wait_started.elapsed() < join_wait_timeout {
let standby_poll = Duration::from_secs(2);
if standby_iters == 0 {
info!(
event = EVENT_ECSTORE_INIT_STATUS,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_STORE_INIT,
stage = "pool_join_standby",
retry_delay_ms = standby_poll.as_millis() as u64,
"Waiting in standby for elected pool writer to commit hot-reloaded topology"
);
} else if standby_iters.is_multiple_of(15) {
debug!(
event = EVENT_ECSTORE_INIT_STATUS,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_STORE_INIT,
stage = "pool_join_standby",
standby_iters,
elapsed_secs = join_wait_started.elapsed().as_secs(),
"Still waiting in standby for elected pool writer to commit hot-reloaded topology"
);
}
standby_iters = standby_iters.saturating_add(1);
select! {
_ = ctx.cancelled() => {
return Err(Error::other(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"storage initialization cancelled while awaiting pool topology commit",
)));
}
_ = instance_ctx.wait_pool_join_wakeup() => {}
_ = sleep(standby_poll) => {}
}
continue;
}
error!("init err: {}", err);
error!("retry after {} second", wait_sec);
sleep(Duration::from_secs(wait_sec)).await;
select! {
_ = ctx.cancelled() => {
return Err(Error::other(std::io::Error::new(
std::io::ErrorKind::Interrupted,
"storage initialization cancelled",
)));
}
_ = sleep(Duration::from_secs(wait_sec)) => {}
}
if exit_count > 10 {
return Err(Error::other("store init failed: init retry budget exhausted"));
@@ -752,7 +861,7 @@ impl ECStore {
Ok(ec)
}
async fn init_pool_metadata_for_startup(self: &Arc<Self>) -> Result<(PoolMeta, PoolMetaReplicaState)> {
pub(super) async fn init_pool_metadata_for_startup(self: &Arc<Self>) -> Result<(PoolMeta, PoolMetaReplicaState)> {
let should_persist_pool_meta = self
.pools
.first()
@@ -1024,7 +1133,6 @@ impl ECStore {
}
let local_pool_indices = local_decommission_queue_prefix(&endpoints, &pool_indices)?;
let has_local_decommission_leadership = endpoints.as_ref().iter().any(pool_first_endpoint_is_local);
let pool_meta_write_safe = self
.ensure_pool_meta_side_effects_safe("decommission resume blocked while pool metadata requires recovery")
.await
@@ -1040,14 +1148,47 @@ impl ECStore {
"Decommission watchdog waiting for pool metadata recovery"
);
}
let gen_rx = self.spawn_generation_background_workers(&endpoints, &rx);
runtime_sources::init_bucket_monitor_for_current_endpoints();
crate::bucket::bucket_target_sys::BucketTargetSys::get().start_heartbeat();
init_background_expiry(self.clone()).await;
crate::bucket::lifecycle::bucket_lifecycle_ops::init_background_stale_multipart_upload_cleanup(self.clone());
TransitionState::init(self.clone()).await;
crate::services::tier::tier::try_migrate_tiering_config(self.clone()).await;
if let Err(err) = runtime_sources::init_tier_config_mgr(self.clone()).await {
info!("TierConfigMgr init error: {}", err);
}
if rebalance_auto_start_deferred {
let store = self.clone();
tokio::spawn(resume_rebalance_after_init(store, gen_rx));
}
Ok(())
}
/// Rotate the per-generation worker cancellation token (cancelling any retired
/// generation's loops) and spawn generation-bound supervisors (`decommission`
/// watchdog, `pool.bin` transaction recovery, and `delete_recovery`) onto `self`.
pub(super) fn spawn_generation_background_workers(
self: &Arc<Self>,
endpoints: &EndpointServerPools,
parent_rx: &CancellationToken,
) -> CancellationToken {
let gen_rx = self.ctx.rotate_generation_cancel(parent_rx);
let has_local_decommission_leadership = endpoints.as_ref().iter().any(pool_first_endpoint_is_local);
if has_local_decommission_leadership {
// The watchdog checks recovery safety and retries transient failures.
// Resume persisted work without an unconditional cold-start delay.
tokio::spawn(supervise_local_decommission_after_init(self.clone(), rx.clone()));
tokio::spawn(supervise_local_decommission_after_init(self.clone(), gen_rx.clone()));
}
let recovery_store = self.clone();
let recovery_rx = rx.clone();
let recovery_rx = gen_rx.clone();
tokio::spawn(async move {
let mut delay = std::time::Duration::from_secs(5);
loop {
@@ -1073,27 +1214,8 @@ impl ECStore {
}
});
super::delete_recovery_runtime::start_delete_recovery(self.clone(), rx.clone());
runtime_sources::init_bucket_monitor_for_current_endpoints();
crate::bucket::bucket_target_sys::BucketTargetSys::get().start_heartbeat();
init_background_expiry(self.clone()).await;
crate::bucket::lifecycle::bucket_lifecycle_ops::init_background_stale_multipart_upload_cleanup(self.clone());
TransitionState::init(self.clone()).await;
crate::services::tier::tier::try_migrate_tiering_config(self.clone()).await;
if let Err(err) = runtime_sources::init_tier_config_mgr(self.clone()).await {
info!("TierConfigMgr init error: {}", err);
}
if rebalance_auto_start_deferred {
let store = self.clone();
tokio::spawn(resume_rebalance_after_init(store, rx));
}
Ok(())
super::delete_recovery_runtime::start_delete_recovery(self.clone(), gen_rx.clone());
gen_rx
}
pub fn init_local_disks() {}
@@ -2095,6 +2217,147 @@ mod tests {
.expect("no latch remains after convergence");
}
#[tokio::test]
async fn test_single_pool_non_elected_follower_converges_without_latching_write_gate() {
let deployment_id = Uuid::new_v4();
let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
let pools = vec![pool0.clone()];
let mut elected = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities(
deployment_id,
vec![PoolMetaBootstrapAuthority::Fresh],
true,
);
let mut follower = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities(
deployment_id,
vec![PoolMetaBootstrapAuthority::None],
false,
);
assert!(!follower.bootstrap_identity_proven());
// Stage 1: before the elected writer mints a pending identity, the
// non-elected follower waits without writing or latching write_blocked.
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut follower, false)
.await
.expect("single-pool follower writes no identity before bootstrap");
let err = load_pool_meta_for_startup(pools.clone(), &mut follower)
.await
.expect_err("follower waits for elected writer to establish cluster identity");
assert!(
err.to_string()
.contains("waiting for the elected writer to establish the cluster identity"),
"{err}"
);
follower
.ensure_write_safe("single-pool follower before identity")
.expect("waiting for initial identity must not latch the write gate");
assert_eq!(pool0.identity_write_attempts.load(Ordering::SeqCst), 0);
assert_eq!(pool0.pool_meta_write_attempts.load(Ordering::SeqCst), 0);
// Stage 2: elected writer mints the nonce-bound pending identity, but
// has not yet published pool.bin; follower still waits unlatched.
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut elected, true)
.await
.expect("elected writer mints single-pool pending identity");
let minted_writes = pool0.identity_write_attempts.load(Ordering::SeqCst);
assert_eq!(minted_writes, 1);
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut follower, false)
.await
.expect("single-pool follower does not overwrite pending identity");
assert_eq!(pool0.identity_write_attempts.load(Ordering::SeqCst), minted_writes);
let err = load_pool_meta_for_startup(pools.clone(), &mut follower)
.await
.expect_err("follower waits for elected writer to publish pool.bin");
assert!(
err.to_string()
.contains("waiting for the elected writer to publish the initial pool.bin"),
"{err}"
);
follower
.ensure_write_safe("single-pool follower during pending identity")
.expect("waiting for initial pool.bin must not latch the write gate");
assert_eq!(pool0.pool_meta_write_attempts.load(Ordering::SeqCst), 0);
// Stage 3: elected writer commits V3 pool.bin and initialized identity;
// the same follower converges to write-ready with zero writes.
let (_, replica_state) = load_pool_meta_for_startup(pools.clone(), &mut elected)
.await
.expect("elected writer loads proven single-pool bootstrap");
persist_pool_meta_for_startup_if_safe(&init_test_pool_meta(None), pools.clone(), replica_state, &mut elected, true, true)
.await
.expect("elected writer commits V3 pool.bin and initialized identity");
let committed_identity_writes = pool0.identity_write_attempts.load(Ordering::SeqCst);
let committed_meta_writes = pool0.pool_meta_write_attempts.load(Ordering::SeqCst);
establish_pool_meta_bootstrap_identity_if_proven(pools.clone(), &mut follower, false)
.await
.expect("converged follower leaves initialized identity untouched");
load_pool_meta_for_startup(pools.clone(), &mut follower)
.await
.expect("published pool.bin admits single-pool follower");
complete_pool_meta_for_startup(pools, &mut follower, false, None, async {
panic!("converged follower must never execute intent retirement")
})
.await
.expect("converged single-pool follower completes startup read-only");
follower
.ensure_write_safe("converged single-pool follower")
.expect("converged follower remains write-ready");
assert_eq!(pool0.identity_write_attempts.load(Ordering::SeqCst), committed_identity_writes);
assert_eq!(pool0.pool_meta_write_attempts.load(Ordering::SeqCst), committed_meta_writes);
}
#[tokio::test]
async fn test_single_pool_non_elected_follower_escalates_hard_faults_to_latched_recovery() {
let deployment_id = Uuid::new_v4();
let initialized = initialized_pool_meta_identity_for_test(deployment_id, 1).expect("encode initialized identity");
let mut corrupt = pending_pool_meta_identity_for_test(deployment_id, 1, Uuid::new_v4()).expect("encode pending identity");
corrupt.truncate(4);
corrupt.extend_from_slice(b"corrupt single-pool identity");
for (label, bad_identity, expected_msg) in [
(
"initialized_missing_pool_meta",
initialized.clone(),
"initialized cluster identity exists",
),
("corrupt_identity_missing_pool_meta", corrupt, "corrupt"),
] {
let pool0 = Arc::new(StartupPoolMetaStorage::new(Vec::new()));
inject_startup_object(&pool0, POOL_META_IDENTITY_NAME, bad_identity);
let pools = vec![pool0.clone()];
let mut follower = PoolMetaWriteState::for_startup_with_pool_bootstrap_authorities(
deployment_id,
vec![PoolMetaBootstrapAuthority::None],
false,
);
let err = load_pool_meta_for_startup(pools.clone(), &mut follower)
.await
.expect_err("hard fault on single-pool follower must fail closed");
assert!(error_chain_text(&err).contains(expected_msg), "case={label} err={err}");
let latch = follower
.ensure_write_safe("single-pool follower hard fault")
.expect_err("hard fault must latch the write gate");
assert_eq!(
latch.pool_metadata_failure().expect("typed recovery latch").kind,
crate::error::PoolMetadataFailure::RecoveryRequired,
"case={label} latch={latch}"
);
// A later healthy snapshot must not silently clear the recovery latch.
inject_startup_object(&pool0, POOL_META_IDENTITY_NAME, initialized.clone());
inject_startup_object(&pool0, POOL_META_NAME, startup_pool_meta_payload(&init_test_pool_meta(None)));
load_pool_meta_for_startup(pools, &mut follower)
.await
.expect("repaired snapshot remains readable for diagnostics");
follower
.ensure_write_safe("single-pool follower after later healthy replica")
.expect_err("recovery latch must remain active after hard fault");
assert_eq!(pool0.identity_write_attempts.load(Ordering::SeqCst), 0);
assert_eq!(pool0.pool_meta_write_attempts.load(Ordering::SeqCst), 0);
}
}
#[tokio::test]
async fn test_two_pool_bootstrap_rejects_pending_replicas_from_different_bootstraps() {
let deployment_id = Uuid::new_v4();
+160 -18
View File
@@ -93,6 +93,55 @@ pub async fn init_disks(
(res, errors)
}
/// Initialize pool disk handles during staged topology reload without reading
/// or mutating live `instance_ctx.local_disk_map`.
pub(crate) async fn init_disks_with_staged_locals(
instance_ctx: &InstanceContext,
eps: &Endpoints,
opt: &DiskOption,
staged_locals: &std::collections::HashMap<String, Option<DiskStore>>,
) -> (Vec<Option<DiskStore>>, Vec<Option<DiskError>>) {
let mut futures = Vec::with_capacity(eps.as_ref().len());
for ep in eps.as_ref().iter() {
let staged = if ep.is_local {
staged_locals.get(&ep.to_string()).cloned()
} else {
None
};
futures.push(async move {
if ep.is_local {
match staged {
Some(Some(disk)) => Ok(disk),
Some(None) => Err(DiskError::VolumeNotFound),
None => Err(DiskError::DiskNotFound),
}
} else {
crate::disk::new_disk_for_instance(instance_ctx, ep, opt).await
}
});
}
let mut res = Vec::with_capacity(eps.as_ref().len());
let mut errors = Vec::with_capacity(eps.as_ref().len());
let results = join_all(futures).await;
for result in results {
match result {
Ok(s) => {
res.push(Some(s));
errors.push(None);
}
Err(e) => {
res.push(None);
errors.push(Some(e));
}
}
}
(res, errors)
}
#[cfg(test)]
pub async fn connect_load_init_formats(
first_disk: bool,
@@ -119,6 +168,29 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx(
set_count: usize,
set_drive_count: usize,
deployment_id: Option<Uuid>,
) -> Result<LoadedFormat> {
connect_load_init_formats_inner(instance_ctx, first_disk, disks, set_count, set_drive_count, deployment_id, false).await
}
pub(crate) async fn connect_load_init_formats_staged(
instance_ctx: &Arc<InstanceContext>,
first_disk: bool,
disks: &mut [Option<DiskStore>],
set_count: usize,
set_drive_count: usize,
deployment_id: Option<Uuid>,
) -> Result<LoadedFormat> {
connect_load_init_formats_inner(instance_ctx, first_disk, disks, set_count, set_drive_count, deployment_id, true).await
}
async fn connect_load_init_formats_inner(
instance_ctx: &Arc<InstanceContext>,
first_disk: bool,
disks: &mut [Option<DiskStore>],
set_count: usize,
set_drive_count: usize,
deployment_id: Option<Uuid>,
staged_mode: bool,
) -> Result<LoadedFormat> {
let (formats, errs, unformatted_bootstrap_routes) = load_format_erasure_all_observing_bootstrap_routes(disks, false).await;
@@ -126,8 +198,17 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx(
// Only the elected pool creator may replay a complete durable format plan.
// Absence of pool metadata or an orphaned format temp file grants no authority.
if first_disk
&& let Some(format) =
resume_format_bootstrap(instance_ctx, disks, &formats, &errs, set_count, set_drive_count, deployment_id).await?
&& let Some(format) = resume_format_bootstrap(
instance_ctx,
disks,
&formats,
&errs,
set_count,
set_drive_count,
deployment_id,
staged_mode,
)
.await?
{
return Ok(LoadedFormat {
format,
@@ -199,7 +280,16 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx(
match try_migrate_format(disks, &formats, set_count, set_drive_count, mode).await {
Ok(LegacyFormatOutcome::Migrated { format, quorum_members }) => {
info!("Migrated format from MinIO config");
retain_format_quorum_members(instance_ctx, disks, &format, &quorum_members, None, set_drive_count).await?;
retain_format_quorum_members_with_mode(
instance_ctx,
disks,
&format,
&quorum_members,
None,
set_drive_count,
staged_mode,
)
.await?;
return Ok(LoadedFormat {
format: *format,
pool_meta_bootstrap_authority: PoolMetaBootstrapAuthority::LegacyAdoption,
@@ -219,7 +309,8 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx(
Err(e) => return Err(e),
}
if first_disk && fresh_bootstrap_proven {
let fm = init_format_erasure(instance_ctx, disks, set_count, set_drive_count, deployment_id).await?;
let fm = init_format_erasure_with_mode(instance_ctx, disks, set_count, set_drive_count, deployment_id, staged_mode)
.await?;
return Ok(LoadedFormat {
format: fm,
pool_meta_bootstrap_authority: PoolMetaBootstrapAuthority::Fresh,
@@ -230,13 +321,14 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx(
// Resolve legacy migration before admitting native reads. Blank replacement
// slots contribute no votes and receive no formatting/bootstrap authority.
if let Some((format, members)) = native_read_candidate {
retain_format_quorum_members(
retain_format_quorum_members_with_mode(
instance_ctx,
disks,
&format,
&members,
Some(&unformatted_bootstrap_routes),
set_drive_count,
staged_mode,
)
.await?;
// Loading an existing format grants no authority to initialize pool
@@ -267,13 +359,14 @@ pub(crate) async fn connect_load_init_formats_with_instance_ctx(
None => select_format_erasure_in_quorum(&formats, 0)?,
};
check_format_erasure_value_for_topology(&fm, formats.len(), set_drive_count)?;
retain_format_quorum_members(
retain_format_quorum_members_with_mode(
instance_ctx,
disks,
&fm,
&quorum_members,
Some(&unformatted_bootstrap_routes),
set_drive_count,
staged_mode,
)
.await?;
@@ -304,6 +397,7 @@ async fn verified_legacy_adoption_source(
}
}
#[allow(dead_code)]
pub(super) async fn retain_format_quorum_members(
instance_ctx: &Arc<InstanceContext>,
disks: &mut [Option<DiskStore>],
@@ -311,6 +405,27 @@ pub(super) async fn retain_format_quorum_members(
quorum_members: &[bool],
unformatted_bootstrap_routes: Option<&[bool]>,
set_drive_count: usize,
) -> Result<()> {
retain_format_quorum_members_with_mode(
instance_ctx,
disks,
format,
quorum_members,
unformatted_bootstrap_routes,
set_drive_count,
false,
)
.await
}
pub(super) async fn retain_format_quorum_members_with_mode(
instance_ctx: &Arc<InstanceContext>,
disks: &mut [Option<DiskStore>],
format: &FormatV3,
quorum_members: &[bool],
unformatted_bootstrap_routes: Option<&[bool]>,
set_drive_count: usize,
staged_mode: bool,
) -> Result<()> {
if set_drive_count == 0
|| quorum_members.len() != disks.len()
@@ -319,11 +434,15 @@ pub(super) async fn retain_format_quorum_members(
return Err(Error::CorruptedFormat);
}
let pool_idx = disks
.iter()
.flatten()
.map(|disk| disk.endpoint().pool_idx)
.find_map(|pool_idx| usize::try_from(pool_idx).ok());
let pool_idx = if staged_mode {
None
} else {
disks
.iter()
.flatten()
.map(|disk| disk.endpoint().pool_idx)
.find_map(|pool_idx| usize::try_from(pool_idx).ok())
};
let registered_endpoints = if let Some(pool_idx) = pool_idx {
instance_ctx
.local_disk_set_drives()
@@ -384,18 +503,28 @@ pub(super) async fn retain_format_quorum_members(
selected_local_disk_ids.push((disk_id, disk.endpoint().to_string()));
}
}
if bootstrap_routes.is_empty() {
quarantine_local_disks(instance_ctx, &quarantined_endpoints).await?;
} else {
quarantine_local_disks_preserving_bootstrap_routes(instance_ctx, &quarantined_endpoints, &bootstrap_routes).await?;
if !staged_mode {
if bootstrap_routes.is_empty() {
quarantine_local_disks(instance_ctx, &quarantined_endpoints).await?;
} else {
quarantine_local_disks_preserving_bootstrap_routes(instance_ctx, &quarantined_endpoints, &bootstrap_routes).await?;
}
}
for (disk, disk_id) in disks.iter().zip(member_disk_ids) {
if let Some(disk) = disk {
disk.set_disk_id_state(disk_id).await?;
if staged_mode {
// During staged reload, update only the wrapper's in-memory ID
// without mutating `instance_ctx.local_disk_id_map` before cutover.
disk.set_disk_id(disk_id).await?;
} else {
disk.set_disk_id_state(disk_id).await?;
}
}
}
reconcile_local_disk_ids(instance_ctx, &local_pool_endpoints, &selected_local_disk_ids).await;
if !staged_mode {
reconcile_local_disk_ids(instance_ctx, &local_pool_endpoints, &selected_local_disk_ids).await;
}
for (disk, belongs_to_quorum) in disks.iter_mut().zip(quorum_members) {
if !belongs_to_quorum {
*disk = None;
@@ -430,12 +559,24 @@ pub fn check_disk_fatal_errs(errs: &[Option<DiskError>]) -> disk::error::Result<
Ok(())
}
#[allow(dead_code)]
async fn init_format_erasure(
instance_ctx: &Arc<InstanceContext>,
disks: &mut [Option<DiskStore>],
set_count: usize,
set_drive_count: usize,
deployment_id: Option<Uuid>,
) -> Result<FormatV3> {
init_format_erasure_with_mode(instance_ctx, disks, set_count, set_drive_count, deployment_id, false).await
}
async fn init_format_erasure_with_mode(
instance_ctx: &Arc<InstanceContext>,
disks: &mut [Option<DiskStore>],
set_count: usize,
set_drive_count: usize,
deployment_id: Option<Uuid>,
staged_mode: bool,
) -> Result<FormatV3> {
let mut fm = FormatV3::new(set_count, set_drive_count);
if let Some(id) = deployment_id {
@@ -447,7 +588,8 @@ async fn init_format_erasure(
write_format_file_all(disks, &fms).await?;
let format = get_format_erasure_in_quorum(&fms, 0)?;
let quorum_members = vec![true; disks.len()];
retain_format_quorum_members(instance_ctx, disks, &format, &quorum_members, None, set_drive_count).await?;
retain_format_quorum_members_with_mode(instance_ctx, disks, &format, &quorum_members, None, set_drive_count, staged_mode)
.await?;
Ok(format)
}
+9
View File
@@ -458,6 +458,7 @@ pub use object::{
};
mod peer;
mod rebalance;
pub mod reload;
#[cfg(test)]
mod usage_watch_tests;
#[cfg(all(test, feature = "test-util"))]
@@ -471,6 +472,12 @@ pub use peer::{
BootstrapLocalTarget, all_local_disk, all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc,
find_local_disk_by_ref_for_scanner_rpc, get_disk_infos, init_local_disks, init_local_disks_with_instance_ctx,
init_lock_clients, prewarm_local_disk_id_map, prewarm_local_disk_id_map_with_instance_ctx,
refresh_local_disks_for_topology_reload, refresh_lock_clients,
};
pub use reload::{
CandidateDiskFormatState, CandidateDiskProbe, CandidateDiskProbeReport, DynamicECStoreHandle, PoolGeometrySummary,
TopologyDiff, TopologyReloadMode, TopologyReloadOutcome, TopologyTransitionKind, analyze_topology_transition,
summarize_endpoint_pools, summarize_pool_geometry,
};
pub struct ECStore {
@@ -950,6 +957,8 @@ impl ECStore {
disk.as_ref().is_some_and(|disk| match disk.as_ref() {
crate::disk::Disk::Local(wrapper) => wrapper.get_disk().usage_watch_binding.matches(&self.ctx.usage_watches),
crate::disk::Disk::Remote(_) => false,
#[cfg(feature = "dst")]
crate::disk::Disk::Sim(_) => false,
})
});
drop(local_disks);
+72 -34
View File
@@ -46,6 +46,15 @@ impl BootstrapLocalTarget {
Arc::ptr_eq(&self.ctx, &store.ctx)
}
pub fn is_startup_formats_ready(&self) -> bool {
self.ctx.is_startup_formats_ready()
}
/// Wake the standby pool-join loop immediately once `pool.bin` has been committed.
pub fn notify_pool_join_wakeup(&self) {
self.ctx.notify_pool_join_wakeup();
}
/// Atomically publish a format control file on this bootstrap instance.
///
/// # Errors
@@ -676,7 +685,16 @@ pub async fn init_local_disks_with_instance_ctx(
runtime_sources::initialize_local_disk_maps(instance_ctx, endpoint_pools, opt).await
}
pub fn init_lock_clients(endpoint_pools: EndpointServerPools) {
/// Refresh local disks for a live topology hot-reload without running
/// destructive startup cleanup on active disks.
pub async fn refresh_local_disks_for_topology_reload(
instance_ctx: &Arc<InstanceContext>,
endpoint_pools: EndpointServerPools,
) -> Result<()> {
runtime_sources::refresh_local_disk_maps_for_reload(instance_ctx, endpoint_pools).await
}
fn build_lock_clients_map(endpoint_pools: &EndpointServerPools) -> HashMap<String, Arc<dyn LockClient>> {
let mut unique_endpoints: HashMap<String, &Endpoint> = HashMap::new();
for pool_eps in endpoint_pools.as_ref().iter() {
@@ -686,35 +704,49 @@ pub fn init_lock_clients(endpoint_pools: EndpointServerPools) {
}
let mut clients = HashMap::new();
let mut first_local_client_set = false;
let existing_map = runtime_sources::global_lock_clients();
let existing_local = runtime_sources::global_lock_client();
let mut local_client_handle = existing_local.clone();
for (key, endpoint) in unique_endpoints {
if endpoint.is_local {
let local_client = Arc::new(LocalClient::new()) as Arc<dyn LockClient>;
let local_client = local_client_handle
.get_or_insert_with(|| Arc::new(LocalClient::new()) as Arc<dyn LockClient>)
.clone();
// Store the first LocalClient globally for use by other modules
if !first_local_client_set {
if let Err(e) = runtime_sources::set_primary_lock_client(local_client.clone()) {
// If already set, ignore the error (another thread may have set it)
debug!(
event = EVENT_LOCK_CLIENT_INITIALIZATION_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_DISK_STARTUP,
error = ?e,
reason = "global_lock_client_already_set",
"Skipped global lock client publication"
);
} else {
first_local_client_set = true;
}
if existing_local.is_none()
&& let Err(e) = runtime_sources::set_primary_lock_client(local_client.clone())
{
debug!(
event = EVENT_LOCK_CLIENT_INITIALIZATION_FAILED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_DISK_STARTUP,
error = ?e,
reason = "global_lock_client_already_set",
"Skipped global lock client publication"
);
}
clients.insert(key, local_client);
} else if let Some(existing_remote) = existing_map.as_ref().and_then(|map| map.get(&key)).cloned() {
clients.insert(key, existing_remote);
} else {
clients.insert(key, Arc::new(RemoteClient::new(endpoint.url.to_string())) as Arc<dyn LockClient>);
}
}
clients
}
/// Build a staged lock-client map for `endpoint_pools` without mutating
/// the active lock-client registry until atomic hot-reload cutover.
pub(super) fn build_staged_lock_clients_map(endpoint_pools: &EndpointServerPools) -> HashMap<String, Arc<dyn LockClient>> {
build_lock_clients_map(endpoint_pools)
}
pub fn init_lock_clients(endpoint_pools: EndpointServerPools) {
let clients = build_lock_clients_map(&endpoint_pools);
// Store the lock clients map globally
if runtime_sources::set_lock_clients(clients).is_err() {
error!(
@@ -727,6 +759,14 @@ pub fn init_lock_clients(endpoint_pools: EndpointServerPools) {
}
}
/// Atomically refresh the global lock clients map during a live topology reload,
/// preserving the existing primary `LocalClient` so active local locks remain
/// visible across the topology transition.
pub fn refresh_lock_clients(endpoint_pools: EndpointServerPools) {
let clients = build_lock_clients_map(&endpoint_pools);
runtime_sources::replace_lock_clients(clients);
}
fn endpoint_rpc_authority(endpoint: &Endpoint) -> Option<String> {
let host = endpoint.url.host_str()?;
let host = if host.contains(':') && !host.starts_with('[') {
@@ -740,30 +780,28 @@ fn endpoint_rpc_authority(endpoint: &Endpoint) -> Option<String> {
})
}
pub(super) async fn init_local_peer(endpoint_pools: &EndpointServerPools, host: &String, port: &String) {
let mut peer_set = Vec::new();
endpoint_pools.as_ref().iter().for_each(|endpoints| {
endpoints.endpoints.as_ref().iter().for_each(|endpoint| {
pub(super) fn resolve_local_peer_name(endpoint_pools: &EndpointServerPools, host: &str, port: &str) -> String {
for endpoints in endpoint_pools.as_ref() {
for endpoint in endpoints.endpoints.as_ref() {
if endpoint.get_type() == EndpointType::Url
&& endpoint.is_local
&& let Some(authority) = endpoint_rpc_authority(endpoint)
{
peer_set.push(authority);
return authority;
}
});
});
if peer_set.is_empty() {
if !host.is_empty() {
runtime_sources::set_local_node_name(format!("{host}:{port}")).await;
return;
}
runtime_sources::set_local_node_name(format!("127.0.0.1:{port}")).await;
return;
}
runtime_sources::set_local_node_name(peer_set[0].clone()).await;
if !host.is_empty() {
return format!("{host}:{port}");
}
format!("127.0.0.1:{port}")
}
pub(super) async fn init_local_peer(endpoint_pools: &EndpointServerPools, host: &str, port: &str) {
let resolved = resolve_local_peer_name(endpoint_pools, host, port);
runtime_sources::set_local_node_name(resolved).await;
}
pub async fn get_disk_infos(disks: &[Option<DiskStore>]) -> Vec<Option<DiskInfo>> {
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,744 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Production Deterministic Simulation Testing (DST) integration suite for `rustfs-ecstore`.
//!
//! Exercises REAL `SetDisks` erasure coding, SIMD Reed-Solomon, HighwayHash256S bitrot
//! framing, `FileMeta` (`xl.meta`), recoverable deletes, and `HealOperations::heal_object`
//! directly on top of `rustfs_dst_runtime::disk::SimDiskIo` (`Disk::Sim(Box<DstSimDisk>)`).
#![cfg(feature = "dst")]
mod storage_api;
use std::collections::{BTreeMap, BTreeSet};
use bytes::Bytes;
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,
};
use tokio::io::AsyncReadExt;
fn deterministic_payload(seed: u64, tag: &str, len: usize) -> Vec<u8> {
let rng = SimRng::from_seed(seed);
let mut header = format!("rustfs-dst:{tag}:seed={seed}:len={len}:").into_bytes();
let mut out = Vec::with_capacity(len);
let copy_hdr = header.len().min(len);
out.extend_from_slice(&header[..copy_hdr]);
header.clear();
while out.len() < len {
let word = rng.next_u64().to_le_bytes();
let take = (len - out.len()).min(word.len());
out.extend_from_slice(&word[..take]);
}
out
}
fn tail_drained_opts() -> ObjectOptions {
dst_object_options()
}
async fn put_bytes(fixture: &DstSimSetFixture, bucket: &str, key: &str, payload: &[u8]) -> EcstoreResult<()> {
let mut reader = PutObjReader::from_vec(payload.to_vec());
let info = fixture
.set_disks
.put_object(bucket, key, &mut reader, &tail_drained_opts())
.await?;
assert_eq!(info.size, payload.len() as i64);
Ok(())
}
async fn get_bytes(fixture: &DstSimSetFixture, bucket: &str, key: &str) -> EcstoreResult<Vec<u8>> {
let mut reader = fixture
.set_disks
.get_object_reader(bucket, key, None, HeaderMap::new(), &ObjectOptions::default())
.await?;
let mut buf = Vec::new();
reader.stream.read_to_end(&mut buf).await.map_err(EcstoreError::from)?;
Ok(buf)
}
/// Locate `<bucket>/<key>/<data_dir>/part.1` on simulated drive `disk_idx`.
fn find_part1_rel_path(fixture: &DstSimSetFixture, disk_idx: usize, bucket: &str, key: &str) -> Option<String> {
let prefix = format!("{bucket}/{key}/");
fixture.sim_disks[disk_idx]
.sim()
.all_files()
.into_iter()
.find(|p| p.starts_with(&prefix) && p.ends_with("/part.1"))
}
// ============================================================================
// Test 1: Real production put_object / get_object / delete_object + degraded
// quorum read/write when drives go offline + ENOSPC handling
// ============================================================================
#[tokio::test]
async fn dst_prod_test1_quorum_put_get_delete_offline_and_enospc() {
for &seed in &[0x000A_11CE_0001_u64, 0x000A_11CE_0002_u64, 0x000A_11CE_0003_u64] {
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
.await
.expect("dst sim 4-drive SetDisks should initialize");
// Verify real `format.json` (`FormatV3`) persisted and readable on every drive
for (slot, disk) in fixture.disks.iter().enumerate() {
let loaded = load_format_erasure(disk, true)
.await
.expect("format.json should load from DstSimDisk");
assert_eq!(loaded.id, fixture.format.id);
assert_eq!(loaded.erasure.this, fixture.format.erasure.sets[0][slot]);
assert!(loaded.disk_info.expect("heal disk_info").fresh_capacity);
}
let bucket = "dst-prod-quorum";
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("make_bucket should succeed across 4 Sim drives");
// Exercise BOTH inline small object AND multi-block (>1 MiB) erasure-coded object
let small_key = "inline/small.bin";
let small_payload = deterministic_payload(seed, "small", 4096);
let large_key = "erasure/multi-block.bin";
let large_payload = deterministic_payload(seed, "large", BLOCK_SIZE_V2 + 98_304);
put_bytes(&fixture, bucket, small_key, &small_payload)
.await
.expect("put small inline object");
put_bytes(&fixture, bucket, large_key, &large_payload)
.await
.expect("put large Reed-Solomon object");
// Verify real physical shards (`part.1`) exist on all 4 drives for the large object
for slot in 0..4 {
assert!(
find_part1_rel_path(&fixture, slot, bucket, large_key).is_some(),
"drive {slot} must store physical bitrot-framed part.1 shard"
);
}
assert_eq!(get_bytes(&fixture, bucket, small_key).await.expect("get small"), small_payload);
assert_eq!(get_bytes(&fixture, bucket, large_key).await.expect("get large"), large_payload);
// Take 2 drives offline (equals parity = 2 on a 2+2 set): degraded read AND write must work!
fixture.sim_disks[0].set_online(false);
fixture.sim_disks[2].set_online(false);
fixture.invalidate_set_caches();
assert_eq!(
get_bytes(&fixture, bucket, small_key)
.await
.expect("degraded read small with 2 drives offline"),
small_payload
);
assert_eq!(
get_bytes(&fixture, bucket, large_key)
.await
.expect("degraded Reed-Solomon reconstruct read with 2 drives offline"),
large_payload
);
// Degraded quorum write while 1 drive is offline (3 online >= write quorum)
fixture.sim_disks[2].set_online(true);
fixture.invalidate_set_caches();
let degraded_key = "erasure/written-while-d0-offline.bin";
let degraded_payload = deterministic_payload(seed ^ 0x55, "degraded-put", BLOCK_SIZE_V2 + 16_384);
put_bytes(&fixture, bucket, degraded_key, &degraded_payload)
.await
.expect("degraded put_object with 1 drive offline should succeed at quorum");
assert_eq!(
get_bytes(&fixture, bucket, degraded_key).await.expect("read degraded-put"),
degraded_payload
);
// Take 3 drives offline (only 1 online < read/write quorum): operations must fail closed!
fixture.sim_disks[1].set_online(false);
fixture.sim_disks[2].set_online(false);
fixture.invalidate_set_caches();
assert!(
get_bytes(&fixture, bucket, large_key).await.is_err(),
"read below quorum (3/4 drives offline) must fail closed"
);
assert!(
put_bytes(&fixture, bucket, "below-quorum.bin", b"must-not-commit")
.await
.is_err(),
"write below quorum (3/4 drives offline) must fail closed"
);
// Bring all drives back online, heal the object written while drive 0 was offline,
// and verify real recoverable delete_object!
for sim in &fixture.sim_disks {
sim.set_online(true);
}
fixture.invalidate_set_caches();
let (heal_res, heal_err) = fixture
.set_disks
.heal_object(
bucket,
degraded_key,
"",
&HealOpts {
scan_mode: HealScanMode::Deep,
remove: true,
..Default::default()
},
)
.await
.expect("heal_object on degraded_key should succeed");
assert!(heal_err.is_none(), "heal_object error should be None: {heal_err:?}");
assert!(find_part1_rel_path(&fixture, 0, bucket, degraded_key).is_some());
let _ = heal_res;
// Delete object through production recoverable-delete protocol
fixture
.set_disks
.delete_object(bucket, small_key, dst_object_options())
.await
.expect("delete_object small_key");
let after_del = get_bytes(&fixture, bucket, small_key).await;
assert!(
after_del.is_err() && is_err_object_not_found(after_del.as_ref().unwrap_err()),
"deleted object must return ObjectNotFound, got: {after_del:?}"
);
// ENOSPC quota enforcement on 3 drives -> write must fail without corrupting existing objects
for slot in [0, 1, 2] {
let current_used = fixture.sim_disks[slot].sim().used_bytes();
fixture.sim_disks[slot].set_capacity_bytes(Some(current_used + 1024));
}
let enospc_payload = vec![0xAB; BLOCK_SIZE_V2];
assert!(
put_bytes(&fixture, bucket, "enospc-denied.bin", &enospc_payload)
.await
.is_err(),
"put_object exceeding drive capacity across quorum must fail with ENOSPC"
);
// Existing large_key remains 100% intact!
fixture.invalidate_set_caches();
assert_eq!(get_bytes(&fixture, bucket, large_key).await.expect("get after enospc"), large_payload);
}
}
// ============================================================================
// Test 2: Real physical shard silent bitrot + tail truncation detected by
// production HighwayHash256S and reconstructed + healed by ecstore
// ============================================================================
#[tokio::test]
async fn dst_prod_test2_physical_bitrot_highwayhash_detect_reconstruct_and_heal() {
// Test across BOTH 4-drive (2+2) and 8-drive (4+4) production erasure topologies!
for &(seed, drives, parity, rot_slots) in &[
(0xB172_0701_u64, 4usize, 2usize, &[0usize, 2usize][..]),
(0xB172_0702_u64, 4usize, 2usize, &[1usize, 3usize][..]),
(0xB172_0703_u64, 8usize, 4usize, &[0usize, 2usize, 5usize, 7usize][..]),
] {
let fixture = make_dst_sim_set_disks(seed, drives, parity, None)
.await
.expect("dst sim SetDisks should initialize");
let bucket = "dst-prod-bitrot";
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("make_bucket");
let key = "critical/ledger-stripe.bin";
let payload = deterministic_payload(seed, "bitrot-target", BLOCK_SIZE_V2 * 2 + 77_777);
put_bytes(&fixture, bucket, key, &payload)
.await
.expect("put multi-stripe object");
// 1. Pre-fault verification: every drive passes production HighwayHash256S `verify_file`
for disk in fixture.disks.iter().take(drives) {
let fi = disk
.read_version("", bucket, key, "", &ReadOptions::default())
.await
.expect("read_version on healthy drive");
let check = disk
.verify_file(bucket, key, &fi)
.await
.expect("verify_file on healthy drive");
assert_eq!(check.results, vec![CHECK_PART_SUCCESS]);
}
// 2. Inject silent physical bitrot (and tail truncation on the last corrupted slot)
// directly into the underlying `SimDiskIo` `part.1` files!
for (idx, &slot) in rot_slots.iter().enumerate() {
let part_rel = find_part1_rel_path(&fixture, slot, bucket, key).expect("part.1 path");
if idx + 1 == rot_slots.len() && rot_slots.len() > 1 {
assert!(
fixture.sim_disks[slot].inject_tail_truncate(&part_rel, 19),
"tail truncation must shrink part.1 on drive {slot}"
);
} else {
assert!(
fixture.sim_disks[slot].inject_bitrot(&part_rel),
"bitrot injection must flip a byte in part.1 on drive {slot}"
);
}
// Confirm production `verify_file` immediately flags `CHECK_PART_FILE_CORRUPT`
let fi = fixture.disks[slot]
.read_version("", bucket, key, "", &ReadOptions::default())
.await
.expect("xl.meta still readable");
let check = fixture.disks[slot]
.verify_file(bucket, key, &fi)
.await
.expect("verify_file must classify corruption");
assert_eq!(
check.results,
vec![CHECK_PART_FILE_CORRUPT],
"HighwayHash256S verify_file must detect silent corruption on drive {slot}"
);
}
// 3. Transparent Reed-Solomon reconstruction on GET: corrupt shards are rejected by
// `BitrotReader` and exact plaintext is reconstructed from surviving shards!
fixture.invalidate_set_caches();
let reconstructed = get_bytes(&fixture, bucket, key)
.await
.expect("GET must transparently reconstruct despite silent bitrot on parity-many drives");
assert_eq!(reconstructed, payload);
// 4. Execute REAL production `HealOperations::heal_object` with `HealScanMode::Deep`!
let (_heal_item, heal_err) = fixture
.set_disks
.heal_object(
bucket,
key,
"",
&HealOpts {
scan_mode: HealScanMode::Deep,
remove: true,
..Default::default()
},
)
.await
.expect("production deep heal_object must succeed");
assert!(heal_err.is_none(), "deep heal_object returned unexpected err: {heal_err:?}");
// 5. Post-heal proof: ALL drives now pass HighwayHash256S `verify_file` (`CHECK_PART_SUCCESS`),
// AND taking the untouched drives offline proves the healed shards serve valid data!
for (slot, disk) in fixture.disks.iter().enumerate().take(drives) {
let fi = disk
.read_version("", bucket, key, "", &ReadOptions::default())
.await
.expect("post-heal read_version");
let check = disk.verify_file(bucket, key, &fi).await.expect("post-heal verify_file");
assert_eq!(
check.results,
vec![CHECK_PART_SUCCESS],
"drive {slot} shard must be 100% healed and verified on disk"
);
}
// Take `parity` previously-healthy drives offline so GET is forced to read the healed drives!
let mut offlined = 0;
for (slot, sim_disk) in fixture.sim_disks.iter().enumerate().take(drives) {
if !rot_slots.contains(&slot) && offlined < parity {
sim_disk.set_online(false);
offlined += 1;
}
}
fixture.invalidate_set_caches();
let post_heal_degraded = get_bytes(&fixture, bucket, key)
.await
.expect("GET reading directly from healed shards must succeed");
assert_eq!(post_heal_degraded, payload);
}
}
// ============================================================================
// Test 3: ALICE power-loss crash (`CrashSemantics::DirtySubsetAndSectorTear` +
// `crash_and_reboot`) across multiple drives & CrashPoints — proving
// old-or-new-never-mixed atomicity and zero FileMeta corruption!
// ============================================================================
#[tokio::test]
async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixed() {
let crash_points = [
CrashPoint::RenameAfterDataRename,
CrashPoint::RenameAfterBackupBeforeMetaCommit,
CrashPoint::RenameAfterMetaCommit,
CrashPoint::MetaWriteAfterTmpBeforeRename,
];
for (seed_idx, &seed) in [0xC2A5_4001_u64, 0xC2A5_4002_u64, 0xC2A5_4003_u64, 0xC2A5_4004_u64]
.iter()
.enumerate()
{
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
.await
.expect("dst sim SetDisks should initialize");
// Enable ALICE / CrashMonkey `DirtySubsetAndSectorTear` on every drive!
for sim in &fixture.sim_disks {
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
}
let bucket = "dst-alice-powerloss";
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("make_bucket");
// Commit baseline anchor objects (inline + multi-block Reed-Solomon)
let anchor_small_key = "anchor/small.bin";
let anchor_small_v1 = deterministic_payload(seed, "anchor-small-v1", 6144);
let anchor_large_key = "anchor/large.bin";
let anchor_large_v1 = deterministic_payload(seed, "anchor-large-v1", BLOCK_SIZE_V2 + 65_536);
put_bytes(&fixture, bucket, anchor_small_key, &anchor_small_v1)
.await
.expect("put anchor small");
put_bytes(&fixture, bucket, anchor_large_key, &anchor_large_v1)
.await
.expect("put anchor large");
// Stage dirty un-fsynced files directly in `.rustfs.sys/tmp` to trigger ALICE dirty-page
// subset & 512B sector-tear reconstruction during power loss, then crash all 4 drives!
for (slot, sim) in fixture.sim_disks.iter().enumerate() {
let dirty_tmp = format!(".rustfs.sys/tmp/inflight-unfsynced-{slot}/part.1");
SimDiskIoTrait::write_file(sim.sim(), &dirty_tmp, Bytes::from(vec![0xEE; 16 * 1024 + 333]))
.await
.expect("stage dirty temp file");
}
fixture.crash_and_reboot_all();
// Anchor objects MUST survive abrupt ALICE power loss 100% bit-exact!
assert_eq!(
get_bytes(&fixture, bucket, anchor_small_key)
.await
.expect("anchor small after ALICE crash"),
anchor_small_v1
);
assert_eq!(
get_bytes(&fixture, bucket, anchor_large_key)
.await
.expect("anchor large after ALICE crash"),
anchor_large_v1
);
// Now test overwriting an existing multi-block object `v1 -> v2` while arming each
// commit `CrashPoint` across 1, 2, or 3 drives, followed by full-cluster ALICE power loss!
for (cp_idx, &point) in crash_points.iter().enumerate() {
let key = format!("overwrite/cp-{cp_idx}.bin");
let v1 = deterministic_payload(seed ^ (cp_idx as u64 + 10), "v1", BLOCK_SIZE_V2 + 24_576);
let v2 = deterministic_payload(seed ^ (cp_idx as u64 + 99), "v2", BLOCK_SIZE_V2 + 49_152);
put_bytes(&fixture, bucket, &key, &v1).await.expect("commit v1 before crash");
assert_eq!(get_bytes(&fixture, bucket, &key).await.expect("verify v1"), v1);
// Arm crash point on `(seed_idx + cp_idx) % 3 + 1` drives (1, 2, or 3 drives)
let affected_drives = ((seed_idx + cp_idx) % 3) + 1;
for slot in 0..affected_drives {
fixture.crash_registry.arm_on_drive(point, &key, "dst-node0", slot);
}
// Attempt overwrite `v2` (may succeed at quorum if only 1 drive crashed, or fail if >=2 crashed)
let _overwrite_outcome = put_bytes(&fixture, bucket, &key, &v2).await;
fixture.crash_registry.clear();
// Simulate simultaneous cluster-wide power outage & ALICE reboot!
fixture.crash_and_reboot_all();
// INVARIANT 1: Zero `xl.meta` (`FileMeta`) structural corruption on ANY drive!
for (slot, sim_disk) in fixture.sim_disks.iter().enumerate().take(4) {
let xl_rel = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}");
if let Ok(raw) = SimDiskIoTrait::read_file(sim_disk.sim(), &xl_rel).await {
let parsed = FileMeta::load(&raw);
assert!(
parsed.is_ok(),
"ALICE power-loss left corrupt xl.meta on drive {slot} at {point:?} (seed={seed:#x}): {parsed:?}"
);
}
}
// INVARIANT 2: Old-or-New-Never-Mixed! Reading `key` must return 100% bit-exact `v1`
// OR 100% bit-exact `v2` — NEVER partial, zeroed, or mixed bytes!
let observed = get_bytes(&fixture, bucket, &key)
.await
.unwrap_or_else(|e| panic!("committed object {key} unreadable after ALICE crash at {point:?}: {e:?}"));
assert!(
observed == v1 || observed == v2,
"atomicity violation after ALICE crash at {point:?} (seed={seed:#x}): payloadlen={} matches neither v1 ({}) nor v2 ({})",
observed.len(),
v1.len(),
v2.len()
);
// INVARIANT 3: Production `heal_object` converges all 4 drives back to unanimous health,
// and previously untouched anchor objects remain 100% bit-exact!
let (_, heal_err) = fixture
.set_disks
.heal_object(
bucket,
&key,
"",
&HealOpts {
scan_mode: HealScanMode::Deep,
remove: true,
..Default::default()
},
)
.await
.expect("post-crash heal_object should succeed");
assert!(heal_err.is_none());
let post_heal = get_bytes(&fixture, bucket, &key)
.await
.expect("readable after post-crash heal");
assert_eq!(post_heal, observed, "heal must preserve the winning committed generation");
assert_eq!(get_bytes(&fixture, bucket, anchor_large_key).await.unwrap(), anchor_large_v1);
}
}
}
// ============================================================================
// Test 4: Deterministic multi-seed chaos loop driving concurrent `tokio::join!`
// operations against real production `SetDisks` + deterministic replay
// ============================================================================
async fn execute_chaos_seed(seed: u64) -> [u8; 32] {
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
.await
.expect("dst sim SetDisks should initialize");
for sim in &fixture.sim_disks {
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
}
let bucket = "dst-chaos-bucket";
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.expect("make_bucket");
let rng = SimRng::from_seed(seed ^ 0xCAFE_BABE_1234_5678);
// Reference state per key: set of permissible payloads (None = deleted/absent, Some(bytes) = valid generation).
// When an operation runs under fault/crash and returns Err, either old or new state is legal;
// when an operation returns Ok with all drives healthy, it narrows to the exact committed state!
let mut model: BTreeMap<String, Vec<Option<Vec<u8>>>> = BTreeMap::new();
let keys: Vec<String> = (0..6).map(|i| format!("chaos/obj-{i}.bin")).collect();
for k in &keys {
model.insert(k.clone(), vec![None]);
}
for step in 0..12u64 {
// Pick two distinct keys for concurrent `tokio::join!` operations so the two tasks
// contend on real `SetDisks` drives, bitrot verifiers, and namespace locks deterministically!
let idx_a = rng.gen_range_usize(keys.len());
let idx_b = (idx_a + 1 + rng.gen_range_usize(keys.len() - 1)) % keys.len();
let key_a = keys[idx_a].clone();
let key_b = keys[idx_b].clone();
// Optionally offline 1 random drive during this wave (within parity = 2 budget)
let offline_slot = if rng.gen_bool(0.45) {
let s = rng.gen_range_usize(4);
fixture.sim_disks[s].set_online(false);
fixture.invalidate_set_caches();
Some(s)
} else {
None
};
let size_a = if rng.gen_bool(0.5) {
2048 + rng.gen_range_usize(4096)
} else {
BLOCK_SIZE_V2 + rng.gen_range_usize(32_768)
};
let payload_a = deterministic_payload(seed.wrapping_add(step * 31 + 1), &key_a, size_a);
let do_delete_b = rng.gen_bool(0.35);
let payload_b = deterministic_payload(seed.wrapping_add(step * 31 + 2), &key_b, 3072 + rng.gen_range_usize(8192));
let fut_a = put_bytes(&fixture, bucket, &key_a, &payload_a);
let fut_b = async {
if do_delete_b {
fixture
.set_disks
.delete_object(bucket, &key_b, dst_object_options())
.await
.map(|_| None)
} else {
put_bytes(&fixture, bucket, &key_b, &payload_b)
.await
.map(|()| Some(payload_b.clone()))
}
};
let read_key = keys[(idx_b + 1) % keys.len()].clone();
let fut_read = get_bytes(&fixture, bucket, &read_key);
let (res_a, res_b, res_read) = tokio::join!(fut_a, fut_b, fut_read);
// Build linearizable candidate set for `fut_read`: any state permissible
// before the wave PLUS any concurrent mutation targeting `read_key` in this wave!
let mut linearizable_read_states: Vec<Option<Vec<u8>>> = model.get(&read_key).expect("tracked key").clone();
if read_key == key_a {
linearizable_read_states.push(Some(payload_a.clone()));
}
if read_key == key_b {
linearizable_read_states.push(if do_delete_b { None } else { Some(payload_b.clone()) });
}
match res_read {
Ok(bytes) => {
assert!(
linearizable_read_states
.iter()
.any(|st| st.as_deref() == Some(bytes.as_slice())),
"seed={seed:#x} step={step}: concurrent GET on {read_key} returned unexpected bytes (len={})",
bytes.len()
);
}
Err(e) => {
assert!(
is_err_object_not_found(&e) && linearizable_read_states.iter().any(Option::is_none),
"seed={seed:#x} step={step}: concurrent GET on {read_key} failed unexpectedly: {e:?}"
);
}
}
match res_a {
Ok(()) => {
model.insert(key_a.clone(), vec![Some(payload_a)]);
}
Err(_) => {
model.entry(key_a.clone()).or_default().push(Some(payload_a));
}
}
match res_b {
Ok(new_state) => {
model.insert(key_b.clone(), vec![new_state]);
}
Err(_) => {
let candidate = if do_delete_b { None } else { Some(payload_b) };
model.entry(key_b.clone()).or_default().push(candidate);
}
}
// Restore any offlined drive
if let Some(s) = offline_slot {
fixture.sim_disks[s].set_online(true);
fixture.invalidate_set_caches();
}
// Periodically inject physical bitrot on one random drive OR trigger ALICE power-loss crash,
// then heal affected keys!
if step % 3 == 1 {
let rot_drive = rng.gen_range_usize(4);
if let Some(part_rel) = find_part1_rel_path(&fixture, rot_drive, bucket, &key_a) {
fixture.sim_disks[rot_drive].inject_bitrot(&part_rel);
}
}
if step % 4 == 3 {
fixture.crash_and_reboot_all();
}
// Heal touched keys so degraded/bitrotted shards converge before next chaos wave
for k in [&key_a, &key_b] {
let _ = fixture
.set_disks
.heal_object(
bucket,
k,
"",
&HealOpts {
scan_mode: HealScanMode::Deep,
remove: true,
..Default::default()
},
)
.await;
}
}
// Final convergence & full-audit pass across all keys and all 4 drives!
fixture.invalidate_set_caches();
let mut final_hasher = Sha256::new();
let mut live_keys = BTreeSet::new();
for key in &keys {
let _ = fixture
.set_disks
.heal_object(
bucket,
key,
"",
&HealOpts {
scan_mode: HealScanMode::Deep,
remove: true,
..Default::default()
},
)
.await;
let allowed = model.get(key).expect("tracked key");
match get_bytes(&fixture, bucket, key).await {
Ok(bytes) => {
assert!(
allowed.iter().any(|st| st.as_deref() == Some(bytes.as_slice())),
"seed={seed:#x}: final state of {key} violates linearizable/crash-safe model"
);
live_keys.insert(key.clone());
final_hasher.update(key.as_bytes());
final_hasher.update((bytes.len() as u64).to_le_bytes());
final_hasher.update(&bytes);
// Every drive's xl.meta must parse cleanly, and non-inline parts must pass verify_file!
for disk in fixture.disks.iter().take(4) {
let fi = disk
.read_version("", bucket, key, "", &ReadOptions::default())
.await
.expect("healthy xl.meta on every drive after final heal");
if !fi.inline_data() && fi.size > 0 {
let check = disk
.verify_file(bucket, key, &fi)
.await
.expect("verify_file after final heal");
assert_eq!(check.results, vec![CHECK_PART_SUCCESS]);
}
}
}
Err(e) => {
assert!(
is_err_object_not_found(&e) && allowed.iter().any(Option::is_none),
"seed={seed:#x}: unexpected final GET error on {key}: {e:?}"
);
final_hasher.update(key.as_bytes());
final_hasher.update(b"<ABSENT>");
}
}
}
assert!(!live_keys.is_empty(), "chaos run should leave at least one live object");
final_hasher.finalize().into()
}
#[tokio::test(flavor = "current_thread")]
async fn dst_prod_test4_deterministic_multiseed_concurrent_chaos_and_replay_equivalence() {
for &seed in &[0xD57_0001_u64, 0xD57_0002_u64, 0xD57_0003_u64, 0xD57_0004_u64] {
let digest_run1 = execute_chaos_seed(seed).await;
let digest_run2 = execute_chaos_seed(seed).await;
assert_eq!(digest_run1, digest_run2, "deterministic replay invariant violated for seed {seed:#x}");
}
}
@@ -49,6 +49,8 @@ fn inherent_hotpath_measurements_have_cpu_attribution_types() {
"encode_data_bytes_mut",
"decode_data",
"decode_data_and_parity",
"decode_data_with_reconstruction_verification",
"decode_data_with_reconstruction_verification_for_lockstep",
] {
assert_measured_as(ERASURE, "Erasure", function);
}
+15
View File
@@ -103,3 +103,18 @@ pub(crate) mod local_drive_retirement {
pub(crate) use super::{DiskAPI, DiskOption, Endpoint, new_disk};
pub(crate) use rustfs_ecstore::api::disk::Disk;
}
#[cfg(feature = "dst")]
pub(crate) mod dst_production_ecstore {
pub(crate) use super::storage_contracts::{BucketOperations, HealOperations, MakeBucketOptions, ObjectIO, ObjectOperations};
pub(crate) use super::{DiskAPI, Error, ObjectOptions, PutObjReader, STORAGE_FORMAT_FILE};
pub(crate) use rustfs_ecstore::api::{
disk::ReadOptions,
dst::{
CHECK_PART_FILE_CORRUPT, CHECK_PART_SUCCESS, CrashPoint, CrashSemantics, DiskIo as SimDiskIoTrait, DstSimSetFixture,
HealOpts, HealScanMode, RngSource, SimRng, dst_object_options, load_format_erasure, make_dst_sim_set_disks,
},
error::{Result as EcstoreResult, is_err_object_not_found},
object::BLOCK_SIZE_V2,
};
}
@@ -427,7 +427,7 @@ impl RootHealTerminal {
self.heal_type.validate()?;
if !matches!(
self.status,
HealTaskStatus::Completed | HealTaskStatus::Cancelled | HealTaskStatus::Failed { .. }
HealTaskStatus::Completed | HealTaskStatus::Cancelled | HealTaskStatus::Timeout | HealTaskStatus::Failed { .. }
) {
return Err(Error::Other(format!("Non-terminal root heal receipt {task_id}")));
}
@@ -1326,8 +1326,7 @@ impl RootHealRecovery {
};
let mut intent = decode_intent(&task.id, &expected)?;
intent.validate_task(task)?;
// A terminal timeout leaves no runtime owner for stop() to snapshot.
// Checkpoint its consumed budget before publishing terminal status;
// Checkpoint consumed execution budget before retrying or handing off;
// never refund time if an earlier checkpoint is already stricter.
intent.options.timeout = match (intent.options.timeout, remaining) {
(Some(previous), Some(remaining)) => Some(previous.min(remaining)),
@@ -86,7 +86,9 @@ fn decode_report(task_id: &str, bytes: &[u8]) -> Result<RootHealReport> {
if let Some(outcome) = &report.outcome
&& (matches!(outcome.execution, HealExecutionOutcome::Pending | HealExecutionOutcome::Running)
|| (report.terminal.status == HealTaskStatus::Cancelled
&& outcome.execution != HealExecutionOutcome::Aborted(HealAbortReason::Cancelled)))
&& outcome.execution != HealExecutionOutcome::Aborted(HealAbortReason::Cancelled))
|| (report.terminal.status == HealTaskStatus::Timeout
&& outcome.execution != HealExecutionOutcome::Aborted(HealAbortReason::Deadline)))
{
return Err(Error::Other(format!("Non-terminal or mismatched heal outcome for {task_id}")));
}
@@ -201,4 +203,39 @@ mod tests {
.contains("size limit")
);
}
#[test]
fn root_report_decoding_validates_timeout_outcome_alignment() {
let task_id = Uuid::new_v4().to_string();
let mut completed = RootHealTerminal::cancelled(&task_id, &HealType::Cluster, HealOptions::default())
.expect("cluster is an administrator recovery type")
.into_completed();
completed.status = HealTaskStatus::Timeout;
let terminal = RootHealTerminal::from_completed(&task_id, &completed).expect("timeout terminal receipt");
let mut deadline_outcome = crate::heal::outcome::HealTaskOutcome::default();
deadline_outcome.start();
deadline_outcome.finish(Some(HealAbortReason::Deadline));
completed.outcome = Some(Arc::new(deadline_outcome));
let valid_bytes = RootHealReport::from_completed(terminal.clone(), &completed)
.encode()
.expect("encode valid timeout report");
let decoded = decode_report(&task_id, &valid_bytes).expect("deadline outcome must decode");
assert_eq!(decoded.terminal().status, HealTaskStatus::Timeout);
for bad_abort in [None, Some(HealAbortReason::Cancelled)] {
let mut mismatched_outcome = crate::heal::outcome::HealTaskOutcome::default();
mismatched_outcome.start();
mismatched_outcome.finish(bad_abort);
completed.outcome = Some(Arc::new(mismatched_outcome));
let invalid_bytes = RootHealReport::from_completed(terminal.clone(), &completed)
.encode()
.expect("encode mismatched timeout report");
let err = match decode_report(&task_id, &invalid_bytes) {
Ok(_) => panic!("timeout report with non-deadline outcome must fail closed"),
Err(err) => err,
};
assert!(err.to_string().contains("Non-terminal or mismatched"), "{err}");
}
}
}
+4 -1
View File
@@ -397,7 +397,10 @@ impl HealManager {
}
let terminal_completion = matches!(
completed_status,
HealTaskStatus::Completed | HealTaskStatus::Cancelled | HealTaskStatus::Failed { .. }
HealTaskStatus::Completed
| HealTaskStatus::Cancelled
| HealTaskStatus::Timeout
| HealTaskStatus::Failed { .. }
);
if (owns_completion || cancelled_completion)
&& terminal_completion
@@ -2671,7 +2671,9 @@ async fn root_recovery_exhausted_timeout_is_not_reset_by_restart() {
process_manager_queue_once(&restarted).await;
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if matches!(restarted.get_task_status(&request.id).await, Ok(HealTaskStatus::Timeout)) {
if matches!(restarted.get_task_status(&request.id).await, Ok(HealTaskStatus::Timeout))
&& !restarted.active_heals.lock().await.contains_key(&request.id)
{
break;
}
tokio::task::yield_now().await;
@@ -2679,11 +2681,20 @@ async fn root_recovery_exhausted_timeout_is_not_reset_by_restart() {
})
.await
.expect("exhausted request stays timed out");
restarted
.cancel_task(&request.id)
.await
.expect("timeout responsibility remains cancellable");
assert!(restarted.root_recovery.pending().await.expect("retired timeout").is_empty());
assert!(
restarted.root_recovery.pending().await.expect("retired timeout").is_empty(),
"terminal timeout must retire durable pending intent"
);
assert_eq!(
restarted
.root_recovery
.completed(&request.id)
.await
.expect("read terminal timeout receipt")
.expect("terminal timeout receipt retained")
.status,
HealTaskStatus::Timeout
);
}
#[tokio::test]
@@ -2735,7 +2746,7 @@ async fn root_recovery_force_start_after_shutdown_does_not_retire_original_owner
}
#[tokio::test]
async fn root_recovery_terminal_timeout_updates_only_existing_journal_before_second_restart() {
async fn root_recovery_terminal_timeout_retires_pending_and_admits_followup_admin_heal() {
for durable in [false, true] {
let (_temp, disk) = recovery_disk().await;
let manager = recovery_manager(vec![disk.clone()]);
@@ -2768,20 +2779,41 @@ async fn root_recovery_terminal_timeout_updates_only_existing_journal_before_sec
.await
.expect("real execution exhausts a nonzero budget");
assert!(!manager.active_heals.lock().await.contains_key(&request.id));
assert!(
manager
.root_recovery
.pending()
.await
.expect("pending retired after timeout")
.is_empty(),
"durable={durable}"
);
// A subsequent non-forceStart admin heal must not be rejected with AlreadyRunning (409).
let followup = root_request();
let admission = manager
.submit_heal_request_with_receipt(followup.clone())
.await
.expect("follow-up admin heal after timeout");
assert_eq!(admission.result, HealAdmissionResult::Accepted, "durable={durable}");
manager
.cancel_task(&followup.id)
.await
.expect("cancel follow-up before restart");
// Restart preserves the timed-out terminal receipt without re-queuing a zero-budget zombie.
let restarted = recovery_manager(vec![disk]);
restarted
.replay_root_heals()
.await
.expect("second restart after terminal timeout");
let queue = restarted.heal_queue.lock().await;
assert_eq!(restarted.get_queue_length().await, 0, "durable={durable}");
assert_eq!(
queue
.requests()
.next()
.expect("remaining timeout responsibility")
.options
.timeout,
Some(Duration::ZERO),
restarted
.get_task_status(&request.id)
.await
.expect("terminal timeout survives restart"),
HealTaskStatus::Timeout,
"durable={durable}"
);
}
+51 -46
View File
@@ -30,8 +30,8 @@ use super::outcome::{HealObjectDisposition, HealObjectIdentity, HealObjectKind,
use super::progress::stable_generation;
pub use super::replacement_execution::ReplacementExecution;
use super::storage_api::owner::{
EcstoreHealLifecycleExpiryContext, PhysicalResourcePlan, ecstore_load_admin_data_usage_from_backend_cached,
ecstore_with_background_resource_set,
EcstoreDynamicStoreHandle, EcstoreHealLifecycleExpiryContext, PhysicalResourcePlan,
ecstore_load_admin_data_usage_from_backend_cached, ecstore_with_background_resource_set,
};
use super::storage_api::storage::{
BucketInfo, BucketOperations, DiskSetSelector, EcstoreHealObjectStorageResult, HealOperations as _, ListOperations as _,
@@ -982,14 +982,14 @@ async fn await_admitted_object<T>(
/// ECStore Heal storage layer implementation
pub struct ECStoreHealStorage {
ecstore: Arc<ECStore>,
store_handle: EcstoreDynamicStoreHandle,
admission: Option<Arc<NodeAdmission>>,
}
impl ECStoreHealStorage {
pub fn new(ecstore: Arc<ECStore>) -> Self {
Self {
ecstore,
store_handle: ecstore.dynamic_handle(),
admission: None,
}
}
@@ -1001,6 +1001,12 @@ impl ECStoreHealStorage {
self
}
/// Resolve the live hot-reloaded `ECStore` generation for this instance
/// context without pinning retired generations in memory.
fn live_ecstore(&self) -> Arc<ECStore> {
self.store_handle.current()
}
async fn heal_object_admitted(
&self,
bucket: &str,
@@ -1011,7 +1017,7 @@ impl ECStoreHealStorage {
) -> Result<(HealResultItem, Option<Error>)> {
run_background_object_inner(
self.admission.as_ref(),
|| self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage),
|| self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage),
opts,
task_cancel,
|result: &(HealResultItem, Option<Error>)| result.1.is_none(),
@@ -1038,7 +1044,7 @@ impl ECStoreHealStorage {
object,
version_id,
opts,
self.ecstore.heal_object(bucket, object, version_id_str, opts).await,
self.live_ecstore().heal_object(bucket, object, version_id_str, opts).await,
)
}),
)
@@ -1094,7 +1100,7 @@ impl ECStoreHealStorage {
async fn resume_disk_inventory(&self, set_disk_id: &str) -> Result<Vec<DiskStore>> {
let (pool_idx, set_idx) = crate::heal::utils::parse_set_disk_id(set_disk_id)?;
let disks = StorageAdminApi::disk_set_inventory(self.ecstore.as_ref(), DiskSetSelector::new(pool_idx, set_idx))
let disks = StorageAdminApi::disk_set_inventory(self.live_ecstore().as_ref(), DiskSetSelector::new(pool_idx, set_idx))
.await
.map_err(|e| Error::TaskExecutionFailed {
message: format!("Failed to get disks for pool {pool_idx} set {set_idx}: {e}"),
@@ -1157,7 +1163,7 @@ impl ECStoreHealStorage {
{
let bucket_incarnation_id = match expected {
Some(expected) => Some(expected),
None => self.ecstore.bucket_incarnation_id(bucket).await.ok(),
None => self.live_ecstore().bucket_incarnation_id(bucket).await.ok(),
};
bucket_incarnation_id
.and_then(|incarnation| verified_object_receipt(bucket, object, version_id, opts, &item, incarnation))
@@ -1183,7 +1189,7 @@ impl ECStoreHealStorage {
"Heal storage request started"
);
let reader = match (*self.ecstore)
let reader = match (*self.live_ecstore())
.get_object_reader(bucket, object, None, Default::default(), &Default::default())
.await
{
@@ -1280,7 +1286,7 @@ impl HealStorageAPI for ECStoreHealStorage {
opts: &HealOpts,
) -> Result<HealStorageObjectResult> {
let removed = self
.ecstore
.live_ecstore()
.purge_delete_marker_with_proof(bucket, object, version_id, purge, opts)
.await
.map_err(Error::Storage)?;
@@ -1309,7 +1315,7 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn admit_bucket_incarnation(&self, bucket: &str) -> Result<Uuid> {
match self.ecstore.bucket_incarnation_id_from_disk(bucket).await {
match self.live_ecstore().bucket_incarnation_id_from_disk(bucket).await {
Ok(id) if !id.is_nil() => Ok(id),
Ok(_) | Err(StorageError::BucketNotFound(_)) => Err(Error::StaleBucketIncarnation {
bucket: bucket.to_owned(),
@@ -1320,7 +1326,7 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn heal_bucket_at_incarnation(&self, bucket: &str, expected: Uuid, opts: &HealOpts) -> Result<HealResultItem> {
self.ecstore
self.live_ecstore()
.heal_bucket_at_incarnation(bucket, expected, opts)
.await
.map_err(|error| incarnation_storage_error(bucket, expected, error))
@@ -1336,12 +1342,12 @@ impl HealStorageAPI for ECStoreHealStorage {
) -> Result<HealStorageObjectResult> {
run_background_object(
self.admission.as_ref(),
|| self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage),
|| self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage),
opts,
|result: &HealStorageObjectResult| result.error.is_none(),
boxed_object_operation(|| async {
let result = self
.ecstore
.live_ecstore()
.heal_object_at_incarnation(bucket, object, version_id.unwrap_or_default(), expected, opts)
.await
.map_err(|error| incarnation_storage_error(bucket, expected, error))?;
@@ -1364,13 +1370,13 @@ impl HealStorageAPI for ECStoreHealStorage {
) -> Result<HealStorageObjectResult> {
run_background_object_inner(
self.admission.as_ref(),
|| self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage),
|| self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage),
opts,
Some(task_cancel),
|result: &HealStorageObjectResult| result.error.is_none(),
boxed_object_operation(|| async {
let result = self
.ecstore
.live_ecstore()
.heal_object_at_incarnation(bucket, object, version_id.unwrap_or_default(), expected, opts)
.await
.map_err(|error| incarnation_storage_error(bucket, expected, error))?;
@@ -1392,12 +1398,12 @@ impl HealStorageAPI for ECStoreHealStorage {
) -> Result<HealStorageObjectResult> {
run_background_object(
self.admission.as_ref(),
|| self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage),
|| self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage),
opts,
|result: &HealStorageObjectResult| result.error.is_none(),
boxed_object_operation(|| async {
let result = self
.ecstore
.live_ecstore()
.heal_mrf_object_at_incarnation(bucket, object, version_id.unwrap_or_default(), expected, opts)
.await
.map_err(|error| incarnation_storage_error(bucket, expected, error))?;
@@ -1421,7 +1427,7 @@ impl HealStorageAPI for ECStoreHealStorage {
"Heal storage request started"
);
match self.ecstore.get_object_info(bucket, object, &Default::default()).await {
match self.live_ecstore().get_object_info(bucket, object, &Default::default()).await {
Ok(info) => Ok(Some(info)),
Err(e) => {
// Map ObjectNotFound to None to align with Option return type
@@ -1557,7 +1563,7 @@ impl HealStorageAPI for ECStoreHealStorage {
"Heal storage admin operation started"
);
match self.ecstore.get_bucket_info(bucket, &Default::default()).await {
match self.live_ecstore().get_bucket_info(bucket, &Default::default()).await {
Ok(info) => Ok(Some(info)),
Err(e) => {
error!(
@@ -1577,7 +1583,7 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn mrf_bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
match self.ecstore.bucket_incarnation_id(bucket).await {
match self.live_ecstore().bucket_incarnation_id(bucket).await {
Ok(incarnation) => Ok(Some(incarnation)),
// A missing bucket leaves the current identity unresolved. It is
// not a retirement receipt for an unknown source generation.
@@ -1587,14 +1593,14 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn replacement_bucket_incarnation(&self, bucket: &str) -> Result<Option<Uuid>> {
self.ecstore
self.live_ecstore()
.replacement_bucket_incarnation_from_disk(bucket)
.await
.map_err(Error::Storage)
}
async fn mrf_bucket_incarnation_retired(&self, bucket: &str, expected: Uuid) -> Result<bool> {
self.ecstore
self.live_ecstore()
.is_bucket_incarnation_retired(bucket, expected)
.await
.map_err(Error::Storage)
@@ -1605,7 +1611,7 @@ impl HealStorageAPI for ECStoreHealStorage {
return Ok(None);
}
let info = match ecstore_load_admin_data_usage_from_backend_cached(self.ecstore.clone()).await {
let info = match ecstore_load_admin_data_usage_from_backend_cached(self.live_ecstore()).await {
Ok(info) if info.is_complete_bucket_usage_snapshot() => info,
Ok(_) | Err(_) => return Ok(None),
};
@@ -1663,7 +1669,7 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn load_heal_lifecycle_expiry_context(&self, bucket: &str) -> Result<Option<HealLifecycleExpiryContext>> {
match self.ecstore.load_heal_lifecycle_expiry_context(bucket).await {
match self.live_ecstore().load_heal_lifecycle_expiry_context(bucket).await {
Ok(Some(context)) => Ok(Some(HealLifecycleExpiryContext::ecstore(context))),
Ok(None) => Ok(None),
Err(err) => {
@@ -1696,7 +1702,7 @@ impl HealStorageAPI for ECStoreHealStorage {
HealLifecycleExpiryContextInner::Test => return Ok(false),
};
match self
.ecstore
.live_ecstore()
.enqueue_heal_lifecycle_expiry(context, bucket, object, version_id, object_info)
.await
{
@@ -1721,7 +1727,7 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn list_buckets_for_admin_heal(&self, selector: Option<DiskSetSelector>) -> Result<Vec<BucketInfo>> {
let listing = self.ecstore.list_buckets_for_admin_heal(selector).await?;
let listing = self.live_ecstore().list_buckets_for_admin_heal(selector).await?;
if !listing.topology_complete {
return Err(Error::BucketDiscoveryIncomplete);
}
@@ -1739,7 +1745,7 @@ impl HealStorageAPI for ECStoreHealStorage {
"Heal storage admin operation started"
);
match self.ecstore.list_bucket(&Default::default()).await {
match self.live_ecstore().list_bucket(&Default::default()).await {
Ok(buckets) => Ok(buckets),
Err(e) => {
error!(
@@ -1776,7 +1782,7 @@ impl HealStorageAPI for ECStoreHealStorage {
..Default::default()
};
match self.ecstore.get_object_info(bucket, object, &opts).await {
match self.live_ecstore().get_object_info(bucket, object, &opts).await {
Ok(_) => Ok(true), // Object exists
Err(e) => {
if matches!(e, StorageError::ObjectNotFound(_, _)) {
@@ -1828,7 +1834,7 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn bucket_incarnation_id(&self, bucket: &str) -> Result<Option<Uuid>> {
self.ecstore
self.live_ecstore()
.bucket_incarnation_id(bucket)
.await
.map(Some)
@@ -1866,12 +1872,12 @@ impl HealStorageAPI for ECStoreHealStorage {
) -> Result<HealStorageObjectResult> {
run_background_object(
self.admission.as_ref(),
|| self.ecstore.physical_heal_plan(object, opts).map_err(Error::Storage),
|| self.live_ecstore().physical_heal_plan(object, opts).map_err(Error::Storage),
opts,
|result: &HealStorageObjectResult| result.error.is_none(),
boxed_object_operation(|| async {
let result = self
.ecstore
.live_ecstore()
.heal_object_with_proof(bucket, object, version_id.unwrap_or(""), opts)
.await
.map_err(Error::Storage)?;
@@ -1890,7 +1896,7 @@ impl HealStorageAPI for ECStoreHealStorage {
expected: Option<Uuid>,
opts: &HealOpts,
) -> Result<Option<HealResultItem>> {
self.ecstore
self.live_ecstore()
.recover_delete_transactions_at_incarnation(bucket, object, expected, opts)
.await
.map_err(Error::Storage)
@@ -1903,7 +1909,7 @@ impl HealStorageAPI for ECStoreHealStorage {
expected: Option<Uuid>,
opts: &HealOpts,
) -> Result<Option<HealResultItem>> {
self.ecstore
self.live_ecstore()
.recover_delete_prefix_at_incarnation(bucket, prefix, expected, opts)
.await
.map_err(Error::Storage)
@@ -1923,7 +1929,7 @@ impl HealStorageAPI for ECStoreHealStorage {
"Heal storage repair started"
);
match self.ecstore.heal_bucket(bucket, opts).await {
match self.live_ecstore().heal_bucket(bucket, opts).await {
Ok(result) => {
debug!(
target: "rustfs::heal::storage",
@@ -1967,7 +1973,7 @@ impl HealStorageAPI for ECStoreHealStorage {
"Heal storage repair started"
);
match self.ecstore.heal_format(dry_run).await {
match self.live_ecstore().heal_format(dry_run).await {
Ok((result, ecstore_error)) => {
let error = ecstore_error.map(Error::Storage);
debug!(
@@ -2006,7 +2012,7 @@ impl HealStorageAPI for ECStoreHealStorage {
set_index: usize,
targets: &[String],
) -> Result<(HealResultItem, Option<Error>)> {
self.ecstore
self.live_ecstore()
.heal_replacement_format(dry_run, pool_index, set_index, targets)
.await
.map(|(result, error)| (result, error.map(Error::Storage)))
@@ -2020,13 +2026,13 @@ impl HealStorageAPI for ECStoreHealStorage {
let set_index = opts
.set
.ok_or_else(|| Error::other("replacement pool metadata placement is missing set scope"))?;
self.ecstore
self.live_ecstore()
.replacement_pool_metadata_required(pool_index, set_index)
.map_err(Error::Storage)
}
async fn heal_replacement_bucket_metadata(&self, bucket: &str, opts: &HealOpts, targets: &[String]) -> Result<()> {
self.ecstore
self.live_ecstore()
.heal_replacement_bucket_metadata(bucket, opts, targets)
.await
.map_err(Error::Storage)
@@ -2039,7 +2045,7 @@ impl HealStorageAPI for ECStoreHealStorage {
opts: &HealOpts,
targets: &[String],
) -> Result<()> {
self.ecstore
self.live_ecstore()
.heal_replacement_bucket_metadata_at_incarnation(bucket, expected, opts, targets)
.await
.map_err(|error| incarnation_storage_error(bucket, expected, error))
@@ -2059,7 +2065,7 @@ impl HealStorageAPI for ECStoreHealStorage {
let set_index = opts
.set
.ok_or_else(|| Error::other("replacement target readback is missing set scope"))?;
self.ecstore
self.live_ecstore()
.replacement_targets_have_version(bucket, object, version_id.unwrap_or(""), pool_index, set_index, targets)
.await
.map_err(Error::Storage)
@@ -2094,8 +2100,7 @@ impl HealStorageAPI for ECStoreHealStorage {
// Enumerate EVERY version (not just the latest) so old versions and
// delete-marker-latest objects are healed too.
let list_info = match self
.ecstore
.clone()
.live_ecstore()
.list_object_versions(bucket, prefix, marker, version_marker, None, MAX_KEYS)
.await
{
@@ -2175,7 +2180,7 @@ impl HealStorageAPI for ECStoreHealStorage {
}
async fn heal_erasure_set_scopes(&self, opts: &HealOpts) -> Result<Option<Vec<(usize, usize)>>> {
self.ecstore
self.live_ecstore()
.heal_erasure_set_scopes(opts)
.await
.map(Some)
@@ -2216,7 +2221,7 @@ impl HealStorageAPI for ECStoreHealStorage {
let forward_to = decode_disk_walk_token(continuation_token.unwrap_or(""));
let (versions, next_forward, is_truncated) = self
.ecstore
.live_ecstore()
.heal_walk_versions_page(
pool_idx,
set_idx,
@@ -2499,7 +2504,7 @@ impl HealStorageAPI for ECStoreHealStorage {
async fn replacement_preformat_retry_is_safe(&self, set_disk_id: &str, targets: &[String]) -> Result<bool> {
let (pool_index, set_index) = crate::heal::utils::parse_set_disk_id(set_disk_id)?;
self.ecstore
self.live_ecstore()
.replacement_preformat_retry_is_safe(pool_index, set_index, targets)
.await
.map_err(Error::Storage)
+6 -4
View File
@@ -61,8 +61,9 @@ pub(crate) use rustfs_ecstore::api::runtime::local_disk_map_read as ecstore_loca
#[cfg(test)]
pub(crate) use rustfs_ecstore::api::storage::init_local_disks as ecstore_init_local_disks;
pub(crate) use rustfs_ecstore::api::storage::{
ECStore as EcstoreStore, HealLifecycleExpiryContext as EcstoreHealLifecycleExpiryContext,
HealObjectStorageResult as EcstoreHealObjectStorageResult, POOL_META_NAME as ECSTORE_POOL_META_NAME,
DynamicECStoreHandle as EcstoreDynamicStoreHandle, ECStore as EcstoreStore,
HealLifecycleExpiryContext as EcstoreHealLifecycleExpiryContext, HealObjectStorageResult as EcstoreHealObjectStorageResult,
POOL_META_NAME as ECSTORE_POOL_META_NAME,
};
use rustfs_storage_api as storage_contracts;
@@ -85,8 +86,9 @@ pub(crate) mod owner {
ECSTORE_BUCKET_META_PREFIX, ECSTORE_DATA_USAGE_CACHE_NAME, ECSTORE_HEAL_REPLACEMENT_RECOVERY_DIR,
ECSTORE_HEALING_MARKER_PATH, ECSTORE_POOL_META_NAME, ECSTORE_RUSTFS_META_BUCKET, EcstoreConditionalFileUpdate,
EcstoreDeleteOptions, EcstoreDiskAPI, EcstoreDiskBytes, EcstoreDiskError, EcstoreDiskResult, EcstoreDiskStore,
EcstoreEndpoint, EcstoreErrorType, EcstoreHealLifecycleExpiryContext, EcstoreStorageError, EcstoreStore,
ecstore_is_reserved_or_invalid_bucket, ecstore_load_admin_data_usage_from_backend_cached, ecstore_local_disk_map_read,
EcstoreDynamicStoreHandle, EcstoreEndpoint, EcstoreErrorType, EcstoreHealLifecycleExpiryContext, EcstoreStorageError,
EcstoreStore, ecstore_is_reserved_or_invalid_bucket, ecstore_load_admin_data_usage_from_backend_cached,
ecstore_local_disk_map_read,
};
pub(crate) use super::{EcstoreDiskOption, ecstore_new_disk};
+40 -35
View File
@@ -26,6 +26,7 @@ use crate::{
manager::{extract_jwt_claims, extract_jwt_claims_allow_missing_exp, get_default_policies},
root_credentials,
};
use arc_swap::ArcSwap;
use futures::future::join_all;
use rustfs_io_metrics::record_system_path_failure;
use rustfs_policy::{auth::UserIdentity, policy::PolicyDoc};
@@ -255,7 +256,7 @@ pub(crate) fn decrypt_iam_blob(data: &[u8]) -> Result<Vec<u8>> {
#[derive(Clone)]
pub struct ObjectStore {
object_api: Arc<IamStore>,
object_api: Arc<ArcSwap<IamStore>>,
}
struct ObjectGroupEdit {
@@ -309,7 +310,20 @@ impl ObjectStore {
const BUCKET_NAME: &'static str = ".rustfs.sys";
pub fn new(object_api: Arc<IamStore>) -> Self {
Self { object_api }
Self {
object_api: Arc::new(ArcSwap::from(object_api)),
}
}
#[inline]
fn api(&self) -> Arc<IamStore> {
self.object_api.load_full()
}
/// Atomically rebind this IAM store to a successor `ECStore` generation
/// during a live pool topology hot-reload.
pub fn rebind_store(&self, object_api: Arc<IamStore>) {
self.object_api.store(object_api);
}
fn decrypt_data_with_source(data: &[u8]) -> Result<DecryptOutcome> {
@@ -484,7 +498,7 @@ impl ObjectStore {
..Default::default()
});
save_iam_config_with_opts(self.object_api.clone(), path, encrypted, &opts).await
save_iam_config_with_opts(self.api(), path, encrypted, &opts).await
}
fn is_plaintext_json(data: &[u8]) -> bool {
@@ -502,7 +516,7 @@ impl ObjectStore {
mode: LoadMode,
) -> Result<(Vec<u8>, IamObjectInfo)> {
let path_ref = path.as_ref();
let (data, obj) = read_iam_config_with_metadata(self.object_api.clone(), path_ref, &mode.read_opts()).await?;
let (data, obj) = read_iam_config_with_metadata(self.api(), path_ref, &mode.read_opts()).await?;
let outcome = Self::decrypt_data_with_source(&data)?;
self.maybe_schedule_lazy_rewrite(path_ref, &outcome, &obj);
@@ -512,7 +526,7 @@ impl ObjectStore {
async fn list_iam_config_items(&self, prefix: &str, ctx: CancellationToken, sender: Sender<StringOrErr>) {
// debug!("list iam config items, prefix: {}", &prefix);
let store = self.object_api.clone();
let store = self.api();
let (tx, mut rx) = mpsc::channel::<ObjectInfoOrErr>(100);
@@ -686,7 +700,7 @@ impl ObjectStore {
/// keeps the bootstrap snapshot load free of namespace locks (rustfs#4304).
async fn load_iam_config_with<Item: DeserializeOwned>(&self, path: impl AsRef<str> + Send, mode: LoadMode) -> Result<Item> {
let path_ref = path.as_ref();
let (data, obj) = read_iam_config_with_metadata(self.object_api.clone(), path_ref, &mode.read_opts()).await?;
let (data, obj) = read_iam_config_with_metadata(self.api(), path_ref, &mode.read_opts()).await?;
let outcome = match Self::decrypt_data_with_source(&data) {
Ok(v) => v,
@@ -708,8 +722,7 @@ impl ObjectStore {
}
async fn read_iam_record_with_revision<Item: DeserializeOwned>(&self, path: &str) -> Result<Option<(Item, String)>> {
let existing =
read_config_preserve_empty_with_metadata_opts(self.object_api.clone(), path, &LoadMode::Locked.read_opts()).await;
let existing = read_config_preserve_empty_with_metadata_opts(self.api(), path, &LoadMode::Locked.read_opts()).await;
match existing.map_err(Error::from) {
Ok((data, metadata)) => {
let record = Self::decode_iam_config_strict(&data)?;
@@ -769,7 +782,7 @@ impl ObjectStore {
..Default::default()
};
let data = Self::prepare_data_for_storage(&serde_json::to_vec(record)?)?;
save_iam_config_with_opts(self.object_api.clone(), &path, data, &opts).await?;
save_iam_config_with_opts(self.api(), &path, data, &opts).await?;
Ok(())
}
@@ -963,7 +976,7 @@ impl ObjectStore {
// If it doesn't exist, the system bucket or metadata is not ready.
let probe_path = format!("{}/format.json", *IAM_CONFIG_PREFIX);
match read_iam_config_no_lock(self.object_api.clone(), &probe_path).await {
match read_iam_config_no_lock(self.api(), &probe_path).await {
Ok(_) => Ok(()),
Err(IamStorageError::ConfigNotFound) => Err(Error::other(format!(
"Storage metadata not ready: probe object '{}' not found (expected IAM config to be initialized)",
@@ -977,7 +990,7 @@ impl ObjectStore {
#[async_trait::async_trait]
impl Store for ObjectStore {
async fn load_bucket_tags(&self, bucket: &str) -> Result<HashMap<String, String>> {
Ok(self.object_api.get_bucket_tags_for_policy(bucket).await?)
Ok(self.api().get_bucket_tags_for_policy(bucket).await?)
}
fn has_watcher(&self) -> bool {
@@ -988,8 +1001,7 @@ impl Store for ObjectStore {
}
async fn load_iam_config_strict<Item: DeserializeOwned>(&self, path: impl AsRef<str> + Send) -> Result<Item> {
let (data, _) =
read_config_preserve_empty_with_metadata_opts(self.object_api.clone(), path.as_ref(), &LoadMode::Locked.read_opts())
.await?;
read_config_preserve_empty_with_metadata_opts(self.api(), path.as_ref(), &LoadMode::Locked.read_opts()).await?;
Self::decode_iam_config_strict(&data)
}
/// Saves IAM configuration with a retry mechanism on failure.
@@ -1015,7 +1027,7 @@ impl Store for ObjectStore {
let path_ref = path.as_ref();
loop {
match save_iam_config(self.object_api.clone(), path_ref, data.clone()).await {
match save_iam_config(self.api(), path_ref, data.clone()).await {
Ok(_) => {
debug!("Successfully saved IAM config to {}", path_ref);
return Ok(());
@@ -1038,7 +1050,7 @@ impl Store for ObjectStore {
}
}
async fn delete_iam_config(&self, path: impl AsRef<str> + Send) -> Result<()> {
delete_iam_config(self.object_api.clone(), path.as_ref()).await?;
delete_iam_config(self.api(), path.as_ref()).await?;
Ok(())
}
@@ -1165,18 +1177,15 @@ impl Store for ObjectStore {
}
let policy_path = get_mapped_policy_path(name, UserType::Svc, false);
let policy_revision = match read_config_preserve_empty_with_metadata_opts(
self.object_api.clone(),
&policy_path,
&LoadMode::Locked.read_opts(),
)
.await
.map_err(Error::from)
{
Ok((_, metadata)) => metadata.etag.filter(|tag| !tag.is_empty() && tag != "*"),
Err(err) if is_err_config_not_found(&err) => None,
Err(err) => return Err(err),
};
let policy_revision =
match read_config_preserve_empty_with_metadata_opts(self.api(), &policy_path, &LoadMode::Locked.read_opts())
.await
.map_err(Error::from)
{
Ok((_, metadata)) => metadata.etag.filter(|tag| !tag.is_empty() && tag != "*"),
Err(err) if is_err_config_not_found(&err) => None,
Err(err) => return Err(err),
};
// Conditionally delete the identity before touching any mapped policy. Keep `delete_prefix`
// false so ECStore evaluates `If-Match` against the current identity object revision.
@@ -1189,7 +1198,7 @@ impl Store for ObjectStore {
..Default::default()
};
match self
.object_api
.api()
.delete_object(Self::BUCKET_NAME, &identity_path, identity_opts)
.await
{
@@ -1209,11 +1218,7 @@ impl Store for ObjectStore {
}),
..Default::default()
};
match self
.object_api
.delete_object(Self::BUCKET_NAME, &policy_path, policy_opts)
.await
{
match self.api().delete_object(Self::BUCKET_NAME, &policy_path, policy_opts).await {
Ok(_)
| Err(
IamStorageError::PreconditionFailed | IamStorageError::FileNotFound | IamStorageError::ObjectNotFound(_, _),
@@ -1284,7 +1289,7 @@ impl Store for ObjectStore {
let path = get_group_info_path(name);
// Take the transaction lock before any object locks. A distinct key lets ordinary
// config reads, writes and deletes keep taking their own namespace locks.
let lock = self.object_api.new_ns_lock(Self::BUCKET_NAME, &format!("{path}.txn")).await?;
let lock = self.api().new_ns_lock(Self::BUCKET_NAME, &format!("{path}.txn")).await?;
let guard = WriteCommitGuard::acquire(&lock, get_lock_acquire_timeout())
.await
.map_err(Error::other)?;
@@ -1294,7 +1299,7 @@ impl Store for ObjectStore {
Err(err) => return Err(err),
};
let edit = ObjectGroupEdit {
api: self.object_api.clone(),
api: self.api(),
path,
policy_path: get_mapped_policy_path(name, UserType::Reg, true),
guard,
+22 -9
View File
@@ -585,7 +585,20 @@ impl<T: Store> IamSys<T> {
pub fn sync_metrics_snapshot(&self) -> IamSyncMetricsSnapshot {
self.store.sync_metrics_snapshot()
}
}
impl IamSys<crate::store::object::ObjectStore> {
/// Atomically rebind the IAM storage backend to a successor `ECStore`
/// generation after a live pool topology hot-reload.
pub fn rebind_store(&self, store: Arc<crate::IamStore>) {
self.store.api.rebind_store(store);
}
}
impl<T> IamSys<T>
where
T: Store,
{
pub async fn set_policy_plugin_client(client: rustfs_policy::policy::opa::AuthZPlugin) {
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Ready(client)));
}
@@ -3518,8 +3531,8 @@ mod tests {
("no_proxy", Some("127.0.0.1,localhost")),
],
async {
let previous = IamSys::<StsTestMockStore>::policy_plugin_state().await;
*get_policy_plugin_state().write().await = PolicyPluginState::Disabled;
let plugin_state = get_policy_plugin_state();
let previous = plugin_state.swap(Arc::new(PolicyPluginState::Disabled));
let result = std::panic::AssertUnwindSafe(async {
let store = StsTestMockStore::new(true);
let iam = IamSys::new(IamCache::new(store).await.expect("initialize Vector IAM fixture"));
@@ -3527,7 +3540,7 @@ mod tests {
})
.catch_unwind()
.await;
*get_policy_plugin_state().write().await = previous;
plugin_state.store(previous);
if let Err(payload) = result {
std::panic::resume_unwind(payload);
}
@@ -4106,9 +4119,9 @@ mod tests {
.await,
Ok(false)
));
*get_policy_plugin_state().write().await = PolicyPluginState::Failed;
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Failed));
assert!(matches!(iam.is_allowed_with_resource_policy(&request, None).await, Ok(true)));
*get_policy_plugin_state().write().await = PolicyPluginState::Disabled;
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Disabled));
request.is_owner = false;
assert!(iam.is_allowed_with_resource_policy(&request, None).await.is_err());
@@ -4254,12 +4267,12 @@ mod tests {
assert_eq!(input["input"]["identity"]["account"], credential.access_key);
assert_eq!(input["input"]["identity"]["is_owner"], false);
}
*get_policy_plugin_state().write().await = PolicyPluginState::Failed;
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Failed));
assert!(matches!(
iam.is_allowed_with_resource_policy(&request, None).await,
Err(Error::IamSysNotInitialized)
));
*get_policy_plugin_state().write().await = PolicyPluginState::Disabled;
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Disabled));
}
})
.await;
@@ -4285,7 +4298,7 @@ mod tests {
));
attach(&iam, ACCOUNT, Some(policy("Allow", "s3vectors:GetVectors")));
assert!(matches!(iam.is_allowed_with_resource_policy(&request, Some(&resource)).await, Ok(true)));
*get_policy_plugin_state().write().await = PolicyPluginState::Failed;
get_policy_plugin_state().store(Arc::new(PolicyPluginState::Failed));
assert!(matches!(
iam.is_allowed_with_resource_policy(&request, Some(&resource)).await,
Err(Error::IAMActionNotAllowed)
@@ -4410,7 +4423,7 @@ mod tests {
assert_eq!(input["input"]["context"]["conditions"]["ResourceTag/project"], json!(["search"]));
}
for state in [PolicyPluginState::Initializing, PolicyPluginState::Failed] {
*get_policy_plugin_state().write().await = state;
get_policy_plugin_state().store(Arc::new(state));
assert!(matches!(
iam.is_allowed_with_resource_policy(&request, Some(&resource)).await,
Err(Error::IamSysNotInitialized)
+6 -4
View File
@@ -75,11 +75,11 @@ rustfs-s3-types = { workspace = true }
# `rustls` named explicitly: `reqwest::Identity::from_pem` (Vault mTLS) is only
# available on the rustls TLS backend, and relying on another crate's feature
# unification to enable it would break silently if that crate changed.
reqwest = { workspace = true, features = ["rustls"] }
vaultrs = { workspace = true }
reqwest = { workspace = true, features = ["rustls"], optional = true }
vaultrs = { workspace = true, optional = true }
# vaultrs surfaces transport-level failures as wrapped rustify errors; the
# operation policy needs the concrete type to classify them for retry decisions.
rustify = { workspace = true }
rustify = { workspace = true, optional = true }
tokio-util = { workspace = true }
# AWS KMS backend. Credentials come from the standard aws-config provider chain
@@ -110,7 +110,9 @@ http = { workspace = true }
tracing-subscriber = { workspace = true, features = ["fmt"] }
[features]
default = []
default = ["vault"]
vault = ["dep:reqwest", "dep:rustify", "dep:vaultrs"]
fuzzing = []
hotpath = [
"hotpath/hotpath",
"hotpath/tokio",
+7 -1
View File
@@ -13,6 +13,7 @@
// limitations under the License.
//! KMS backend implementations
#![cfg_attr(not(feature = "vault"), allow(dead_code))]
use crate::error::{KmsError, Result};
use crate::types::*;
@@ -25,11 +26,14 @@ pub mod aws;
#[cfg(test)]
mod contract_tests;
pub mod local;
#[cfg(test)]
#[cfg(all(test, feature = "vault"))]
pub(crate) mod scripted_vault;
pub mod static_kms;
#[cfg(feature = "vault")]
pub mod vault;
#[cfg(feature = "vault")]
pub(crate) mod vault_credentials;
#[cfg(feature = "vault")]
pub mod vault_transit;
/// Refuse a key identifier that cannot be used as a single path segment.
@@ -1000,6 +1004,7 @@ mod tests {
insta::assert_json_snapshot!("local_backend_capabilities", capabilities_snapshot(backend.capabilities()));
}
#[cfg(feature = "vault")]
#[tokio::test]
async fn vault_kv2_backend_capabilities_golden() {
let config = KmsConfig::vault(
@@ -1015,6 +1020,7 @@ mod tests {
insta::assert_json_snapshot!("vault_kv2_backend_capabilities", capabilities_snapshot(backend.capabilities()));
}
#[cfg(feature = "vault")]
#[tokio::test]
async fn vault_transit_backend_capabilities_golden() {
let config = KmsConfig::vault_transit(
+2
View File
@@ -58,6 +58,7 @@ mod error;
pub mod local_export;
pub mod local_restore;
mod manifest;
#[cfg(feature = "vault")]
pub mod vault_restore;
pub use capability::{AtRestProtection, BackupBackendKind, BackupResponsibility};
@@ -82,6 +83,7 @@ pub use manifest::{
DigestAlgorithm, LocalKdfDescriptor, LocalKeyDerivation, ReservedSlot, VaultExternalReferences, VaultKvRecordReference,
VaultTransitReference,
};
#[cfg(feature = "vault")]
pub use vault_restore::{
VaultRestoreAbortReport, VaultRestoreAbortSkip, VaultRestoreAbortSkipReason, VaultRestoreClient, VaultRestoreMismatch,
VaultRestoreReport, VaultRestoreRequest, VaultRestoreSequence, VaultRestoreStage, VaultRestoreTarget, abort_vault_restore,
+4 -2
View File
@@ -17,7 +17,9 @@
pub mod ciphers;
pub mod dek;
#[cfg(feature = "vault")]
pub use dek::desired_context_binding;
pub use dek::{
AesDekCrypto, CONTEXT_BINDING_AAD_V1, DataKeyEnvelope, DekCrypto, context_aad, desired_context_binding,
envelope_aad_write_enabled, envelope_wrap_aad, generate_key_material, is_data_key_envelope,
AesDekCrypto, CONTEXT_BINDING_AAD_V1, DataKeyEnvelope, DekCrypto, context_aad, envelope_aad_write_enabled, envelope_wrap_aad,
generate_key_material, is_data_key_envelope,
};
+1
View File
@@ -407,6 +407,7 @@ impl From<url::ParseError> for KmsError {
}
}
#[cfg(feature = "vault")]
impl From<reqwest::Error> for KmsError {
fn from(error: reqwest::Error) -> Self {
Self::BackendError {
+11
View File
@@ -84,6 +84,17 @@ pub mod service_manager;
mod time_serde;
pub mod types;
#[cfg(feature = "fuzzing")]
pub mod fuzz_exports {
pub use crate::encryption::{
ciphers::{AesCipher, ChaCha20Cipher, ObjectCipher},
dek::{
AesDekCrypto, CONTEXT_BINDING_AAD_V1, DataKeyEnvelope, DekCrypto, context_aad, desired_context_binding,
envelope_wrap_aad, is_data_key_envelope,
},
};
}
#[cfg(test)]
pub(crate) mod test_support {
use crate::persisted_observability::UNKNOWN_FIELDS_METRIC;
+4
View File
@@ -13,6 +13,7 @@
// limitations under the License.
//! Operation execution policy for external KMS backend calls.
#![cfg_attr(not(feature = "vault"), allow(dead_code))]
//!
//! Vault-backed operations leave the process boundary, so every call needs a
//! per-attempt timeout, a total operation deadline, and classification-driven
@@ -100,6 +101,7 @@ pub(crate) enum ErrorClass {
/// page from an intermediate load balancer). Everything that is not throttling,
/// a recoverable 5xx, or a connection-level failure is fatal; in particular
/// 400/401/403/404 must never be retried.
#[cfg(feature = "vault")]
pub(crate) fn classify_vaultrs(error: &vaultrs::error::ClientError) -> ErrorClass {
use rustify::errors::ClientError as RestError;
use vaultrs::error::ClientError;
@@ -145,6 +147,7 @@ impl AttemptError {
/// Classification reads the raw error before `map` consumes it, so call
/// sites keep their site-specific error mapping (404 to key-not-found and
/// so on) without losing the status code the retry decision needs.
#[cfg(feature = "vault")]
pub(crate) fn from_vaultrs(
error: vaultrs::error::ClientError,
map: impl FnOnce(vaultrs::error::ClientError) -> KmsError,
@@ -1811,6 +1814,7 @@ mod tests {
assert_eq!(policy.max_attempts, in_range.retry_attempts);
}
#[cfg(feature = "vault")]
#[test]
fn classify_vaultrs_matrix() {
use rustify::errors::ClientError as RestError;
+27 -8
View File
@@ -15,6 +15,7 @@
//! KMS service manager for dynamic configuration and runtime management
use crate::audit::KmsAuditSink;
#[cfg(feature = "vault")]
use crate::backends::vault_credentials::CredentialTaskHandle;
use crate::backends::{KmsBackend, local::LocalKmsBackend};
use crate::config::{BackendConfig, KmsConfig};
@@ -118,6 +119,7 @@ struct ServiceVersion {
/// Owner of the backend's credential renewal task, if the backend needs
/// one. Stop shuts it down explicitly; reconfigure recycles it through
/// the handle's cancel-on-drop behavior when the old version is discarded.
#[cfg(feature = "vault")]
credential_task: Option<Arc<CredentialTaskHandle>>,
/// Background deletion worker owned by this service version, if the
/// backend supports deletion scheduling
@@ -444,6 +446,7 @@ impl KmsServiceManager {
// Shut down the stopped version's credential renewal task before
// reporting stopped, so stop deterministically recycles the background
// task even while in-flight operations still hold the old service Arc.
#[cfg(feature = "vault")]
if let Some(task) = state.current_service.as_ref().and_then(|sv| sv.credential_task.clone()) {
task.shutdown().await;
}
@@ -622,6 +625,7 @@ impl KmsServiceManager {
// Create backend. Vault backends may also spawn a background
// credential renewal task whose owner handle lives on the service
// version, so replacing the version recycles the task.
#[cfg(feature = "vault")]
let mut credential_task = None;
let backend = match &config.backend_config {
BackendConfig::Local(_) => {
@@ -630,16 +634,30 @@ impl KmsServiceManager {
Arc::new(backend) as Arc<dyn KmsBackend>
}
BackendConfig::VaultKv2(_) => {
info!("Creating Vault KV2 KMS backend for version {}", version);
let backend = crate::backends::vault::VaultKmsBackend::new(config.clone()).await?;
credential_task = backend.spawn_credential_renewal().map(Arc::new);
Arc::new(backend) as Arc<dyn KmsBackend>
#[cfg(feature = "vault")]
{
info!("Creating Vault KV2 KMS backend for version {}", version);
let backend = crate::backends::vault::VaultKmsBackend::new(config.clone()).await?;
credential_task = backend.spawn_credential_renewal().map(Arc::new);
Arc::new(backend) as Arc<dyn KmsBackend>
}
#[cfg(not(feature = "vault"))]
{
return Err(KmsError::configuration_error("Vault KV2 KMS backend disabled at compile time"));
}
}
BackendConfig::VaultTransit(_) => {
info!("Creating Vault Transit KMS backend for version {}", version);
let backend = crate::backends::vault_transit::VaultTransitKmsBackend::new(config.clone()).await?;
credential_task = backend.spawn_credential_renewal().map(Arc::new);
Arc::new(backend) as Arc<dyn KmsBackend>
#[cfg(feature = "vault")]
{
info!("Creating Vault Transit KMS backend for version {}", version);
let backend = crate::backends::vault_transit::VaultTransitKmsBackend::new(config.clone()).await?;
credential_task = backend.spawn_credential_renewal().map(Arc::new);
Arc::new(backend) as Arc<dyn KmsBackend>
}
#[cfg(not(feature = "vault"))]
{
return Err(KmsError::configuration_error("Vault Transit KMS backend disabled at compile time"));
}
}
BackendConfig::Static(_) => {
info!("Creating Static KMS backend for version {}", version);
@@ -687,6 +705,7 @@ impl KmsServiceManager {
version,
service: encryption_service,
manager: kms_manager,
#[cfg(feature = "vault")]
credential_task,
deletion_worker: None,
probe_worker: None,
+2 -2
View File
@@ -20,7 +20,7 @@ workspace = true
# workspace build touches vendor C/C++ tooling.
[target.'cfg(target_os = "linux")'.dependencies]
aws-credential-types = { workspace = true, optional = true }
aws-sigv4 = { version = "1.2", optional = true }
aws-sigv4 = { version = "1.6", optional = true }
base64-simd = { workspace = true, optional = true }
bytes = { workspace = true, optional = true }
libc = { workspace = true, optional = true }
@@ -29,7 +29,7 @@ nixl-sys = { workspace = true, optional = true }
parking_lot = { workspace = true, optional = true }
quick-xml = { workspace = true, features = ["serialize"], optional = true }
# Match the native rc transport so it can retain its alias TLS and proxy policy.
reqwest = { version = "0.12", default-features = false, optional = true }
reqwest = { version = ">=0.12, <0.13", default-features = false, optional = true }
rustix = { workspace = true, features = ["fs"], optional = true }
serde = { workspace = true, features = ["derive"], optional = true }
thiserror = { workspace = true, optional = true }
+20 -1
View File
@@ -1471,6 +1471,20 @@ pub async fn start_background_task(disks: Vec<CapacityDiskRef>) {
/// Start capacity refresh and metrics schedulers with lifecycle ownership.
pub async fn start_background_tasks(disks: Vec<CapacityDiskRef>) -> CapacityBackgroundTasks {
start_background_tasks_dynamic(move || {
let disks = disks.clone();
async move { disks }
})
.await
}
/// Start capacity refresh and metrics schedulers using a dynamic local-disk
/// discovery closure so topology hot-reload additions and removals are tracked.
pub async fn start_background_tasks_dynamic<F, Fut>(disk_provider: F) -> CapacityBackgroundTasks
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Vec<CapacityDiskRef>> + Send + 'static,
{
let manager = get_capacity_manager();
let manager_for_refresh = manager.clone();
let manager_for_metrics = manager.clone();
@@ -1487,7 +1501,12 @@ pub async fn start_background_tasks(disks: Vec<CapacityDiskRef>) -> CapacityBack
tasks.spawn(async move {
run_scheduled_refresh_loop(refresh_interval, refresh_shutdown, move || {
run_scheduled_capacity_refresh(manager_for_refresh.clone(), disks.clone())
let manager = manager_for_refresh.clone();
let fut = disk_provider();
async move {
let disks = fut.await;
run_scheduled_capacity_refresh(manager, disks).await
}
})
.await;
});
+3 -2
View File
@@ -29,7 +29,8 @@ documentation = "https://docs.rs/rustfs-s3select-api/latest/rustfs_s3select_api/
workspace = true
[features]
default = []
default = ["parquet"]
parquet = ["datafusion/parquet"]
hotpath = [
"hotpath/hotpath",
"hotpath/tokio",
@@ -70,7 +71,7 @@ chrono = { workspace = true, features = ["serde"] }
jiff = { workspace = true, features = ["serde"] }
crc-fast.workspace = true
rustfs-common.workspace = true
datafusion = { workspace = true, default-features = false, features = ["parquet", "recursive_protection", "sql"] }
datafusion = { workspace = true, default-features = false, features = ["recursive_protection", "sql"] }
rustfs-ecstore.workspace = true
rustfs-gateway-types.workspace = true
rustfs-s3-types = { workspace = true }
+9 -2
View File
@@ -14,10 +14,11 @@
#![recursion_limit = "256"]
#[cfg(feature = "parquet")]
use datafusion::parquet::errors::ParquetError;
use datafusion::{
arrow::error::ArrowError,
common::{DataFusionError, SchemaError},
parquet::errors::ParquetError,
sql::sqlparser::parser::ParserError,
};
use std::{error::Error as StdError, fmt::Display};
@@ -27,6 +28,7 @@ mod csv_input;
mod input_stream;
mod metrics;
pub mod object_store;
#[cfg(feature = "parquet")]
pub mod parquet_budget;
pub mod query;
pub mod request;
@@ -220,6 +222,7 @@ fn classify_select_error_source(err: &(dyn StdError + 'static)) -> Option<Select
if let Some(error) = err.downcast_ref::<SelectError>() {
return Some(error.clone());
}
#[cfg(feature = "parquet")]
if let Some(error) = err.downcast_ref::<parquet_budget::ParquetBudgetError>() {
return Some(match error {
parquet_budget::ParquetBudgetError::Exceeded => SelectError::ResourceExhausted,
@@ -257,6 +260,7 @@ fn classify_select_error_source(err: &(dyn StdError + 'static)) -> Option<Select
_ => Some(SelectError::InternalError),
};
}
#[cfg(feature = "parquet")]
if let Some(error) = err.downcast_ref::<ParquetError>() {
return match error {
ParquetError::External(_) => None,
@@ -281,8 +285,9 @@ fn classify_select_error_source(err: &(dyn StdError + 'static)) -> Option<Select
| DataFusionError::Configuration(_)
| DataFusionError::Substrait(_)
| DataFusionError::Ffi(_) => Some(SelectError::InternalError),
#[cfg(feature = "parquet")]
DataFusionError::ParquetError(_) => None,
DataFusionError::ArrowError(_, _)
| DataFusionError::ParquetError(_)
| DataFusionError::ObjectStore(_)
| DataFusionError::IoError(_)
| DataFusionError::SQL(_, _)
@@ -346,6 +351,7 @@ mod tests {
use datafusion::common::DataFusionError;
use datafusion::sql::sqlparser::parser::ParserError;
#[cfg(feature = "parquet")]
#[test]
fn parquet_admission_errors_preserve_select_error_codes() {
for (source, expected) in [
@@ -459,6 +465,7 @@ mod tests {
DataFusionError::ArrowError(Box::new(ArrowError::JsonError("private json detail".to_string())), None),
SelectError::JsonParsingError,
),
#[cfg(feature = "parquet")]
(
DataFusionError::ParquetError(Box::new(ParquetError::General("private parquet detail".to_string()))),
SelectError::ParquetParsingError,
+17 -6
View File
@@ -28,7 +28,7 @@ use crate::{
},
query::{
ast::{JsonPathSegment, JsonSource},
parser::{BoundedRustFsDialect, validate_set_operator_budget},
parser::{BoundedRustFsDialect, validate_compound_identifier_depth, validate_set_operator_budget},
session::QueryExecutionTracker,
},
resolve_select_object_store_handle, select_is_err_bucket_not_found, select_is_err_object_not_found,
@@ -566,13 +566,16 @@ pub(crate) fn legacy_json_source_from_input(input: &SelectObjectContentInput) ->
if validate_set_operator_budget(&tokens).is_err() {
return JsonSource::default();
}
let Ok(mut statements) = SqlParser::new(&dialect).with_tokens(tokens).parse_statements() else {
let Ok(statements) = SqlParser::new(&dialect).with_tokens(tokens).parse_statements() else {
return JsonSource::default();
};
if statements.len() != 1 {
let [statement] = statements.as_slice() else {
return JsonSource::default();
};
if validate_compound_identifier_depth(statement).is_err() {
return JsonSource::default();
}
let Some(Statement::Query(query)) = statements.pop() else {
let Statement::Query(query) = statement else {
return JsonSource::default();
};
let SetExpr::Select(select) = query.body.as_ref() else {
@@ -940,6 +943,7 @@ impl ObjectStore for EcObjectStore {
meta,
range: result_range,
attributes: Attributes::default(),
extensions: Default::default(),
});
}
@@ -1104,6 +1108,7 @@ impl ObjectStore for EcObjectStore {
meta,
range: result_range,
attributes: Attributes::default(),
extensions: Default::default(),
})
}
@@ -1686,11 +1691,17 @@ mod test {
}
#[test]
fn legacy_source_adapter_bounds_operator_and_set_chains_on_small_stack() {
fn legacy_source_adapter_bounds_sql_chains_on_small_stack() {
use crate::query::parser::MAX_SELECT_FIELD_ACCESS_DEPTH;
let plus_chain = format!("SELECT {} FROM S3Object.employees", vec!["1"; 64 * 1024].join("+"));
let trailing_err = format!("SELECT {}+) FROM S3Object.employees", vec!["1"; 64 * 1024].join("+"));
let union_chain = vec!["SELECT 1"; 16 * 1024].join(" UNION ");
for expression in [plus_chain, trailing_err, union_chain] {
let dotted_chain = format!(
"SELECT {} FROM S3Object.employees",
vec!["a"; MAX_SELECT_FIELD_ACCESS_DEPTH + 1].join(".")
);
for expression in [plus_chain, trailing_err, union_chain, dotted_chain] {
let input = json_document_input("bucket", "input.json", &expression);
let source = std::thread::Builder::new()
.stack_size(1024 * 1024)
+14 -1
View File
@@ -14,11 +14,12 @@
use std::{
collections::VecDeque,
ops::ControlFlow,
sync::atomic::{AtomicUsize, Ordering},
};
use datafusion::sql::sqlparser::{
ast::Expr,
ast::{Expr, Statement, visit_expressions},
dialect::Dialect,
keywords::Keyword,
parser::{Parser as SqlParser, ParserError},
@@ -123,6 +124,18 @@ pub fn validate_set_operator_budget(tokens: &[Token]) -> Result<(), ParserError>
Ok(())
}
/// Rejects dotted identifiers that sqlparser builds outside its recursion budget.
pub fn validate_compound_identifier_depth(statement: &Statement) -> Result<(), ParserError> {
visit_expressions(statement, |expr| match expr {
Expr::CompoundIdentifier(parts) if parts.len() > MAX_SELECT_FIELD_ACCESS_DEPTH => {
ControlFlow::Break(ParserError::RecursionLimitExceeded)
}
_ => ControlFlow::Continue(()),
})
.break_value()
.map_or(Ok(()), Err)
}
pub trait Parser {
fn parse(&self, sql: &str) -> QueryResult<VecDeque<ExtStatement>>;
}
+17 -3
View File
@@ -18,16 +18,21 @@ use crate::{
QueryError, QueryResult, SelectInputMetrics, SelectObjectSnapshot,
object_store::{EcObjectStore, is_json_document_input, legacy_json_source_from_input},
};
#[cfg(any(test, feature = "parquet"))]
use datafusion::arrow::array::StringArray;
#[cfg(feature = "parquet")]
use datafusion::{
arrow::{
array::{Int32Array, StringArray},
array::Int32Array,
datatypes::{DataType, Field, Schema},
record_batch::RecordBatch,
},
parquet::arrow::ArrowWriter,
};
use datafusion::{
common::DataFusionError,
execution::{SessionStateBuilder, config::SessionConfig, context::SessionState, runtime_env::RuntimeEnvBuilder},
object_store::{ObjectStore, ObjectStoreExt, memory::InMemory, path::Path},
parquet::arrow::ArrowWriter,
prelude::SessionContext,
};
use parking_lot::Mutex;
@@ -519,7 +524,14 @@ impl SessionCtxFactory {
// Choose test data format based on what the request serialization specifies.
let data_bytes: Vec<u8> = if context.input.request.input_serialization.parquet.is_some() {
test_parquet_bytes()?
#[cfg(feature = "parquet")]
{
test_parquet_bytes()?
}
#[cfg(not(feature = "parquet"))]
{
return Err(crate::SelectError::InvalidDataSource.into());
}
} else if context.input.request.input_serialization.json.is_some() {
// NDJSON: one JSON object per line — usable for both LINES and DOCUMENT
// requests (DOCUMENT inputs are converted to NDJSON by EcObjectStore, but
@@ -588,6 +600,7 @@ impl SessionCtxFactory {
}
}
#[cfg(feature = "parquet")]
fn test_parquet_bytes() -> QueryResult<Vec<u8>> {
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int32, false),
@@ -618,6 +631,7 @@ fn test_parquet_bytes() -> QueryResult<Vec<u8>> {
Ok(bytes)
}
#[cfg(feature = "parquet")]
fn test_parquet_batch(
schema: Arc<Schema>,
ids: &[i32],
+4 -3
View File
@@ -29,7 +29,8 @@ documentation = "https://docs.rs/rustfs-s3select-query/latest/rustfs_s3select_qu
workspace = true
[features]
default = []
default = ["parquet"]
parquet = ["rustfs-s3select-api/parquet", "datafusion/parquet"]
hotpath = [
"hotpath/hotpath",
"hotpath/tokio",
@@ -42,11 +43,11 @@ hotpath-cpu = ["hotpath", "hotpath/hotpath-cpu", "rustfs-s3select-api/hotpath-cp
[dependencies]
hotpath.workspace = true
rustfs-s3select-api = { workspace = true }
rustfs-s3select-api = { workspace = true, default-features = false }
async-trait.workspace = true
bytes.workspace = true
csv-core.workspace = true
datafusion = { workspace = true, default-features = false, features = ["parquet", "recursive_protection", "sql"] }
datafusion = { workspace = true, default-features = false, features = ["recursive_protection", "sql"] }
derive_builder = { workspace = true }
futures = { workspace = true }
parking_lot = { workspace = true }
@@ -134,7 +134,7 @@ impl TableProvider for DelimitedSelectTable {
async fn scan(
&self,
_state: &dyn Session,
projection: Option<&Vec<usize>>,
projection: Option<&[usize]>,
filters: &[Expr],
limit: Option<usize>,
) -> DFResult<Arc<dyn ExecutionPlan>> {
@@ -146,7 +146,7 @@ impl TableProvider for DelimitedSelectTable {
));
let config = FileScanConfigBuilder::new(self.object_store_url.clone(), file_source)
.with_file(PartitionedFile::new(self.object_path.clone(), self.object_size))
.with_projection_indices(projection.cloned())?
.with_projection_indices(projection.map(ToOwned::to_owned))?
.with_limit(scan_limit)
.build();
let plan: Arc<dyn ExecutionPlan> = DataSourceExec::from_data_source(config);
@@ -97,7 +97,7 @@ impl TableProvider for JsonDocumentTable {
async fn scan(
&self,
state: &dyn Session,
projection: Option<&Vec<usize>>,
projection: Option<&[usize]>,
filters: &[Expr],
limit: Option<usize>,
) -> DFResult<Arc<dyn ExecutionPlan>> {
@@ -66,7 +66,6 @@ use crate::{
delimited_table::{DelimitedFormat, DelimitedSelectTable},
json_document_table::JsonDocumentTable,
json_lines_schema,
parquet_table::ParquetSelectTable,
},
execution::factory::QueryExecutionFactoryRef,
instance::{DEFAULT_MAX_CONCURRENT_QUERIES, DEFAULT_QUERY_TIMEOUT_SECS},
@@ -428,13 +427,26 @@ impl SimpleQueryDispatcher {
tracker: &QueryExecutionTracker,
) -> QueryResult<MetadataProvider> {
if self.input.request.input_serialization.parquet.is_some() {
let query_guard = tracker.query_guard().ok_or(QueryError::Cancel)?;
let provider = ParquetSelectTable::try_new(session.inner(), self.input.as_ref(), Some(query_guard)).await?;
let current_session_table_provider = self.build_table_handle_provider()?;
let metadata_provider =
MetadataProvider::new(provider, current_session_table_provider, self.func_manager.clone(), session.clone());
#[cfg(feature = "parquet")]
{
let query_guard = tracker.query_guard().ok_or(QueryError::Cancel)?;
let provider = crate::dispatcher::parquet_table::ParquetSelectTable::try_new(
session.inner(),
self.input.as_ref(),
Some(query_guard),
)
.await?;
let current_session_table_provider = self.build_table_handle_provider()?;
let metadata_provider =
MetadataProvider::new(provider, current_session_table_provider, self.func_manager.clone(), session.clone());
return Ok(metadata_provider);
return Ok(metadata_provider);
}
#[cfg(not(feature = "parquet"))]
{
let _ = tracker;
return Err(rustfs_s3select_api::SelectError::InvalidDataSource.into());
}
}
if is_json_document_input(&self.input) {
@@ -17,5 +17,6 @@ mod json_document_schema;
mod json_document_table;
mod json_lines_schema;
pub mod manager;
#[cfg(feature = "parquet")]
mod parquet_table;
mod schema_inference;
@@ -343,7 +343,7 @@ impl TableProvider for ParquetSelectTable {
async fn scan(
&self,
state: &dyn Session,
projection: Option<&Vec<usize>>,
projection: Option<&[usize]>,
filters: &[Expr],
limit: Option<usize>,
) -> DFResult<Arc<dyn ExecutionPlan>> {
@@ -361,7 +361,7 @@ impl TableProvider for ParquetSelectTable {
);
let config = FileScanConfigBuilder::new(self.object_store_url.clone(), file_source)
.with_file(self.partitioned_file())
.with_projection_indices(projection.cloned())?
.with_projection_indices(projection.map(ToOwned::to_owned))?
.with_limit(scan_limit)
.with_batch_size(Some(1))
.build();
+4 -2
View File
@@ -24,7 +24,7 @@ use rustfs_s3select_api::{
QueryError,
query::{
ast::ExtStatement,
parser::{Parser as RustFsParser, validate_set_operator_budget},
parser::{Parser as RustFsParser, validate_compound_identifier_depth, validate_set_operator_budget},
},
};
@@ -108,7 +108,9 @@ impl<'a> ExtParser<'a> {
/// Parse a new expression
fn parse_statement(&mut self) -> Result<ExtStatement> {
Ok(ExtStatement::SqlStatement(Box::new(self.parser.parse_statement()?)))
let statement = self.parser.parse_statement()?;
validate_compound_identifier_depth(&statement)?;
Ok(ExtStatement::SqlStatement(Box::new(statement)))
}
// Report unexpected token
+8 -3
View File
@@ -121,7 +121,7 @@ fn classify_planner_error(error: datafusion::common::DataFusionError) -> QueryEr
&error,
datafusion::common::DataFusionError::Plan(message)
if message.starts_with("Failed to coerce arguments to satisfy a call to")
|| (message.starts_with("Internal error: Function '")
|| (message.starts_with("Function '")
&& message.contains("' failed to match any signature, errors:"))
) {
return SelectError::IncorrectSqlFunctionArgumentType.into();
@@ -1018,8 +1018,13 @@ mod tests {
Err(ref err) if matches!(err.s3_select_policy_error(), Some(SelectError::UnsupportedSqlStructure { .. }))
));
// Dot chains are also bounded at parse time by sqlparser's recursion limit.
// Dot chains are bounded before planning.
let allowed_dots = vec!["a"; max_depth].join(".");
assert!(ExtParser::parse_sql(&format!("SELECT {allowed_dots} FROM S3Object")).is_ok());
let deep_dots = vec!["a"; max_depth + 1].join(".");
assert!(ExtParser::parse_sql(&format!("SELECT {deep_dots} FROM S3Object")).is_err());
assert_eq!(
ExtParser::parse_sql(&format!("SELECT {deep_dots} FROM S3Object")),
Err(datafusion::sql::sqlparser::parser::ParserError::RecursionLimitExceeded)
);
}
}
+69 -30
View File
@@ -81,7 +81,17 @@ struct CachedResponse {
/// Cache key: (lowercased bucket, normalized prefix, max entries).
type PrefixUsageCacheKey = (String, String, usize);
type PrefixUsageCacheMap = Option<HashMap<PrefixUsageCacheKey, CachedResponse>>;
enum PrefixUsageCacheEntry {
Computing(Arc<()>),
Ready(CachedResponse),
}
enum PrefixUsageLookup {
Hit(Arc<BucketPrefixUsageResponse>),
Compute(Arc<()>),
}
type PrefixUsageCacheMap = Option<HashMap<PrefixUsageCacheKey, PrefixUsageCacheEntry>>;
static PREFIX_USAGE_CACHE: Mutex<PrefixUsageCacheMap> = Mutex::new(None);
@@ -114,14 +124,15 @@ pub async fn bucket_prefix_usage(
}
let normalized_prefix = prefix.trim_matches('/').to_string();
let cache_key = (bucket.to_ascii_lowercase(), normalized_prefix.clone(), max_entries);
if let Some(response) = lookup_cached(&cache_key) {
return Ok((*response).clone());
}
let reservation = match lookup_or_reserve(&cache_key) {
PrefixUsageLookup::Hit(response) => return Ok((*response).clone()),
PrefixUsageLookup::Compute(reservation) => reservation,
};
let store = ecstore_resolve_object_store_handle()
.ok_or_else(|| ScannerError::Other("object store is not initialized".to_string()))?;
let response = Arc::new(compute_prefix_usage(store, bucket, &normalized_prefix, max_entries).await);
store_cached(cache_key, response.clone());
store_cached(&cache_key, &reservation, response.clone());
Ok((*response).clone())
}
@@ -266,40 +277,46 @@ fn aggregate_set_prefix_usage(
}
}
fn lookup_cached(key: &(String, String, usize)) -> Option<Arc<BucketPrefixUsageResponse>> {
let mut guard = PREFIX_USAGE_CACHE.lock().unwrap_or_else(|poison| poison.into_inner());
let map = guard.as_mut()?;
let cached = map.get(key)?;
if cached.computed_at.elapsed() > CACHE_TTL {
map.remove(key);
return None;
}
Some(cached.response.clone())
}
fn store_cached(key: (String, String, usize), response: Arc<BucketPrefixUsageResponse>) {
fn lookup_or_reserve(key: &PrefixUsageCacheKey) -> PrefixUsageLookup {
let mut guard = PREFIX_USAGE_CACHE.lock().unwrap_or_else(|poison| poison.into_inner());
let map = guard.get_or_insert_with(HashMap::new);
// Bound the cache: drop expired entries first, and if the cap is still
// exceeded clear wholesale — the next queries recompute in milliseconds.
match map.get(key) {
Some(PrefixUsageCacheEntry::Ready(cached)) if cached.computed_at.elapsed() <= CACHE_TTL => {
return PrefixUsageLookup::Hit(cached.response.clone());
}
Some(PrefixUsageCacheEntry::Computing(reservation)) => return PrefixUsageLookup::Compute(reservation.clone()),
_ => {}
}
if map.len() >= CACHE_MAX_ENTRIES {
map.retain(|_, cached| cached.computed_at.elapsed() <= CACHE_TTL);
map.retain(|_, entry| !matches!(entry, PrefixUsageCacheEntry::Ready(cached) if cached.computed_at.elapsed() > CACHE_TTL));
if map.len() >= CACHE_MAX_ENTRIES {
map.clear();
}
}
map.insert(
key,
CachedResponse {
let reservation = Arc::new(());
map.insert(key.clone(), PrefixUsageCacheEntry::Computing(reservation.clone()));
PrefixUsageLookup::Compute(reservation)
}
fn store_cached(key: &PrefixUsageCacheKey, reservation: &Arc<()>, response: Arc<BucketPrefixUsageResponse>) {
let mut guard = PREFIX_USAGE_CACHE.lock().unwrap_or_else(|poison| poison.into_inner());
if let Some(entry) = guard.as_mut().and_then(|map| map.get_mut(key))
&& matches!(entry, PrefixUsageCacheEntry::Computing(owner) if Arc::ptr_eq(owner, reservation))
{
// Invalidation or eviction retires the reservation with its entry.
*entry = PrefixUsageCacheEntry::Ready(CachedResponse {
computed_at: std::time::Instant::now(),
response,
},
);
});
}
}
#[cfg(test)]
mod tests {
use super::{CACHE_MAX_ENTRIES, PREFIX_USAGE_CACHE, invalidate_prefix_usage_cache, store_cached};
use super::{
CACHE_MAX_ENTRIES, PREFIX_USAGE_CACHE, PrefixUsageLookup, invalidate_prefix_usage_cache, lookup_or_reserve, store_cached,
};
use rustfs_data_usage::PrefixUsageSummary;
fn response(bucket: &str) -> super::BucketPrefixUsageResponse {
@@ -318,10 +335,10 @@ mod tests {
}
fn seed(bucket: &str, prefix: &str) {
store_cached(
(bucket.to_ascii_lowercase(), prefix.to_string(), 10),
std::sync::Arc::new(response(bucket)),
);
let key = (bucket.to_ascii_lowercase(), prefix.to_string(), 10);
if let PrefixUsageLookup::Compute(reservation) = lookup_or_reserve(&key) {
store_cached(&key, &reservation, std::sync::Arc::new(response(bucket)));
}
}
fn contains(bucket: &str, prefix: &str) -> bool {
@@ -349,6 +366,28 @@ mod tests {
invalidate_prefix_usage_cache("");
assert!(!contains("beta", "y"));
// A query on the previous generation may finish after its replacement.
let key = ("alpha".to_owned(), "x".to_owned(), 10);
for invalidate in ["alpha", ""] {
let PrefixUsageLookup::Compute(old) = lookup_or_reserve(&key) else {
panic!("expected cold lookup")
};
invalidate_prefix_usage_cache(invalidate);
let PrefixUsageLookup::Compute(new) = lookup_or_reserve(&key) else {
panic!("expected replacement")
};
// A late old result must not claim the replacement's still-computing slot.
store_cached(&key, &old, std::sync::Arc::new(response("alpha")));
let expected = std::sync::Arc::new(response("alpha"));
store_cached(&key, &new, expected.clone());
store_cached(&key, &old, std::sync::Arc::new(response("alpha")));
let PrefixUsageLookup::Hit(actual) = lookup_or_reserve(&key) else {
panic!("expected cached result")
};
assert!(std::sync::Arc::ptr_eq(&actual, &expected));
invalidate_prefix_usage_cache("alpha");
}
// Hard cap: overflow clears rather than grows.
for index in 0..=(CACHE_MAX_ENTRIES / 2) {
let bucket = format!("cap-bucket-{index}");
@@ -915,6 +915,8 @@ async fn remote_disk_belongs_to_set(disk: &Disk, set: &crate::SetDisks) -> bool
if Arc::ptr_eq(&requested.get_disk(), &local.get_disk()))
}),
Disk::Remote(_) => false,
#[allow(unreachable_patterns)]
_ => false,
}
}
+48 -8
View File
@@ -1134,10 +1134,26 @@ pub async fn init_scanner_with_recovery(
"Scanner recovery intent startup discovery failed"
);
}
return Some(init_data_scanner_task_with_storage(ctx, storeapi, runtime_guard).await);
let dynamic_store = storeapi.dynamic_handle();
drop(storeapi);
return Some(
init_data_scanner_task_with_store_provider(
ctx,
move || {
let current = dynamic_store.current();
let generation = current.topology_generation();
(current, generation)
},
runtime_guard,
)
.await,
);
}
let dynamic_store = storeapi.dynamic_handle();
drop(storeapi);
Some(tokio::spawn(async move {
if let Err(error) = run_scanner_usage_recovery_intents_for_startup(ctx.clone(), storeapi.clone()).await {
let initial_store = dynamic_store.current();
if let Err(error) = run_scanner_usage_recovery_intents_for_startup(ctx.clone(), initial_store).await {
warn!(
target: "rustfs::scanner",
event = EVENT_SCANNER_PERSIST_STATE,
@@ -1148,7 +1164,9 @@ pub async fn init_scanner_with_recovery(
"Scanner recovery intent startup discovery failed"
);
}
if let Err(error) = resume_scanner_cycle_cleanup(ctx, storeapi).await {
let cleanup_store = dynamic_store.current();
drop(dynamic_store);
if let Err(error) = resume_scanner_cycle_cleanup(ctx, cleanup_store).await {
warn!(
target: "rustfs::scanner",
event = EVENT_SCANNER_PERSIST_STATE,
@@ -1173,13 +1191,26 @@ where
async fn init_data_scanner_task_with_storage<S>(
ctx: CancellationToken,
storeapi: Arc<S>,
mut runtime_guard: ScannerRuntimeGuard,
runtime_guard: ScannerRuntimeGuard,
) -> tokio::task::JoinHandle<()>
where
S: ScannerStorage,
{
init_data_scanner_task_with_store_provider(ctx, move || (storeapi.clone(), 0), runtime_guard).await
}
async fn init_data_scanner_task_with_store_provider<S, F>(
ctx: CancellationToken,
store_provider: F,
mut runtime_guard: ScannerRuntimeGuard,
) -> tokio::task::JoinHandle<()>
where
S: ScannerStorage,
F: Fn() -> (Arc<S>, u64) + Send + Sync + 'static,
{
let startup = runtime_guard.startup_token();
let (startup_features, startup_maintenance_generation) = configure_scanner_defaults(&ctx, &storeapi).await;
let (startup_store, mut last_topology_generation) = store_provider();
let (startup_features, startup_maintenance_generation) = configure_scanner_defaults(&ctx, &startup_store).await;
// Force init global sleeper so config is read once at startup.
let _ = &*SCANNER_SLEEPER;
if let Err(err) = refresh_scanner_runtime_config_from_global() {
@@ -1196,14 +1227,18 @@ where
runtime_guard.mark_initialized();
let replication_active = startup_features.replication;
drop(startup_store);
let ctx_clone = ctx;
let storeapi_clone = storeapi;
tokio::spawn(async move {
let _runtime_guard = runtime_guard;
let initial_usage_state = {
let (startup_probe_store, _) = store_provider();
async move { initial_scanner_startup_usage_state(&startup_probe_store, replication_active).await }
};
if !wait_for_scanner_startup(
startup,
&ctx_clone,
initial_scanner_startup_usage_state(&storeapi_clone, replication_active),
initial_usage_state,
replication_active,
startup_maintenance_generation.unwrap_or_else(scanner_maintenance_generation),
randomized_cycle_delay_for,
@@ -1222,11 +1257,16 @@ where
break;
}
let (cycle_store, topology_generation) = store_provider();
if topology_generation != last_topology_generation {
last_topology_generation = topology_generation;
service_continuation = None;
}
let runtime_generation = scanner_runtime_config_generation();
let maintenance_generation = scanner_maintenance_generation();
let run_result = run_data_scanner_with_maintenance_state(
ctx_clone.clone(),
storeapi_clone.clone(),
cycle_store,
startup_features,
startup_maintenance_generation,
startup,
+3 -2
View File
@@ -28,7 +28,8 @@ categories = ["cryptography"]
workspace = true
[features]
default = []
default = ["vault"]
vault = ["rustfs-kms/vault"]
# MinIO-compatible sealed object keys (DARE). Mirrors the `m-compatible` feature of
# the server binary, which enables both together.
m-compatible = ["dep:chacha20poly1305", "dep:hex-simd", "dep:hmac", "dep:sha2"]
@@ -41,7 +42,7 @@ test-util = []
# the storage engine and must not depend on either: what it needs from the
# running server arrives through `SseHost`.
rustfs-config = { workspace = true }
rustfs-kms = { workspace = true }
rustfs-kms = { workspace = true, default-features = false }
rustfs-policy = { workspace = true }
rustfs-s3-types = { workspace = true }
rustfs-utils = { workspace = true, features = ["http", "path"] }
+1 -1
View File
@@ -96,7 +96,7 @@ pub fn init() -> StartupReport {
///
/// Frozen on first read, by [`init`] or by the first request, so one process
/// never answers the same question two ways.
pub(crate) fn key_policy_enforced() -> bool {
pub fn key_policy_enforced() -> bool {
static ENFORCED: LazyLock<bool> =
LazyLock::new(|| get_env_bool(ENV_RUSTFS_KMS_ENFORCE_SSE_KEY_POLICY, DEFAULT_KMS_ENFORCE_SSE_KEY_POLICY));
*ENFORCED
@@ -20,7 +20,9 @@ use futures::StreamExt;
use rustfs_zip::CompressionFormat;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use tar_codec::{Archive as _, DecodePolicy, Member, MemberPayload as _, PaxDecodePolicy, PaxVendorExtensionPolicy, TarArchive};
use tar_codec::{
Archive as _, DecodeError, DecodePolicy, Member, MemberPayload as _, PaxDecodePolicy, PaxVendorExtensionPolicy, TarArchive,
};
use tar_framing::{
FrameError, FrameErrorInner, PaxKeyword, PaxRecord, PaxValue, StreamPolicy, UstarKind,
logical::{MemberExtensions, PaxState, TarReader},
@@ -226,7 +228,7 @@ async fn parse_with_tar_framing(bytes: &[u8]) -> (Vec<ParsedMember>, Option<Fram
frame
.effective_path()
.expect("tar-framing should resolve the fixture path")
.into_owned(),
.to_vec(),
)
.expect("fixture paths should be UTF-8");
let size = frame.header.effective_size;
@@ -399,13 +401,7 @@ async fn tar_codec_policy_accepts_only_the_explicit_minio_vendor_namespace() {
bodies.push(body);
}
assert_eq!(bodies, [b"alpha-body".to_vec(), b"bravo-body".to_vec()]);
assert!(
members
.next()
.await
.expect("the member cursor should be fused after an error")
.is_none()
);
assert!(matches!(members.next().await, Err(DecodeError::Poisoned)));
}
fn pax_record(key: &str, value: &str) -> Vec<u8> {
+3 -3
View File
@@ -9,7 +9,7 @@ repository.workspace = true
description = "RustFS internal adapter for zstd 0.13 consumers using the fixed codec"
[dependencies]
zstd_fixed = { package = "zstd", version = "=0.14.4", default-features = false }
zstd_fixed = { package = "zstd", version = "=0.14.5", default-features = false }
[features]
default = ["legacy", "arrays", "zdict_builder"]
@@ -31,8 +31,8 @@ zstdmt = ["zstd_fixed/zstdmt"]
[dev-dependencies]
# Enables zstd-safe's `seekable` feature for tests/security.rs. The test imports
# `zstd_safe::seekable` directly so cargo-shear treats this as a used dependency.
zstd-safe = { version = "8.3.0", features = ["seekable"] }
toml = "1.2.2"
zstd-safe = { version = "8.4.0", features = ["seekable"] }
toml = "1.2.3"
semver = "1.0.28"
apache-avro.workspace = true
arrow-array = "60.2.0"
+1 -1
View File
@@ -2,7 +2,7 @@
**Use this when:** maintaining the dependency bridge for consumers that still require zstd 0.13.
This private package satisfies the version constraints of Avro, Arrow IPC, Parquet, and Kafka. Its version is a resolver compatibility identifier. Its entire library is a re-export of the exact registry `zstd 0.14.4` implementation, including that implementation's `zstd-safe` types. The original zstd 0.13 implementation and zstd-safe 7.x are removed from the resolved graph. Every old feature and the default feature set is forwarded.
This private package satisfies the version constraints of Avro, Arrow IPC, Parquet, and Kafka. Its version is a resolver compatibility identifier. Its entire library is a re-export of the exact registry `zstd 0.14.5` implementation, including that implementation's `zstd-safe` types. The original zstd 0.13 implementation and zstd-safe 7.x are removed from the resolved graph. Every old feature and the default feature set is forwarded.
The fixed implementation closes RUSTSEC-2026-0391, RUSTSEC-2026-0398, and RUSTSEC-2026-0403. A successful advisory scan alone is insufficient evidence: cargo-deny skips local path packages. The dependency-graph test therefore requires this adapter's sole runtime dependency to be the exact fixed registry implementation and rejects vulnerable registry codec versions. Security tests exercise abandoned stream contexts, malformed legacy frames, and seekable offsets past EOF. Consumer tests retain zstandard support in all four upstream formats.
+1 -1
View File
@@ -59,7 +59,7 @@ fn legacy_constraints_resolve_only_to_the_fixed_registry_implementation() {
adapters += 1;
assert_eq!(version, Version::new(0, 13, 4));
let runtime = package["dependencies"].as_array().expect("adapter dependency edges");
assert!(runtime.iter().any(|value| value.as_str() == Some("zstd 0.14.4")));
assert!(runtime.iter().any(|value| value.as_str() == Some("zstd 0.14.5")));
} else {
let source = package["source"].as_str().expect("registry codec source");
assert!(source.starts_with("registry+"), "codec implementation must remain a registry package");
+4 -1
View File
@@ -8,7 +8,8 @@ Wants=network-online.target
# Requires=postgresql.service
[Service]
Type=notify
Type=notify-reload
ReloadSignal=SIGHUP
NotifyAccess=main
User=rustfs
Group=rustfs
@@ -21,6 +22,8 @@ WorkingDirectory=/opt/rustfs
# from RUSTFS_* variables. See `../config/rustfs.env` for an example template.
EnvironmentFile=/etc/default/rustfs
ExecStart=/usr/bin/rustfs server
# Reload is synchronous via Type=notify-reload + ReloadSignal=SIGHUP (RELOADING=1 / MONOTONIC_USEC / READY=1).
TimeoutReloadSec=120s
# service log configuration
LogsDirectory=rustfs

Some files were not shown because too many files have changed in this diff Show More