Compare commits

..

8 Commits

Author SHA1 Message Date
loverustfs f59daa1500 ci: require execution evidence for production ECStore recovery tests 2026-12-02 20:00:31 +08:00
loverustfs f956f54ceb test(ecstore): verify durable overwrite and multipart replay on simulated disks
Require the armed crash paths to fire and preserve the generation acknowledged to the caller. Store per-drive publication evidence so completion retries after power loss can verify the original upload and reject absent or misplaced witnesses.
2026-12-02 20:00:31 +08:00
loverustfs ffe40451c1 fix(kms): skip Transit directories when listing keys
Keep the BYOK wrapping-key directory out of key pagination so the deletion sweep can continue. Refs rustfs/rustfs#9846.
2026-12-02 19:34:25 +08:00
Rasmus Haslund 615e55825e fix(s3): echo multipart checksums in ListParts (#9814)
Carry the upload's checksum algorithm and type and each part's recorded checksums through PartInfo and render them in the ListParts response.
2026-12-02 16:08:17 +08:00
Hauser Zhi 2537596a4f chore(deps): refresh Cargo dependencies (#9842)
* chore(deps): refresh Cargo dependencies

Update TAR and Windows bindings, preserve Windows file disposition flags, and retain the recorder version shared with Kafka and Gateway RDMA. Refresh the standalone fuzz dependency graph.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* chore(deps): upgrade metrics to 0.25

Route metrics 0.24 consumers through the 0.25 implementation in both workspaces. Verify that legacy metrics share the recorder and that dependency resolution cannot silently restore a second recorder.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* chore(deps): update RustFS Kafka to 1.5.0

Resolve both Kafka packages at 1.5.0 and drop the unused metrics facade patch from the fuzz workspace. Keep the main workspace facade for the remaining Metrique dependency.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(metrics): disambiguate the doctest extern names

Alias the 0.25 implementation so rustdoc can link it alongside the 0.24 compatibility facade. Preserve the shared recorder and dependency lockfile.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* chore(deps): update http to 1.6.0

Align the workspace and standalone fuzz manifests and lockfiles on http 1.6.0.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(deps): refresh Cargo dependencies and preserve HTTP values

Refresh registry constraints and lockfiles. Preserve legacy opaque ETags and response headers with byte validation while retaining POST and signed override validation.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:38 +08:00
Hauser Zhi 6b014ec215 feat(capacity): read usage directly on dedicated mounts (#9840)
* feat(capacity): read usage directly on dedicated mounts

Allow operators of dedicated filesystems to use block usage for background
capacity estimates. Reuse the existing blocking scan and cache update
paths so a successful probe establishes the per-disk baseline.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* refactor(capacity): verify whole mounts before reading usage

Share mount eligibility across a refresh and read allocated blocks
through the checked directory descriptor. Rebuild a complete per-disk
baseline when the local disk set changes.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(capacity): discard stale topology on bounded refresh

Reconcile a scheduled full refresh against the topology it scanned.
Represent baseline completeness with the per-disk map and compute
aggregate totals in one pass.

Refs: rustfs/rustfs#9837
Refs: rustfs/backlog#3399

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

* fix(capacity): restrict direct reads to isolated filesystem types

Use the filesystem type from the existing descriptor-based statfs
call to keep shared-pool accounting out of the direct mount path.
Cover directory fallback and symlinked mount roots.

Refs: rustfs/rustfs#9837

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>

---------

Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:30 +08:00
Hauser Zhi a368c669a2 feat(bench): record write latency in preflight queue samples (#9850)
Co-authored-by: heihutu <heihutu@gmail.com>
Co-authored-by: zhi22915 <qiuzgang@gmail.com>
Co-authored-by: qunjiazhu <qunjiazhu@gmail.com>
2026-12-02 16:06:24 +08:00
hector e0b548fff0 fix(docker): switch docker-compose-simple.yml to single-disk mode and /health/ready (#9848)
* fix(docker): switch docker-compose-simple.yml to single-disk mode and /health/ready

- Use single-node single-disk layout (RUSTFS_VOLUMES=/data with a single rustfs_data volume) so docker compose up works out of the box without triggering same-device strict disk topology errors
- Switch healthcheck to /health/ready on port 9000 with --connect-timeout 3 --max-time 5 (decoupled from console toggle)
- Pin volume-permission-helper to alpine:3.24 with network_mode: none and skip redundant recursive chown -R when ownership is already 10001:10001
- Allow overriding S3/Console host ports and credentials via env vars, and configure ulimits.nofile=65535

Signed-off-by: xiaomage <jhma@rustfs.com>

* fix(docker): align RUSTFS_OBS_LOG_DIRECTORY to /logs in docker-compose-simple.yml

Signed-off-by: xiaomage <jhma@rustfs.com>

---------

Signed-off-by: xiaomage <jhma@rustfs.com>
2026-12-02 11:21:56 +08:00
92 changed files with 2320 additions and 3136 deletions
+13
View File
@@ -382,6 +382,19 @@ jobs:
} > artifacts/workspace/doctest-diagnostics.txt
exit "${status}"
- name: Verify production ECStore crash and recovery
if: needs.classify-changes.outputs.mode == 'full'
env:
CARGO_BUILD_JOBS: "2"
run: |
dst=(--locked -p rustfs-ecstore --features dst --test dst_production_ecstore --profile ci)
mkdir -p artifacts/workspace/dst
cargo nextest list "${dst[@]}" --message-format json > artifacts/workspace/dst/selection.json
rm -f target/nextest/ci/junit.xml
trap 'if [[ -f target/nextest/ci/junit.xml ]]; then cp target/nextest/ci/junit.xml artifacts/workspace/dst/junit.xml; fi' EXIT
cargo nextest run "${dst[@]}" --no-tests fail --retries 0
python3 scripts/ci_test_artifact.py evidence --dst artifacts/workspace/dst/selection.json target/nextest/ci/junit.xml
- name: Upload test reports and diagnostics
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
Generated
+415 -222
View File
File diff suppressed because it is too large Load Diff
+17 -15
View File
@@ -40,6 +40,7 @@ members = [
"crates/lock", # Distributed locking implementation
"crates/log-analyzer", # Offline log fault-analysis core (rustfs diagnose)
"crates/madmin", # Management dashboard and admin API interface
"crates/metrics-compat", # Shared recorder for dependencies requiring metrics 0.24
"crates/notify", # Notification system for events
"crates/obs", # Observability utilities
"crates/object-capacity", # Capacity scan and refresh core
@@ -192,13 +193,13 @@ hyper = { version = "=1.12.0" } # Keep the HTTP/2 Expect backport below active.
h2 = { version = "0.4.21" }
hyper-rustls = { default-features = false, version = "0.27.10" }
hyper-util = { version = "0.1.21" }
http = "1.5.0"
http = "1.6.0"
http-body = "1.1.0"
http-body-util = "0.1.5"
memchr = "2.8.3"
minlz = "1.2.3"
reqwest = "0.13.5"
rustfs-kafka-async = { version = "1.4.1" }
rustfs-kafka-async = { version = "1.5.0" }
slab = { version = "0.4.12" }
socket2 = { version = "0.6.5" }
tokio = { version = "1.54.1" }
@@ -224,7 +225,7 @@ apache-avro = { version = "0.23.0", features = ["snappy", "zstandard"] }
bytes = { version = "1.12.2" }
csv-core = "0.1.13"
bytesize = "2.7.0"
byteorder = "1.5.0"
byteorder = "1.5.1"
flatbuffers = "25.12.19"
form_urlencoded = "1.2.3"
prost = "0.14.6"
@@ -269,7 +270,7 @@ proptest = "1"
# Time and Date
chrono = { version = "0.4.45" }
humantime = "2.4.0"
jiff = { version = "1.0.3" }
jiff = { version = "1.1.0" }
time = { version = "0.3.55" }
# Database
@@ -282,15 +283,15 @@ anyhow = "1.0.105"
arc-swap = "1.9.5"
rustfs-tokio-tar = { version = "0.7.1" }
# Candidate Snowball parser versions exercised by rustfs-zip compatibility fixtures.
tar-codec = "0.0.17"
tar-framing = "0.0.17"
tar-codec = "0.0.18"
tar-framing = "0.0.18"
atoi = "3.1.1"
atomic_enum = "0.3.0"
aws-config = { version = "1.13.4" }
aws-credential-types = { version = "1.3.1" }
aws-sdk-kms = { default-features = false, version = "1.134.0" }
aws-sdk-s3 = { default-features = false, version = "1.163.0" }
aws-sdk-sts = { default-features = false, version = "1.129.0" }
aws-sdk-sts = { default-features = false, version = "1.130.0" }
aws-sdk-s3vectors = { default-features = false, version = "=1.52.0" }
aws-smithy-async = { version = "1.3.1" }
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
@@ -357,7 +358,7 @@ percent-encoding = "2.3.2"
# Server-side QR rendering for TOTP enrollment, so neither the console nor the
# CLI needs its own QR encoder. No default features: the image/render backends
# pull in an image stack this only needs SVG and text output from.
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
qrcode-rs = { version = "2.2.1", default-features = false, features = ["std", "svg"] }
pin-project-lite = "0.2.18"
pretty_assertions = "1.4.1"
rand = { version = "0.10.4" }
@@ -378,7 +379,7 @@ siphasher = "1.0.4"
smallvec = { version = "1.16.6" }
compact_str = "0.10.0"
snap = "1.1.2"
starshard = { version = "2.4.1" }
starshard = { version = "2.4.2" }
strum = { version = "0.28.0" }
sync_wrapper = "1.0.2"
sysinfo = "0.40.5"
@@ -400,15 +401,15 @@ vaultrs = { version = "0.8.0" }
tar = "0.4.46"
walkdir = "2.5.1"
winapi-util = "0.1.11"
windows = { version = "0.62.2" }
windows-sys = "0.61.2"
windows = { version = "0.101.0" }
windows-sys = "0.101.0"
xxhash-rust = { version = "0.8.21" }
zip = "9.9.0"
zstd = "0.14.5"
# Observability and Metrics
metrics = "0.24.6"
metrics-util = "0.20"
metrics = "0.25.1"
metrics-util = "0.21"
dial9 = { version = "0.5.9", default-features = false }
opentelemetry = { version = "0.33.1" }
opentelemetry-appender-tracing = { version = "0.33.1" }
@@ -416,7 +417,7 @@ opentelemetry-otlp = { version = "0.33.1" }
opentelemetry-proto = { version = "0.33.1", default-features = false, features = ["metrics", "gen-tonic-messages"] }
opentelemetry_sdk = { version = "0.33.1" }
opentelemetry-semantic-conventions = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.1" }
opentelemetry-stdout = { version = "0.33.2" }
pyroscope = { version = "2.1.5" }
# FTP and SFTP
@@ -431,7 +432,7 @@ russh-sftp = "4.0.0"
dav-server = "0.12.0"
# Performance Analysis and Memory Profiling
rustfs-mimalloc = { version = "0.7.5" }
rustfs-mimalloc = { version = "0.7.6" }
# Hotpath 0.33 infers type-qualified names for methods without explicit labels or impl_type.
hotpath = { version = "=0.33.1", default-features = false }
# Snapshot testing for output format regression detection
@@ -483,6 +484,7 @@ strip = "none"
# Pin upstream fixes until compatible crates.io releases are available.
[patch.crates-io]
metrics = { path = "crates/metrics-compat" }
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
hyper = { path = "vendor/hyper" }
lance-bitpacking = { git = "https://github.com/GatewayJ/lance", rev = "35a95d99a1f413d9cad0427837ee6939974a1570" }
+6
View File
@@ -45,6 +45,9 @@ pub const ENV_CAPACITY_METRICS_INTERVAL: &str = "RUSTFS_CAPACITY_METRICS_INTERVA
/// Environment variable for following symbolic links during capacity calculation
pub const ENV_CAPACITY_FOLLOW_SYMLINKS: &str = "RUSTFS_CAPACITY_FOLLOW_SYMLINKS";
/// Use filesystem-reported used space on dedicated drive mounts.
pub const ENV_CAPACITY_USE_MOUNT_USAGE: &str = "RUSTFS_CAPACITY_USE_MOUNT_USAGE";
/// Environment variable for enabling dynamic timeout calculation
pub const ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: &str = "RUSTFS_CAPACITY_ENABLE_DYNAMIC_TIMEOUT";
@@ -94,6 +97,9 @@ pub const DEFAULT_CAPACITY_METRICS_INTERVAL_SECS: u64 = 600;
/// Default: false (disabled for safety)
pub const DEFAULT_CAPACITY_FOLLOW_SYMLINKS: bool = false;
/// Use directory scans by default to preserve logical file-size accounting.
pub const DEFAULT_CAPACITY_USE_MOUNT_USAGE: bool = false;
/// Enable dynamic timeout calculation based on directory characteristics
/// Default: true (enabled)
pub const DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT: bool = true;
-2
View File
@@ -871,8 +871,6 @@ pub struct SizeSummary {
/// remove versions that resolved without allocating one key per healthy
/// version on the hot path.
pub reconciliation_scopes: Vec<SizeReconciliationScope>,
/// True when lifecycle evaluation queued deletion for every remaining version of the object.
pub all_versions_queued_for_delete: bool,
}
/// Replication target size summary
@@ -65,7 +65,6 @@ impl GrpcLockClient {
suppress_contention_logs: false,
refresh_interval: None,
cache_fence_stamp_requested: false,
owner_incarnation: None,
}
}
+1 -1
View File
@@ -328,7 +328,7 @@ pub mod bucket {
assign_site_replication_rule_priorities, commit_force_delete_intent, complete_force_delete_intent,
delete_replication_state_from_config, delete_replication_version_id, get_global_replication_pool,
get_global_replication_stats, get_proxy_targets, init_background_replication,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule, legacy_role_target_arn,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule,
merge_incoming_replication_config, merge_user_replication_config, persist_force_delete_intent,
read_durable_mrf_backlog, replication_state_to_filemeta, replication_status_to_filemeta, replication_statuses_map,
replication_target_arn_deployment_id, replication_target_arns, resync_start_conflict_id,
+1 -22
View File
@@ -939,7 +939,7 @@ impl BucketTargetSys {
found = true;
break;
}
if existing_target.endpoint == target.endpoint && existing_target.target_bucket == target.target_bucket {
if existing_target.endpoint == target.endpoint {
return Err(BucketTargetError::BucketRemoteAlreadyExists {
bucket: existing_target.target_bucket.clone(),
});
@@ -5591,25 +5591,4 @@ mod tests {
assert_eq!(base.targets.len(), 1);
assert_eq!(base.targets[0].arn, existing.arn);
}
#[test]
fn upsert_target_entry_allows_distinct_target_buckets_on_same_endpoint() {
let bucket = "bkt-bucket-repl";
let mut site_target = repair_target(bucket, "site-repl");
site_target.target_bucket = bucket.to_string();
let mut bucket_repl_target = repair_target(bucket, "bucket-repl");
bucket_repl_target.target_bucket = "bkt-bucket-repl-replica".to_string();
let mut targets = vec![site_target];
BucketTargetSys::upsert_target_entry(&mut targets, &bucket_repl_target, false)
.expect("distinct target bucket on same endpoint should succeed");
assert_eq!(targets.len(), 2);
let mut duplicate_bucket_target = repair_target(bucket, "dup-arn");
duplicate_bucket_target.target_bucket = "bkt-bucket-repl-replica".to_string();
let err = BucketTargetSys::upsert_target_entry(&mut targets, &duplicate_bucket_target, false)
.expect_err("duplicate endpoint + target_bucket should be rejected");
assert!(matches!(err, BucketTargetError::BucketRemoteAlreadyExists { .. }));
}
}
@@ -1378,11 +1378,6 @@ impl ExpiryState {
.await
};
if deleted {
runtime_sources::notify_scanner_dirty_usage_mutation(
&v.obj_info.bucket,
&v.obj_info.name,
runtime_sources::ScannerDirtyUsageMutationSource::TierExpiration,
);
trace.emit(EVENT_LIFECYCLE_DELETE_COMPLETED, "delete_completed", None);
} else {
record_scanner_lifecycle_expiry_delete_failed(&v.src, 1);
@@ -1406,15 +1401,6 @@ impl ExpiryState {
v.bucket_incarnation_id,
)
.await;
if v.versions.len() > failed {
for ver in &v.versions {
runtime_sources::notify_scanner_dirty_usage_mutation(
&v.bucket,
&ver.object_name,
runtime_sources::ScannerDirtyUsageMutationSource::TierExpiration,
);
}
}
if failed == 0 {
trace.emit(EVENT_LIFECYCLE_DELETE_COMPLETED, "delete_completed", None);
} else {
@@ -2261,11 +2247,6 @@ impl TransitionState {
ts.num_objects = 1;
}
transition_state.add_lastday_stats(&task.event.storage_class, ts);
runtime_sources::notify_scanner_dirty_usage_mutation(
&task.obj_info.bucket,
&task.obj_info.name,
runtime_sources::ScannerDirtyUsageMutationSource::TierExpiration,
);
emit_transition_complete_event(obj_info_for_event, incarnation_id);
}
+1 -1
View File
@@ -48,7 +48,7 @@ pub use replication_config_boundary::{
REMOTE_TARGET_UNSUPPORTED_FIELDS, REMOTE_TARGET_WRITABLE_FIELDS, REPLICATION_CAPABILITY_CONTRACT_VERSION,
REPLICATION_READ_ONLY_HISTORICAL_FIELDS, REPLICATION_WRITABLE_FIELDS, ReplicationConfigStructureError,
ReplicationConfigurationExt, ReplicationTargetValidationError, assign_site_replication_rule_priorities,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule, legacy_role_target_arn,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule,
merge_incoming_replication_config, merge_user_replication_config, replication_target_arn_deployment_id,
replication_target_arns, should_remove_replication_target, site_replication_rule_deployment_id,
unsupported_replication_config_field, validate_replication_config_structure, validate_replication_config_target_arns,
@@ -18,7 +18,7 @@ pub use rustfs_replication::{
REMOTE_TARGET_UNSUPPORTED_FIELDS, REMOTE_TARGET_WRITABLE_FIELDS, REPLICATION_CAPABILITY_CONTRACT_VERSION,
REPLICATION_READ_ONLY_HISTORICAL_FIELDS, REPLICATION_WRITABLE_FIELDS, ReplicationConfigStructureError,
ReplicationConfigurationExt, ReplicationRuleExt, ReplicationTargetValidationError, assign_site_replication_rule_priorities,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule, legacy_role_target_arn,
invalid_replication_config_status_field, is_site_replication_role, is_site_replication_rule,
merge_incoming_replication_config, merge_user_replication_config, replication_target_arn_deployment_id,
replication_target_arns, should_remove_replication_target, site_replication_rule_deployment_id,
unsupported_replication_config_field, validate_replication_config_structure, validate_replication_config_target_arns,
@@ -25,7 +25,6 @@ use tracing::error;
use super::replication_config_boundary::{
ObjectOpts, ReplicationConfigurationExt as _, ReplicationRuleExt as _, invalid_replication_config_status_field,
legacy_role_target_arn,
};
use super::replication_error_boundary::Result;
use super::replication_filemeta_boundary::{
@@ -144,7 +143,7 @@ fn validate_delete_replication_config(
)));
}
let role = legacy_role_target_arn(&config.role).unwrap_or_default();
let role = config.role.trim();
let mut role_destination = None;
for rule in &config.rules {
if rule.status.as_str() == Status::ENABLED.as_str() {
@@ -1102,29 +1101,4 @@ mod tests {
let stored_marker = config.resync(marker, ReplicateDecision::default(), &HashMap::new()).await;
assert!(!stored_marker.targets.contains_key(arn));
}
#[test]
fn validate_delete_replication_config_accepts_iam_role_with_multiple_destinations() {
let mut bucket_rule = replication_rule();
bucket_rule.destination.bucket = "arn:minio:replication:us-east-1:peer-b:bkt-replica".to_string();
let mut site_rule = replication_rule();
site_rule.id = Some("rustfs-site-replication:peer-b".to_string());
site_rule.priority = Some(2);
site_rule.destination.bucket = "arn:minio:replication:us-east-1:peer-b:bkt-source".to_string();
let config = PersistedReplicationConfiguration {
role: "arn:aws:iam::123456789012:role/rustfs-replication".to_string(),
rules: vec![bucket_rule, site_rule],
};
let versioning = VersioningConfiguration {
status: Some("Enabled".to_string()),
..Default::default()
};
assert!(
validate_delete_replication_config(&versioning, Some(&config)).is_ok(),
"AWS IAM role ARN must not be treated as a legacy single-target destination ARN"
);
}
}
@@ -1677,27 +1677,12 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
/// Queues a replica delete task
pub async fn queue_replica_delete_task(&self, doi: DeletedObjectReplicationInfo) -> ReplicationQueueAdmission {
if !self.in_flight.try_begin_delete(&doi) {
debug!(
event = EVENT_REPLICATION_IN_FLIGHT_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION,
bucket = %doi.bucket,
object = %doi.delete_object.object_name,
version_id = ?doi.delete_object.version_id,
delete_marker_version_id = ?doi.delete_object.delete_marker_version_id,
op_type = ?doi.op_type,
"Replication delete task already in flight; not queued again"
);
return ReplicationQueueAdmission::Skipped;
}
let target_arns = doi.admitted_target_arns();
let ch = self
.worker_queue_channel(&doi.op_type, &doi.bucket, &doi.delete_object.object_name, 0)
.await;
let Some(channel) = ch else {
self.in_flight.finish_delete(&doi);
return ReplicationQueueAdmission::Missed;
};
@@ -1709,7 +1694,6 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
self.stats.dec_q(&doi.bucket, 0, true, doi.op_type);
self.stats.dec_target_q(&doi.bucket, &target_arns, 0);
self.in_flight.finish_delete(&doi);
let admission = self.queue_mrf_save_admission(doi.to_mrf_entry(), "delete").await;
self.apply_queue_backpressure("delete", false, "Replication delete queue is backpressured")
@@ -2433,28 +2417,16 @@ pub(crate) struct ReplicationInFlight {
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum ReplicationInFlightKey {
Object {
bucket: String,
object: String,
version_id: Option<uuid::Uuid>,
generation: ReplicationGenerationSnapshot,
},
Delete {
bucket: String,
object: String,
version_id: Option<uuid::Uuid>,
delete_marker_version_id: Option<uuid::Uuid>,
delete_marker: bool,
force_delete: bool,
force_delete_id: Option<uuid::Uuid>,
target_arns: Vec<String>,
},
struct ReplicationInFlightKey {
bucket: String,
object: String,
version_id: Option<uuid::Uuid>,
generation: ReplicationGenerationSnapshot,
}
impl From<&ReplicateObjectInfo> for ReplicationInFlightKey {
fn from(info: &ReplicateObjectInfo) -> Self {
Self::Object {
Self {
bucket: info.bucket.clone(),
object: info.name.clone(),
version_id: info.version_id,
@@ -2463,25 +2435,6 @@ impl From<&ReplicateObjectInfo> for ReplicationInFlightKey {
}
}
impl ReplicationInFlightKey {
fn from_delete(info: &DeletedObjectReplicationInfo) -> Option<Self> {
let del = &info.delete_object;
if del.version_id.is_none() && del.delete_marker_version_id.is_none() && del.force_delete_id.is_none() {
return None;
}
Some(Self::Delete {
bucket: info.bucket.clone(),
object: del.object_name.clone(),
version_id: del.version_id,
delete_marker_version_id: del.delete_marker_version_id,
delete_marker: del.delete_marker,
force_delete: del.force_delete,
force_delete_id: del.force_delete_id,
target_arns: info.admitted_target_arns(),
})
}
}
impl ReplicationInFlight {
fn lock(&self) -> std::sync::MutexGuard<'_, std::collections::HashSet<ReplicationInFlightKey>> {
self.keys.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
@@ -2496,19 +2449,6 @@ impl ReplicationInFlight {
self.lock().remove(&ReplicationInFlightKey::from(ri));
}
fn try_begin_delete(&self, doi: &DeletedObjectReplicationInfo) -> bool {
let Some(key) = ReplicationInFlightKey::from_delete(doi) else {
return true;
};
self.lock().insert(key)
}
fn finish_delete(&self, doi: &DeletedObjectReplicationInfo) {
if let Some(key) = ReplicationInFlightKey::from_delete(doi) {
self.lock().remove(&key);
}
}
#[cfg(test)]
fn len(&self) -> usize {
self.lock().len()
@@ -2519,30 +2459,21 @@ impl ReplicationInFlight {
/// including when replication panics.
struct ReplicationInFlightGuard {
in_flight: Arc<ReplicationInFlight>,
key: Option<ReplicationInFlightKey>,
key: ReplicationInFlightKey,
}
impl ReplicationInFlightGuard {
fn new(in_flight: Arc<ReplicationInFlight>, ri: &ReplicateObjectInfo) -> Self {
Self {
in_flight,
key: Some(ReplicationInFlightKey::from(ri)),
}
}
fn for_delete(in_flight: Arc<ReplicationInFlight>, doi: &DeletedObjectReplicationInfo) -> Self {
Self {
in_flight,
key: ReplicationInFlightKey::from_delete(doi),
key: ReplicationInFlightKey::from(ri),
}
}
}
impl Drop for ReplicationInFlightGuard {
fn drop(&mut self) {
if let Some(key) = self.key.take() {
self.in_flight.lock().remove(&key);
}
self.in_flight.lock().remove(&self.key);
}
}
@@ -2617,7 +2548,6 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
let _in_flight = ReplicationInFlightGuard::for_delete(in_flight, del_info.as_ref());
replicate_delete(*del_info, storage).await;
}
}
@@ -4234,38 +4164,6 @@ mod tests {
assert!(in_flight.try_begin(&ri));
}
#[tokio::test]
async fn queue_replica_delete_task_deduplicates_versioned_delete_in_flight() {
let pool = new_test_replication_pool(Arc::new(LoadResyncNodeStore::new("node-a", empty_resync_shared_state()))).await;
let (tx, _rx) = mpsc::channel(4);
pool.workers.write().await.push(tx);
let dm_version = uuid::Uuid::new_v4();
let doi = DeletedObjectReplicationInfo {
bucket: "delete-dedup-bucket".to_string(),
op_type: ReplicationType::Heal,
target_arn: "arn:minio:replication:us-east-1:peer-b:replica".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "prod/dyn-0".to_string(),
delete_marker: true,
delete_marker_version_id: Some(dm_version),
..Default::default()
},
..Default::default()
};
assert_eq!(pool.queue_replica_delete_task(doi.clone()).await, ReplicationQueueAdmission::Queued);
assert_eq!(
pool.queue_replica_delete_task(doi.clone()).await,
ReplicationQueueAdmission::Skipped,
"scanner heal must not enqueue duplicate copies of an already-queued delete marker"
);
assert_eq!(pool.in_flight.len(), 1);
drop(ReplicationInFlightGuard::for_delete(pool.in_flight.clone(), &doi));
assert_eq!(pool.in_flight.len(), 0);
assert_eq!(pool.queue_replica_delete_task(doi).await, ReplicationQueueAdmission::Queued);
}
#[tokio::test]
async fn regular_worker_admission_counts_target_backlog_before_receive() {
let pool = new_test_replication_pool(Arc::new(LoadResyncNodeStore::new("node-a", empty_resync_shared_state()))).await;
@@ -13,7 +13,7 @@
// limitations under the License.
use super::replication_bandwidth_boundary;
use super::replication_config_boundary::{ObjectOpts, ReplicationConfigurationExt as _, legacy_role_target_arn};
use super::replication_config_boundary::{ObjectOpts, ReplicationConfigurationExt as _};
use super::replication_config_store::ReplicationConfigStore;
use super::replication_error_boundary::{Error, Result, is_err_object_not_found, is_err_version_not_found};
use super::replication_event_sink::{EventArgs, send_event, send_local_event};
@@ -2195,14 +2195,14 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
let has_stored_delete_decision = stored_delete_decision.is_some();
if let Some(rc) = rcfg.config.as_ref()
&& let Some(role) = legacy_role_target_arn(&rc.role)
&& !rc.role.is_empty()
{
if oi.version_purge_status_internal.is_none() && !oi.version_purge_status.is_empty() {
oi.version_purge_status_internal = Some(format!("{role}={};", oi.version_purge_status.as_str()));
oi.version_purge_status_internal = Some(format!("{}={};", rc.role, oi.version_purge_status.as_str()));
}
if oi.replication_status_internal.is_none() && !oi.replication_status.is_empty() {
oi.replication_status_internal = Some(format!("{role}={};", oi.replication_status.as_str()));
oi.replication_status_internal = Some(format!("{}={};", rc.role, oi.replication_status.as_str()));
}
let keys_to_update: Vec<_> = user_defined
@@ -2213,7 +2213,7 @@ pub async fn get_heal_replicate_object_info(oi: &ObjectInfo, rcfg: &ReplicationC
for (k, v) in keys_to_update {
user_defined.remove(&k);
user_defined.insert(target_reset_header(role), v);
user_defined.insert(target_reset_header(rc.role.as_str()), v);
}
}
@@ -2686,25 +2686,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
let purge_source = purge_source.clone();
// Spawn task in the join set
let is_site_peer = tgt_client.is_site_replication_peer();
join_set.spawn(async move {
let tgt_info = replicate_delete_to_target(&dobj_clone, tgt_client.clone(), purge_source).await;
let source = if is_site_peer {
rustfs_scanner_metrics::metrics::ScannerWorkSource::SiteReplication
} else {
rustfs_scanner_metrics::metrics::ScannerWorkSource::BucketReplication
};
match tgt_info.replication_status {
ReplicationStatusType::Completed | ReplicationStatusType::CompletedLegacy => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_executed(source, 1);
}
ReplicationStatusType::Failed => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_failed(source, 1);
}
_ => {}
}
tgt_info
});
join_set.spawn(async move { replicate_delete_to_target(&dobj_clone, tgt_client.clone(), purge_source).await });
}
// Collect all results
@@ -4346,28 +4328,12 @@ pub(crate) async fn replicate_object_with_outcome<S: ReplicationStorage>(
let roi_clone = roi.clone();
let storage_clone = storage.clone();
let is_site_peer = tgt_client.is_site_replication_peer();
join_set.spawn(async move {
let tgt_info = if roi.op_type == ReplicationType::Object {
if roi.op_type == ReplicationType::Object {
roi_clone.replicate_object(storage_clone, tgt_client).await
} else {
roi_clone.replicate_all(storage_clone, tgt_client).await
};
let source = if is_site_peer {
rustfs_scanner_metrics::metrics::ScannerWorkSource::SiteReplication
} else {
rustfs_scanner_metrics::metrics::ScannerWorkSource::BucketReplication
};
match tgt_info.replication_status {
ReplicationStatusType::Completed | ReplicationStatusType::CompletedLegacy => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_executed(source, 1);
}
ReplicationStatusType::Failed => {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_failed(source, 1);
}
_ => {}
}
tgt_info
});
}
@@ -283,13 +283,8 @@ impl BucketTarget {
self.target_bucket.is_empty() && self.endpoint.is_empty() && self.arn.is_empty()
}
pub fn url(&self) -> Result<Url> {
let trimmed = self.endpoint.trim();
let host_and_path = trimmed
.strip_prefix("https://")
.or_else(|| trimmed.strip_prefix("http://"))
.unwrap_or(trimmed);
let scheme = if self.secure { "https" } else { "http" };
Url::parse(&format!("{}://{}", scheme, host_and_path)).map_err(Error::other)
Url::parse(&format!("{}://{}", scheme, self.endpoint)).map_err(Error::other)
}
}
@@ -175,30 +175,7 @@ fn endpoint_matches_audience(endpoint: &str, audience: &str) -> bool {
}
pub(crate) fn on_authenticated_peer_boot_epoch_changed(audience: &str, old_epoch: Uuid, new_epoch: Uuid) {
if old_epoch == new_epoch {
return;
}
// Synchronously fence grant admission for `old_epoch` before scheduling the
// shard sweep so late RPCs from `old_epoch` cannot be admitted and locks
// granted to `new_epoch` are never disturbed.
rustfs_lock::retire_local_owner_incarnation(audience, old_epoch);
let owner = audience.to_string();
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
let reclaimed = rustfs_lock::reclaim_all_local_guards_for_owner_incarnation(&owner, old_epoch).await;
if reclaimed > 0 {
info!(
event = "internode_peer_locks_reclaimed_on_restart",
owner = %owner,
old_boot_epoch = %old_epoch,
new_boot_epoch = %new_epoch,
reclaimed,
"Reclaimed stale local lock guards from restarted peer incarnation"
);
}
});
}
if *STREAM_RESPONSE_AUTH_STRICT {
if old_epoch == new_epoch || *STREAM_RESPONSE_AUTH_STRICT {
return;
}
let mut removed_endpoints = Vec::new();
@@ -138,17 +138,8 @@ impl<T: Send + 'static> Drop for InFlightRpc<'_, T> {
const LOCK_RPC_LIVENESS_WINDOW_DEADLINES: u32 = 2;
const LOCK_RPC_REQUEST_BACKOFF_THRESHOLD: u32 = 3;
const LOCK_RPC_REQUEST_BACKOFF_MAX: Duration = Duration::from_secs(30);
const LATE_RELEASE_RETRY_DELAYS: [Duration; 8] = [
Duration::from_millis(100),
Duration::from_millis(250),
Duration::from_millis(500),
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(4),
Duration::from_secs(8),
Duration::from_secs(16),
];
const LATE_RELEASE_IN_FLIGHT_LIMIT: usize = 256;
const LATE_RELEASE_RETRY_DELAYS: [Duration; 3] = [Duration::from_millis(100), Duration::from_millis(500), Duration::from_secs(1)];
const LATE_RELEASE_IN_FLIGHT_LIMIT: usize = 32;
const TIMEOUT_LOG_STATE_MAX: usize = 1024;
const TIMEOUT_LOG_STATE_RETENTION: Duration = Duration::from_secs(600);
@@ -467,7 +458,6 @@ impl RemoteClient {
suppress_contention_logs: false,
refresh_interval: None,
cache_fence_stamp_requested: false,
owner_incarnation: None,
}
}
@@ -478,15 +468,6 @@ impl RemoteClient {
if let Some(reason) = crate::cluster::rpc::remote_disk::internode_offline_bypass_reason(&self.addr) {
return Err(LockError::internal(reason));
}
self.get_client_for_cleanup().await
}
async fn get_client_for_cleanup(
&self,
) -> Result<NodeServiceClient<InterceptedService<AuthenticatedChannel, TonicInterceptor>>> {
// Unlock and late-release cleanup RPCs intentionally bypass `internode_offline_bypass_reason`
// so that as soon as a partitioned or paused peer becomes reachable again, pending lock
// releases clear immediately instead of waiting for `remote_disk`'s periodic health monitor.
node_service_time_out_client(&self.addr, TonicInterceptor::Signature(gen_tonic_signature_interceptor()))
.await
.map_err(|err| LockError::internal(format!("can not get client, err: {err}")))
@@ -763,9 +744,6 @@ impl RemoteClient {
fn bounded_acquire_request(request: &LockRequest, deadline: Duration) -> LockRequest {
let mut bounded = request.clone();
bounded.acquire_timeout = bounded.acquire_timeout.min(deadline);
if bounded.owner_incarnation.is_none() {
bounded.owner_incarnation = Some(crate::cluster::rpc::http_auth::tonic_rpc_boot_epoch());
}
bounded
}
@@ -995,7 +973,7 @@ impl RemoteClient {
let unlock_request = Self::create_unlock_request(lock_id);
let request_string = serde_json::to_string(&unlock_request)
.map_err(|e| LockError::internal(format!("Failed to serialize request: {e}")))?;
let mut client = self.get_client_for_cleanup().await?;
let mut client = self.get_client().await?;
let resource_summary = unlock_request.resource.to_string();
let mut req = Request::new(GenerallyLockRequest { args: request_string });
attach_lock_mutation_body_digest(&mut req)?;
@@ -1013,7 +991,7 @@ impl RemoteClient {
async fn request_release_batch(&self, lock_ids: &[LockId]) -> Result<BatchGenerallyLockResponse> {
let unlock_requests = lock_ids.iter().map(Self::create_unlock_request).collect::<Vec<_>>();
let mut client = self.get_client_for_cleanup().await?;
let mut client = self.get_client().await?;
let resource_summary = Self::summarize_resources(&unlock_requests);
let mut req = Request::new(BatchGenerallyLockRequest {
args: unlock_requests
@@ -2306,12 +2284,10 @@ mod tests {
let request = test_lock_request(Duration::from_secs(30));
let bounded = RemoteClient::bounded_acquire_request(&request, Duration::from_secs(3));
assert_eq!(bounded.acquire_timeout, Duration::from_secs(3));
assert_eq!(bounded.owner_incarnation, Some(crate::cluster::rpc::http_auth::tonic_rpc_boot_epoch()));
let request = test_lock_request(Duration::from_secs(1));
let bounded = RemoteClient::bounded_acquire_request(&request, Duration::from_secs(3));
assert_eq!(bounded.acquire_timeout, Duration::from_secs(1));
assert_eq!(bounded.owner_incarnation, Some(crate::cluster::rpc::http_auth::tonic_rpc_boot_epoch()));
}
#[test]
+2 -4
View File
@@ -185,10 +185,8 @@ const DECOMMISSION_CAPACITY_INTENT_CONFLICT_MAX_ATTEMPTS: usize = 12;
// A scanner pause backlog handoff conflict is a transient membership
// transition: the native authority is expected to converge once surviving
// replicas advance their durable commit. Bound the wait so a genuinely
// divergent authority still reaches a terminal, attributable failure, while
// giving multi-second network partitions and post-partition membership commits
// enough budget (~65s at the 1.5s backoff cap) to converge.
const DECOMMISSION_SCANNER_BACKLOG_HANDOFF_MAX_ATTEMPTS: usize = 48;
// divergent authority still reaches a terminal, attributable failure.
const DECOMMISSION_SCANNER_BACKLOG_HANDOFF_MAX_ATTEMPTS: usize = 12;
const DECOMMISSION_SOURCE_CLEANUP_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(100);
/// In-place attempts for a source cleanup quorum failure before the entry is
/// deferred to the end of the round.
+1 -1
View File
@@ -1832,7 +1832,7 @@ impl LocalDiskWrapper {
/// Only suppresses idle monitoring; request paths still validate the format on disk.
pub(crate) async fn can_skip_background_probe(&self) -> bool {
if self.retired.is_cancelled() || self.runtime_state() != RuntimeDriveHealthState::Online {
if self.runtime_state() != RuntimeDriveHealthState::Online {
return false;
}
let observed = self.disk.format_info.read().await.id;
+313 -53
View File
@@ -70,6 +70,12 @@ use crate::disk::{
endpoint::Endpoint,
error::{DiskError, Error, Result},
format::FormatV3,
multipart_source::{
MULTIPART_SOURCE_PROTOCOL_VERSION, MultipartProofKind, MultipartPublicationResult, MultipartSourceOperation,
MultipartSourcePhase, MultipartSourceProof, MultipartSourceRequest, MultipartSourceResponse, MultipartSourceSnapshot,
MultipartUndoCapability, ProofVerificationContext, PublicationIdentity, SourceConditionV1, capture_source_condition,
publication_identity, require_source_condition, strip_transport_condition,
},
part_transaction_path, validate_delete_recovery_options, validate_format_control_path,
};
use crate::erasure::coding::{self, bitrot_verify};
@@ -78,6 +84,8 @@ use crate::set_disk::SetDisks;
use crate::store::init_format::save_format_file;
const DST_DELETE_TX_DIR: &str = ".rustfs.sys/dst-del-tx";
const DST_MULTIPART_STATE: &str = ".dst-mpu-consumed";
const DST_MULTIPART_ANCHOR: &str = ".dst-mpu-retirement-anchor";
const DEFAULT_SIM_CAPACITY_BYTES: u64 = 10 * 1024 * 1024 * 1024;
fn sim_to_io_err(err: SimErr) -> IoError {
@@ -210,6 +218,22 @@ struct SimDeleteTxRecord {
backup_xl: Option<Vec<u8>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SimMultipartAnchor {
disk_id: Uuid,
physical_slot: usize,
publication: PublicationIdentity,
original_sha256: [u8; 32],
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct SimMultipartState {
anchor: SimMultipartAnchor,
capability_sha256: Option<[u8; 32]>,
}
/// Deterministic simulated disk implementing production [`DiskAPI`] directly
/// on top of [`SimDiskIo`].
#[derive(Clone)]
@@ -226,6 +250,7 @@ pub struct DstSimDisk {
scanning: Arc<AtomicU32>,
delete_tx_lock: Arc<tokio::sync::Mutex<()>>,
cas_lock: Arc<tokio::sync::Mutex<()>>,
multipart_publication_lock: Arc<tokio::sync::Mutex<()>>,
configured_capacity: Arc<RwLock<Option<u64>>>,
multipart_proof_authority: Arc<RwLock<Option<crate::disk::multipart_source::ProofVerificationContext>>>,
}
@@ -281,6 +306,7 @@ impl DstSimDisk {
scanning: Arc::new(AtomicU32::new(0)),
delete_tx_lock: Arc::new(tokio::sync::Mutex::new(())),
cas_lock: Arc::new(tokio::sync::Mutex::new(())),
multipart_publication_lock: Arc::new(tokio::sync::Mutex::new(())),
configured_capacity: Arc::new(RwLock::new(None)),
multipart_proof_authority: Arc::new(RwLock::new(None)),
}
@@ -299,6 +325,12 @@ impl DstSimDisk {
&self.sim
}
/// Returns the simulator-only retirement witness path for fault injection.
pub fn multipart_retirement_anchor_path(volume: &str, object: &str, data_dir: Uuid) -> Result<String> {
let target_dir = join_vol_path(volume, object)?;
Ok(format!("{target_dir}/{data_dir}/{DST_MULTIPART_ANCHOR}"))
}
pub fn crash_registry(&self) -> &CrashRegistry {
&self.crash_registry
}
@@ -431,6 +463,241 @@ impl DstSimDisk {
Ok(())
}
fn multipart_authority(&self) -> Result<ProofVerificationContext> {
self.multipart_proof_authority
.read()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone()
.ok_or(DiskError::UnsupportedDisk)
}
async fn sync_multipart_source_absence(&self, mut path: &str) -> Result<()> {
while let Some((parent, _)) = path.rsplit_once('/') {
match self.sim.stat(parent).await {
Ok(contents) if contents.is_dir => return self.fsync_parent_chain(parent).await,
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
Err(SimErr::NotFound(_)) => path = parent,
Err(error) => return Err(map_sim_err(error)),
}
}
self.fsync_parent_chain("").await
}
async fn prepare_multipart_anchor(
&self,
source_dir: &str,
src_path: &str,
target: (&str, &str),
fi: &FileInfo,
publication: PublicationIdentity,
) -> Result<SimMultipartAnchor> {
self.multipart_authority()?;
let condition = require_source_condition(fi)?;
if publication.lineage.path != src_path
|| (publication.lineage.bucket.as_str(), publication.lineage.object.as_str()) != target
|| condition.attach(&mut fi.clone())? != publication
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
{
return Err(DiskError::ConditionalDeleteConflict);
}
match self.sim.stat(&format!("{source_dir}/{DST_MULTIPART_STATE}")).await {
Err(SimErr::NotFound(_)) => {}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
}
let original = self
.sim
.read_file(&format!("{source_dir}/{STORAGE_FORMAT_FILE}"))
.await
.map_err(map_sim_err)?;
let original_fi = get_file_info(
&original,
RUSTFS_META_MULTIPART_BUCKET,
src_path,
&publication.lineage.original_version_id.unwrap_or_default().to_string(),
FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: true,
},
)?;
if capture_source_condition(target.0, target.1, src_path, &original_fi, publication.attempt)? != condition
|| publication.lineage.geometry.distribution.get(self.disk_idx) != Some(&original_fi.erasure.index)
{
return Err(DiskError::ConditionalDeleteConflict);
}
Ok(SimMultipartAnchor {
disk_id: self.get_disk_id().await?.ok_or(DiskError::InconsistentDisk)?,
physical_slot: self.disk_idx,
publication,
original_sha256: Sha256::digest(original).into(),
})
}
fn multipart_snapshot(
anchor: &SimMultipartAnchor,
revision: u64,
phase: MultipartSourcePhase,
record: &[u8],
target: &[u8],
capability_sha256: Option<[u8; 32]>,
) -> MultipartSourceSnapshot {
let state_sha256: [u8; 32] = Sha256::digest(record).into();
let mut inventory = Sha256::new();
inventory.update(state_sha256);
inventory.update(Sha256::digest(target));
MultipartSourceSnapshot {
disk_id: anchor.disk_id,
physical_slot: anchor.physical_slot,
lineage: anchor.publication.lineage.clone(),
generation: anchor.publication.source_generation,
revision,
phase,
state_sha256,
head_sha256: None,
inventory_sha256: inventory.finalize().into(),
capability_sha256,
publication: Some(anchor.publication.clone()),
}
}
async fn publish_multipart_witness(
&self,
source_dir: &str,
target_dir: &str,
anchor: SimMultipartAnchor,
target: &[u8],
) -> Result<MultipartPublicationResult> {
let authority = self.multipart_authority()?;
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", anchor.publication.final_data_dir);
let anchor_bytes = rmp_serde::to_vec_named(&anchor).map_err(Error::other)?;
self.write_durable_file(&anchor_path, Bytes::from(anchor_bytes)).await?;
let undo_capability = MultipartUndoCapability::new();
let state = SimMultipartState {
anchor,
capability_sha256: Some(undo_capability.digest()),
};
let record = rmp_serde::to_vec_named(&state).map_err(Error::other)?;
// The fsync of the source directory also persists removal of its old
// xl.meta name, which was renamed to the destination during commit.
self.write_durable_file(&format!("{source_dir}/{DST_MULTIPART_STATE}"), Bytes::copy_from_slice(&record))
.await?;
let snapshot = Self::multipart_snapshot(
&state.anchor,
1,
MultipartSourcePhase::ConsumedUnsealed,
&record,
target,
state.capability_sha256,
);
let publication = state.anchor.publication;
let proof = MultipartSourceProof::issue(&authority, MultipartProofKind::Published, publication.attempt, None, snapshot)?;
Ok(MultipartPublicationResult {
publication,
proof,
undo_capability,
})
}
async fn confirm_multipart_witness(
&self,
path: &str,
publication: &PublicationIdentity,
challenge: Uuid,
) -> Result<MultipartSourceProof> {
self.ensure_online()?;
publication.lineage.validate()?;
if publication.lineage.path != path || challenge.is_nil() {
return Err(DiskError::ConditionalDeleteConflict);
}
let _guard = self.multipart_publication_lock.lock().await;
let authority = self.multipart_authority()?;
let lineage = &publication.lineage;
let source_dir = join_vol_path(RUSTFS_META_MULTIPART_BUCKET, path)?;
let target_dir = join_vol_path(&lineage.bucket, &lineage.object)?;
let target_meta = format!("{target_dir}/{STORAGE_FORMAT_FILE}");
let anchor_path = format!("{target_dir}/{}/{DST_MULTIPART_ANCHOR}", publication.final_data_dir);
let anchor_raw = self.sim.read_file(&anchor_path).await.map_err(map_sim_err)?;
let anchor: SimMultipartAnchor = rmp_serde::from_slice(&anchor_raw).map_err(Error::other)?;
if Some(anchor.disk_id) != self.get_disk_id().await?
|| anchor.physical_slot != self.disk_idx
|| anchor.publication != *publication
{
return Err(DiskError::ConditionalDeleteConflict);
}
let target = self.sim.read_file(&target_meta).await.map_err(map_sim_err)?;
let fi = get_file_info(
&target,
&lineage.bucket,
&lineage.object,
&publication.version_id.unwrap_or_default().to_string(),
FileInfoOpts {
data: false,
include_free_versions: false,
include_part_checksums: true,
},
)?;
let condition = SourceConditionV1 {
lineage: lineage.clone(),
generation: publication.source_generation,
attempt: publication.attempt,
};
let geometry = &lineage.geometry;
if publication_identity(&fi)?.as_ref() != Some(publication)
|| condition.attach(&mut fi.clone())? != *publication
|| geometry.distribution.get(self.disk_idx) != Some(&fi.erasure.index)
|| fi.erasure.distribution != geometry.distribution
|| fi.erasure.data_blocks != geometry.data_blocks
|| fi.erasure.parity_blocks != geometry.parity_blocks
|| fi.erasure.block_size != geometry.block_size
{
return Err(DiskError::ConditionalDeleteConflict);
}
if !fi.inline_data() && fi.size > 0 {
let verified = self.verify_file(&lineage.bucket, &lineage.object, &fi).await?;
if verified.results.iter().any(|result| *result != CHECK_PART_SUCCESS) {
return Err(DiskError::FileCorrupt);
}
}
self.sim.fsync_file(&target_meta).await.map_err(map_sim_err)?;
self.fsync_parent_chain(&target_dir).await?;
let (kind, snapshot) = match self.sim.stat(&source_dir).await {
Err(SimErr::NotFound(_)) => {
self.sync_multipart_source_absence(&source_dir).await?;
(
MultipartProofKind::RootMissingTerminal,
Self::multipart_snapshot(&anchor, 0, MultipartSourcePhase::RootMissing, &anchor_raw, &target, None),
)
}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => {
match self.sim.stat(&format!("{source_dir}/{STORAGE_FORMAT_FILE}")).await {
Err(SimErr::NotFound(_)) => {}
Err(error) => return Err(map_sim_err(error)),
Ok(_) => return Err(DiskError::ConditionalDeleteConflict),
}
let state_path = format!("{source_dir}/{DST_MULTIPART_STATE}");
let mut raw = self.sim.read_file(&state_path).await.map_err(map_sim_err)?;
let mut state: SimMultipartState = rmp_serde::from_slice(&raw).map_err(Error::other)?;
if state.anchor != anchor {
return Err(DiskError::ConditionalDeleteConflict);
}
if state.capability_sha256.take().is_some() {
raw = Bytes::from(rmp_serde::to_vec_named(&state).map_err(Error::other)?);
self.write_durable_file(&state_path, raw.clone()).await?;
}
(
MultipartProofKind::TerminalTarget,
Self::multipart_snapshot(&anchor, 2, MultipartSourcePhase::LocalTerminalSeal, &raw, &target, None),
)
}
};
MultipartSourceProof::issue(&authority, kind, challenge, None, snapshot)
}
fn load_filemeta_preserving_inline(raw: &[u8]) -> Result<FileMeta> {
let (mut fm, inline_buf) = FileMeta::load_with_borrowed_inline_data(raw)?;
if !inline_buf.is_empty() {
@@ -1428,7 +1695,7 @@ impl DiskAPI for DstSimDisk {
&self,
src_volume: &str,
src_path: &str,
file_info: FileInfo,
mut file_info: FileInfo,
dst_volume: &str,
dst_path: &str,
) -> Result<RenameDataResp> {
@@ -1442,6 +1709,23 @@ impl DiskAPI for DstSimDisk {
let bkp_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
let src_meta = format!("{src_dir}/{STORAGE_FORMAT_FILE}");
let multipart = src_volume == RUSTFS_META_MULTIPART_BUCKET;
let _multipart_guard = if multipart {
Some(self.multipart_publication_lock.lock().await)
} else {
None
};
let publication = if multipart { publication_identity(&file_info)? } else { None };
let multipart_anchor = if let Some(publication) = publication {
let anchor = self
.prepare_multipart_anchor(&src_dir, src_path, (dst_volume, dst_path), &file_info, publication)
.await?;
strip_transport_condition(&mut file_info.metadata);
Some(anchor)
} else {
None
};
let existing_raw = match self.sim.read_file(&dst_meta).await {
Ok(b) => Some(b),
Err(SimErr::NotFound(_)) => None,
@@ -1484,20 +1768,15 @@ impl DiskAPI for DstSimDisk {
self.sim.create_dir_all(&src_dir).await.map_err(map_sim_err)?;
self.sim.create_dir_all(&dst_dir).await.map_err(map_sim_err)?;
let multipart_pub_identity = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
crate::disk::multipart_source::publication_identity(&file_info)?
} else {
None
};
let has_external_parts =
!file_info.inline_data() && file_info.data.as_ref().is_none_or(|d| d.is_empty()) && file_info.size > 0;
if has_external_parts
&& let Some(data_dir) = file_info.data_dir
&& !data_dir.is_nil()
{
let src_data_dir = multipart_pub_identity
let src_data_dir = multipart_anchor
.as_ref()
.map(|p| p.lineage.original_data_dir)
.map(|anchor| anchor.publication.lineage.original_data_dir)
.unwrap_or(data_dir);
let src_data = format!("{src_dir}/{src_data_dir}");
let dst_data = format!("{dst_dir}/{data_dir}");
@@ -1533,7 +1812,10 @@ impl DiskAPI for DstSimDisk {
self.check_crash_point(CrashPoint::RenameAfterBackupBeforeMetaCommit, dst_volume, dst_path)?;
self.sim.write_file(&src_meta, new_meta_bytes).await.map_err(map_sim_err)?;
self.sim
.write_file(&src_meta, new_meta_bytes.clone())
.await
.map_err(map_sim_err)?;
self.sim.fsync_file(&src_meta).await.map_err(map_sim_err)?;
self.sim.rename(&src_meta, &dst_meta).await.map_err(map_sim_err)?;
@@ -1545,50 +1827,12 @@ impl DiskAPI for DstSimDisk {
let _ = self.sim.remove_dir_all(&src_dir).await;
}
let multipart_source = if src_volume == RUSTFS_META_MULTIPART_BUCKET {
let publication = crate::disk::multipart_source::publication_identity(&file_info)?;
let authority = self
.multipart_proof_authority
.read()
.unwrap_or_else(|p| p.into_inner())
.clone();
if let (Some(publication), Some(authority)) = (publication, authority) {
let disk_id = self
.disk_id
.read()
.unwrap_or_else(|p| p.into_inner())
.ok_or(DiskError::InconsistentDisk)?;
let undo_capability = crate::disk::multipart_source::MultipartUndoCapability::new();
let snapshot = crate::disk::multipart_source::MultipartSourceSnapshot {
disk_id,
physical_slot: self.disk_idx,
lineage: publication.lineage.clone(),
generation: publication.source_generation,
revision: 1,
phase: crate::disk::multipart_source::MultipartSourcePhase::ConsumedUnsealed,
state_sha256: [0; 32],
head_sha256: None,
inventory_sha256: [0; 32],
capability_sha256: Some(undo_capability.digest()),
publication: Some(publication.clone()),
};
let proof = crate::disk::multipart_source::MultipartSourceProof::issue(
&authority,
crate::disk::multipart_source::MultipartProofKind::Published,
Uuid::new_v4(),
None,
snapshot,
)?;
Some(Box::new(crate::disk::multipart_source::MultipartPublicationResult {
publication,
proof,
undo_capability,
}))
} else {
None
}
} else {
None
let multipart_source = match multipart_anchor {
Some(anchor) => Some(Box::new(
self.publish_multipart_witness(&src_dir, &dst_dir, anchor, &new_meta_bytes)
.await?,
)),
None => None,
};
Ok(RenameDataResp {
@@ -1601,6 +1845,22 @@ impl DiskAPI for DstSimDisk {
})
}
async fn recover_multipart_source(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
if request.protocol_version != MULTIPART_SOURCE_PROTOCOL_VERSION {
return Err(DiskError::UnsupportedDisk);
}
match request.operation {
MultipartSourceOperation::ConfirmTerminal {
expected: None,
publication,
challenge,
} => Ok(MultipartSourceResponse::TerminalConfirmed(
self.confirm_multipart_witness(&request.path, &publication, challenge).await?,
)),
_ => Err(DiskError::UnsupportedDisk),
}
}
async fn list_dir(&self, _origvolume: &str, volume: &str, dir_path: &str, count: i32) -> Result<Vec<String>> {
self.ensure_online()?;
self.ensure_volume_exists(volume).await?;
+1 -1
View File
@@ -1731,7 +1731,7 @@ async fn remove_windows_empty_directory(directory: LockedEmptyDirectory) -> std:
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle};
let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
let disposition_size = u32::try_from(std::mem::size_of_val(&disposition))
.map_err(|_| std::io::Error::other("FILE_DISPOSITION_INFO size exceeds the Win32 API limit"))?;
let handle = directory.handle.as_raw_handle();
+4 -2
View File
@@ -6252,7 +6252,7 @@ fn rename_into_existing_parent(
// its header, the complete UTF-16 name, and trailing zeroed storage.
// `dst_parent` and `source` remain live until the synchronous call returns.
unsafe {
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: true };
(*rename_info).Anonymous = FILE_RENAME_INFORMATION_0 { ReplaceIfExists: 1 };
(*rename_info).RootDirectory = dst_parent.as_raw_handle();
(*rename_info).FileNameLength = file_name_length;
std::ptr::copy_nonoverlapping(
@@ -7753,7 +7753,9 @@ fn set_windows_file_delete_on_close(file: &winapi_util::Handle, delete_file: boo
Win32::{Foundation::RtlNtStatusToDosError, System::IO::IO_STATUS_BLOCK},
};
let mut disposition = FILE_DISPOSITION_INFORMATION { DeleteFile: delete_file };
let mut disposition = FILE_DISPOSITION_INFORMATION {
DeleteFile: u8::from(delete_file),
};
let length = u32::try_from(size_of::<FILE_DISPOSITION_INFORMATION>())
.map_err(|_| io::Error::other("Windows file disposition size exceeds u32"))?;
let mut io_status = IO_STATUS_BLOCK::default();
@@ -58,7 +58,6 @@ pub use types::{
RebalanceStats, RebalanceStopPropagationRecord,
};
use types::{RebalanceBucketConfigs, RebalanceBucketOutcome, RebalanceDeferKind, RebalanceEntryOutcome};
pub(crate) use worker::is_transient_rebalance_error;
#[cfg(any(test, feature = "test-util"))]
pub async fn test_store_with_persisted_rebalance_meta(
@@ -287,7 +287,7 @@ pub(super) fn resolve_rebalance_bucket_result(
}
}
pub(crate) fn is_transient_rebalance_error(err: &Error) -> bool {
pub(super) fn is_transient_rebalance_error(err: &Error) -> bool {
let err = rebalance_error_source(err);
match err {
Error::SlowDown
@@ -8022,47 +8022,18 @@ impl SetDisks {
// - If no_lock is false, we must have obtained the lock out side of this function
// - If no_lock is true, we should not obtain locks
lookup_opts.no_lock = true;
let oi = if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|store| {
!store.single_pool()
&& !crate::bucket::utils::is_meta_bucketname(bucket)
&& !opts.data_movement
&& !opts.replication_request
&& !opts.no_lock
&& !opts.skip_decommissioned
&& !opts.skip_rebalancing
}) {
lookup_opts.metadata_cache_safe = false;
lookup_opts.metadata_cache_fence_proof = None;
lookup_opts.suppress_read_repair = true;
let lookup = store.get_latest_object_info_for_conditional_write(bucket, object, &lookup_opts);
#[cfg(feature = "diagnostic-read-version-caller")]
let lookup = crate::cluster::rpc::runtime_sources::with_read_version_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::WritePreconditionRead,
async {
crate::cluster::rpc::runtime_sources::observe_read_version_context_boundary(
rustfs_io_metrics::internode_metrics::ReadVersionContextBoundary::WritePreconditionLookup,
);
lookup.await
},
);
lookup.await.and_then(|(info, _)| {
lookup_opts.precondition_check(&info)?;
Ok(info)
})
} else {
let lookup = self.get_object_info(bucket, object, &lookup_opts);
#[cfg(feature = "diagnostic-read-version-caller")]
let lookup = crate::cluster::rpc::runtime_sources::with_read_version_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::WritePreconditionRead,
async {
crate::cluster::rpc::runtime_sources::observe_read_version_context_boundary(
rustfs_io_metrics::internode_metrics::ReadVersionContextBoundary::WritePreconditionLookup,
);
lookup.await
},
);
lookup.await
};
let lookup = self.get_object_info(bucket, object, &lookup_opts);
#[cfg(feature = "diagnostic-read-version-caller")]
let lookup = crate::cluster::rpc::runtime_sources::with_read_version_entry(
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::WritePreconditionRead,
async {
crate::cluster::rpc::runtime_sources::observe_read_version_context_boundary(
rustfs_io_metrics::internode_metrics::ReadVersionContextBoundary::WritePreconditionLookup,
);
lookup.await
},
);
let oi = lookup.await;
Self::evaluate_write_precondition(oi, &http_preconditions, bucket, object, opts)
}
}
+2 -313
View File
@@ -14,10 +14,9 @@
use super::{
Bytes, DATA_MOVEMENT_MULTIPART_PREFIX, DiskError, DiskStore, FileInfo, HashMap, HashSet, OBJECT_OP_IGNORED_ERRS, ObjProps,
OffsetDateTime, SLASH_SEPARATOR, SetDisks, Sha256, TRANSITION_COMPLETE, Uuid, debug, disk, error,
file_info_is_valid_for_metadata, hex, reduce_read_quorum_errs, warn,
OffsetDateTime, SetDisks, Sha256, TRANSITION_COMPLETE, Uuid, debug, disk, error, file_info_is_valid_for_metadata, hex,
reduce_read_quorum_errs, warn,
};
use crate::disk::DiskAPI;
#[cfg(test)]
use crate::disk::DiskOption;
#[cfg(test)]
@@ -28,21 +27,6 @@ use rustfs_filemeta::metadata_keys;
use rustfs_utils::http;
use sha2::Digest;
const MAX_INCOMPLETE_OVERWRITE_ROLLBACK_STEPS: usize = 4;
pub(super) struct IncompleteOverwriteSlotRollback {
pub(super) slot_index: usize,
pub(super) rollback_dir: Uuid,
pub(super) undo_file_info: FileInfo,
}
pub(super) struct IncompleteOverwriteResolution {
pub(super) online_disks: Vec<Option<DiskStore>>,
pub(super) fi: FileInfo,
pub(super) parts_metadata: Vec<FileInfo>,
pub(super) rollbacks: Vec<IncompleteOverwriteSlotRollback>,
}
#[derive(Clone, Copy)]
struct FileInfoIdentityGroup {
key: FileInfoQuorumKey,
@@ -806,301 +790,6 @@ impl SetDisks {
Self::find_file_info_in_quorum(metas, &mod_time, &etag, quorum)
}
pub(super) fn is_null_version_request(version_id: &str) -> bool {
version_id.is_empty() || Uuid::parse_str(version_id).is_ok_and(|id| id.is_nil())
}
/// Quick complete-set check before inspecting per-disk `xl.meta.bkp` files:
/// requires a non-system null-version target, every set member online and
/// returning valid metadata without errors (a missing/replaced drive could
/// have held a committed quorum copy of the newest generation), and every
/// live identity at the newest modification time strictly below its write
/// quorum.
pub(super) fn may_have_incomplete_null_overwrite(
&self,
bucket: &str,
version_id: &str,
disks: &[Option<DiskStore>],
parts_metadata: &[FileInfo],
errs: &[Option<DiskError>],
) -> bool {
if crate::bucket::utils::is_meta_bucketname(bucket)
|| !Self::is_null_version_request(version_id)
|| disks.len() != self.set_drive_count
|| disks.is_empty()
|| parts_metadata.len() != disks.len()
|| errs.len() != disks.len()
|| disks.iter().any(Option::is_none)
{
return false;
}
if errs.iter().any(Option::is_some) || !parts_metadata.iter().all(file_info_is_valid_for_metadata) {
return false;
}
Self::newest_live_generation_below_write_quorum(parts_metadata, errs, self.default_write_quorum()).is_some()
}
fn newest_live_generation_below_write_quorum(
parts_metadata: &[FileInfo],
errs: &[Option<DiskError>],
default_write_quorum: usize,
) -> Option<OffsetDateTime> {
let latest_mod_time = parts_metadata
.iter()
.zip(errs.iter())
.filter(|(fi, err)| err.is_none() && file_info_is_valid_for_metadata(fi))
.filter_map(|(fi, _)| fi.mod_time)
.max()?;
let mut counts: HashMap<FileInfoQuorumKey, (usize, usize)> = HashMap::new();
for (fi, err) in parts_metadata.iter().zip(errs.iter()) {
if err.is_some() || !file_info_is_valid_for_metadata(fi) || fi.mod_time != Some(latest_mod_time) {
continue;
}
let write_quorum = fi.write_quorum(default_write_quorum);
let entry = counts.entry(Self::file_info_quorum_key(fi)).or_insert((0, write_quorum));
entry.0 += 1;
if entry.0 >= entry.1 {
return None;
}
}
(!counts.is_empty()).then_some(latest_mod_time)
}
/// Resolve a split null-version set left behind when an unversioned
/// overwrite failed below write quorum and `undo_write` was indeterminate
/// or failed on a subset of drives. With every drive in the set answering,
/// any newest live generation below write quorum never committed; restoring
/// those drives' preserved `<rollback_dir>/xl.meta.bkp` recovers the prior
/// committed version when the combined set reaches valid read quorum.
#[allow(clippy::too_many_arguments)]
pub(super) async fn discover_incomplete_overwrite_rollbacks(
&self,
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
version_id: &str,
parts_metadata: &[FileInfo],
errs: &[Option<DiskError>],
read_data: bool,
include_part_checksums: bool,
) -> Option<IncompleteOverwriteResolution> {
if !self.may_have_incomplete_null_overwrite(bucket, version_id, disks, parts_metadata, errs) {
return None;
}
let disk_object = rustfs_utils::path::encode_dir_object(object);
let mut candidate_metadata = parts_metadata.to_vec();
let candidate_errs = errs.to_vec();
let mut rolled_back_slots = vec![false; disks.len()];
let mut rollbacks = Vec::new();
let default_write_quorum = self.default_write_quorum();
for _ in 0..MAX_INCOMPLETE_OVERWRITE_ROLLBACK_STEPS {
let Some(latest_mod_time) =
Self::newest_live_generation_below_write_quorum(&candidate_metadata, &candidate_errs, default_write_quorum)
else {
break;
};
let target_slots = (0..disks.len())
.filter(|&slot| {
!rolled_back_slots[slot]
&& candidate_errs[slot].is_none()
&& file_info_is_valid_for_metadata(&candidate_metadata[slot])
&& candidate_metadata[slot].mod_time == Some(latest_mod_time)
})
.collect::<Vec<_>>();
if target_slots.is_empty() {
break;
}
let mut step_rolled_back = false;
for slot_index in target_slots {
let disk = disks.get(slot_index).and_then(Option::as_ref)?;
let live_fi = &candidate_metadata[slot_index];
let loaded = Self::load_overwrite_rollback_backup_on_disk(
disk,
bucket,
object,
&disk_object,
live_fi,
read_data,
include_part_checksums,
)
.await?;
let Some((rollback_dir, bkp_fi)) = loaded else {
continue;
};
let mut undo_file_info = live_fi.clone();
if undo_file_info.data_dir == bkp_fi.data_dir {
undo_file_info.data_dir = None;
}
candidate_metadata[slot_index] = bkp_fi;
rolled_back_slots[slot_index] = true;
rollbacks.push(IncompleteOverwriteSlotRollback {
slot_index,
rollback_dir,
undo_file_info,
});
step_rolled_back = true;
}
if !step_rolled_back {
break;
}
if let Ok((read_quorum, _)) =
Self::object_quorum_from_meta(&candidate_metadata, &candidate_errs, self.default_parity_count)
&& let Ok(read_quorum) = usize::try_from(read_quorum)
&& reduce_read_quorum_errs(&candidate_errs, OBJECT_OP_IGNORED_ERRS, read_quorum).is_none()
&& let Ok((online_disks, fi)) =
Self::select_valid_fileinfo(disks, &candidate_metadata, &candidate_errs, read_quorum)
{
return Some(IncompleteOverwriteResolution {
online_disks,
fi,
parts_metadata: candidate_metadata,
rollbacks,
});
}
}
None
}
async fn load_overwrite_rollback_backup_on_disk(
disk: &DiskStore,
bucket: &str,
object: &str,
disk_object: &str,
live_fi: &FileInfo,
read_data: bool,
include_part_checksums: bool,
) -> Option<Option<(Uuid, FileInfo)>> {
let entries = match disk.list_dir("", bucket, disk_object, -1).await {
Ok(entries) => entries,
Err(
DiskError::FileNotFound | DiskError::FileVersionNotFound | DiskError::PathNotFound | DiskError::VolumeNotFound,
) => return Some(None),
Err(_) => return None,
};
let live_key = Self::file_info_quorum_key(live_fi);
let mut best: Option<(Uuid, FileInfo)> = None;
for entry in entries {
if !entry.ends_with(SLASH_SEPARATOR) {
continue;
}
let Ok(candidate_dir) = Uuid::parse_str(entry.trim_end_matches(SLASH_SEPARATOR)) else {
continue;
};
let sub_path = format!("{disk_object}{SLASH_SEPARATOR}{candidate_dir}");
let sub_entries = match disk.list_dir("", bucket, &sub_path, -1).await {
Ok(sub_entries) => sub_entries,
Err(
DiskError::FileNotFound
| DiskError::FileVersionNotFound
| DiskError::PathNotFound
| DiskError::VolumeNotFound,
) => continue,
Err(_) => return None,
};
if !sub_entries.iter().any(|name| name == crate::disk::STORAGE_FORMAT_FILE_BACKUP) {
continue;
}
if sub_entries.iter().any(|name| {
let trimmed = name.trim_end_matches(SLASH_SEPARATOR);
matches!(
trimmed,
"delete-prepared"
| "delete-target"
| "delete-commit-finished"
| crate::disk::local::DELETE_QUORUM_COMMITTED_FILE
| "xl.meta.delete-marker.rollback"
)
}) {
continue;
}
let bkp_path = format!("{sub_path}{SLASH_SEPARATOR}{}", crate::disk::STORAGE_FORMAT_FILE_BACKUP);
let bkp_bytes = match disk.read_all(bucket, &bkp_path).await {
Ok(bytes) => bytes,
Err(
DiskError::FileNotFound
| DiskError::FileVersionNotFound
| DiskError::PathNotFound
| DiskError::VolumeNotFound,
) => continue,
Err(_) => return None,
};
let Ok(bkp_meta) = rustfs_filemeta::FileMeta::load(&bkp_bytes) else {
continue;
};
let expected_dir = bkp_meta
.find_unshared_data_dir_for_version(Some(Uuid::nil()))
.unwrap_or_else(|| crate::disk::local::inline_metadata_rollback_dir(Uuid::nil(), &bkp_meta));
if expected_dir != candidate_dir {
continue;
}
let Ok(mut bkp_fi) = rustfs_filemeta::get_file_info(
&bkp_bytes,
bucket,
object,
"",
rustfs_filemeta::FileInfoOpts {
data: read_data,
include_free_versions: false,
include_part_checksums,
},
) else {
continue;
};
if bkp_fi.validate_for_metadata_read().is_err() {
continue;
}
if read_data
&& (bkp_fi.data.as_ref().is_some_and(|d| !d.is_empty()) || bkp_fi.size == 0)
&& !bkp_fi.inline_data()
&& (bkp_fi.size == 0 || bkp_fi.version_id.is_none_or(|v| v.is_nil()))
{
bkp_fi.set_inline_data();
}
if !file_info_is_valid_for_metadata(&bkp_fi)
|| bkp_fi.mod_time > live_fi.mod_time
|| Self::file_info_quorum_key(&bkp_fi) == live_key
{
continue;
}
if !bkp_fi.deleted && !bkp_fi.is_remote() && !bkp_fi.inline_data() && bkp_fi.size > 0 {
match disk.check_parts(bucket, object, &bkp_fi).await {
Ok(resp)
if !resp.results.is_empty() && resp.results.iter().all(|res| *res == crate::disk::CHECK_PART_SUCCESS) => {
}
Ok(_)
| Err(
DiskError::FileNotFound
| DiskError::FileVersionNotFound
| DiskError::PathNotFound
| DiskError::VolumeNotFound,
) => continue,
Err(_) => return None,
}
}
if best.as_ref().is_none_or(|(_, prev)| bkp_fi.mod_time > prev.mod_time) {
best = Some((candidate_dir, bkp_fi));
}
}
Some(best)
}
pub(crate) fn hydrate_selected_fileinfo_part_checksums(fi: &mut FileInfo) -> disk::error::Result<()> {
fi.hydrate_shard_integrity().map_err(DiskError::from)?;
fi.hydrate_data_movement_part_checksums().map_err(DiskError::from)?;
+5 -119
View File
@@ -391,33 +391,6 @@ struct ObjectLockDiagGuard {
mode: &'static str,
acquired_at: Instant,
_attempt: ObjectLockAttempt,
_local_writer_gate: Option<tokio::sync::OwnedMutexGuard<()>>,
}
type PutCommitKeyGateKey = (String, String, String);
type PutCommitKeyGateMap = HashMap<PutCommitKeyGateKey, std::sync::Weak<tokio::sync::Mutex<()>>>;
static LOCAL_PUT_COMMIT_KEY_GATES: std::sync::LazyLock<std::sync::Mutex<PutCommitKeyGateMap>> =
std::sync::LazyLock::new(|| std::sync::Mutex::new(HashMap::new()));
fn local_put_commit_key_gate(namespace: &str, bucket: &str, object: &str) -> Arc<tokio::sync::Mutex<()>> {
let key = (
namespace.to_string(),
bucket.to_string(),
rustfs_utils::path::object_name_disk_identity(object).into_owned(),
);
let mut gates = LOCAL_PUT_COMMIT_KEY_GATES
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(existing) = gates.get(&key).and_then(std::sync::Weak::upgrade) {
return existing;
}
if gates.len() > 4096 {
gates.retain(|_, weak| weak.strong_count() > 0);
}
let created = Arc::new(tokio::sync::Mutex::new(()));
gates.insert(key, Arc::downgrade(&created));
created
}
impl ObjectLockDiagGuard {
@@ -440,7 +413,6 @@ impl ObjectLockDiagGuard {
mode,
acquired_at: Instant::now(),
_attempt: ObjectLockAttempt::default(),
_local_writer_gate: None,
}
}
@@ -449,11 +421,6 @@ impl ObjectLockDiagGuard {
self
}
fn with_local_writer_gate(mut self, gate: Option<tokio::sync::OwnedMutexGuard<()>>) -> Self {
self._local_writer_gate = gate;
self
}
/// Whether the underlying namespace lock's heartbeat has observed a
/// refresh-quorum loss (backlog#899 Phase 2). Callers fence their commit
/// point on this so a stale lock holder does not race a double-write.
@@ -5602,13 +5569,7 @@ impl SetDisks {
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let acquire_start = Instant::now();
let mut timeout = get_lock_acquire_timeout();
if op == "get_object_info"
&& self.ctx.is_dist_erasure().await
&& rustfs_utils::get_env_opt_str(rustfs_config::ENV_OBJECT_LOCK_ACQUIRE_TIMEOUT).is_none()
{
timeout = timeout.max(Duration::from_secs(8));
}
let timeout = get_lock_acquire_timeout();
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "read", timeout);
let result = ns_lock.get_read_lock(timeout).await;
if let Err(error) = &result {
@@ -5630,88 +5591,14 @@ impl SetDisks {
.with_attempt(attempt))
}
async fn acquire_dist_put_commit_write_lock(
&self,
ns_lock: &NamespaceLockWrapper,
bucket: &str,
object: &str,
acquire_start: Instant,
acquire_timeout: Duration,
) -> std::result::Result<NamespaceLockGuard, rustfs_lock::error::LockError> {
use std::hash::{Hash, Hasher};
const SPLIT_VOTE_BUDGETS_MS: [u64; 3] = [120, 240, 480];
let mut hasher = std::collections::hash_map::DefaultHasher::new();
ns_lock.owner().hash(&mut hasher);
let owner_jitter_ms = (hasher.finish() % 4).saturating_mul(8);
let mut round = 0usize;
loop {
let remaining = acquire_timeout.saturating_sub(acquire_start.elapsed());
if remaining.is_zero() {
return Err(rustfs_lock::LockError::timeout(format!("{bucket}/{object}"), acquire_timeout));
}
let round_budget = SPLIT_VOTE_BUDGETS_MS
.get(round)
.map(|&ms| Duration::from_millis(ms).min(remaining))
.unwrap_or(remaining);
match ns_lock.get_write_lock(round_budget).await {
Ok(guard) => return Ok(guard),
Err(err @ (rustfs_lock::LockError::Timeout { .. } | rustfs_lock::LockError::AlreadyLocked { .. })) => {
let after_elapsed = acquire_start.elapsed();
if after_elapsed >= acquire_timeout {
return Err(err);
}
let left = acquire_timeout.saturating_sub(after_elapsed);
let rand_jitter_ms = (u64::from(rand::random::<u8>()) % 13).saturating_add(4);
let backoff = Duration::from_millis(owner_jitter_ms.saturating_add(rand_jitter_ms)).min(left / 4);
if !backoff.is_zero() {
tokio::time::sleep(backoff).await;
}
round = round.saturating_add(1);
}
Err(err) => return Err(err),
}
}
}
async fn acquire_write_lock_diag(&self, op: &'static str, bucket: &str, object: &str) -> Result<ObjectLockDiagGuard> {
crate::hp_guard!("SetDisks::acquire_write_lock");
let diag_enabled = is_object_lock_diag_enabled();
let ns_lock = self.new_ns_lock(bucket, object).await?;
let acquire_start = Instant::now();
let mut acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let dist_erasure = self.ctx.is_dist_erasure().await;
if op == "put_object_commit"
&& dist_erasure
&& !put_object_commit_lock_timeout_override_enabled(op)
&& rustfs_utils::get_env_opt_str(rustfs_config::ENV_OBJECT_LOCK_ACQUIRE_TIMEOUT).is_none()
{
acquire_timeout = acquire_timeout.max(Duration::from_secs(8));
}
let local_writer_gate = if op == "put_object_commit" && dist_erasure {
let gate = local_put_commit_key_gate(&self.set_lock_namespace, bucket, object);
match tokio::time::timeout(acquire_timeout, gate.lock_owned()).await {
Ok(guard) => Some(guard),
Err(_) => {
let err = rustfs_lock::LockError::timeout(format!("{bucket}/{object}"), acquire_timeout);
record_lock_acquire_failure(op, bucket, object, "write", &err);
record_put_object_commit_lock_admission(op, put_object_commit_lock_acquire_error_outcome(op, &err));
return Err(map_put_object_commit_lock_acquire_error(self, op, bucket, object, err));
}
}
} else {
None
};
let remaining_timeout = acquire_timeout.saturating_sub(acquire_start.elapsed());
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", remaining_timeout);
let result = if op == "put_object_commit" && dist_erasure && !put_object_commit_lock_timeout_override_enabled(op) {
self.acquire_dist_put_commit_write_lock(&ns_lock, bucket, object, acquire_start, acquire_timeout)
.await
} else {
ns_lock.get_write_lock(remaining_timeout).await
};
let acquire_timeout = get_put_object_commit_lock_acquire_timeout(op);
let mut attempt = ObjectLockAttempt::start(op, bucket, object, None, &ns_lock, "write", acquire_timeout);
let result = ns_lock.get_write_lock(acquire_timeout).await;
if let Err(error) = &result {
record_lock_acquire_failure(op, bucket, object, "write", error);
}
@@ -5737,8 +5624,7 @@ impl SetDisks {
owner,
"write",
)
.with_attempt(attempt)
.with_local_writer_gate(local_writer_gate))
.with_attempt(attempt))
}
#[cfg(any(test, feature = "test-util"))]
@@ -917,29 +917,6 @@ impl SetDisks {
self.recover_delete_key(bucket, object, context).await
}
/// Fast-path check used while holding the key's write and transaction locks:
/// returns `true` only when every drive in the set is online and reports zero
/// pending delete recovery transactions for `bucket/object`.
pub(in crate::set_disk) async fn has_no_pending_delete_recovery_transactions(
&self,
bucket: &str,
object: &str,
work_budget: Option<&crate::object_api::DeleteRecoveryWorkBudget>,
) -> bool {
let disks = self.disk_inventory().await;
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
return false;
}
let pages = join_all(disks.iter().flatten().map(|disk| async {
match work_budget {
Some(budget) => discover_bounded(disk, bucket, object, budget).await,
None => discover(disk, bucket, Some(object)).await,
}
}))
.await;
pages.into_iter().all(|page| matches!(page, Ok(ids) if ids.is_empty()))
}
/// Caller retains the exact key's write lock and its lifecycle owner.
pub(in crate::set_disk) async fn recover_delete_key(
&self,
+2 -672
View File
@@ -35,7 +35,6 @@ mod heal_lock_wait_tests;
struct ExplicitVersionHeal<'a> {
opts: &'a HealOpts,
allow_regeneration: bool,
allow_incomplete_overwrite_rollback: bool,
preserve_unrepairable: bool,
commit_fence: Option<&'a (dyn Fn() -> bool + Sync)>,
namespace_owner: Option<&'a Arc<dyn Send + Sync>>,
@@ -938,7 +937,6 @@ impl SetDisks {
ExplicitVersionHeal {
opts,
allow_regeneration: true,
allow_incomplete_overwrite_rollback: true,
preserve_unrepairable: false,
commit_fence: None,
namespace_owner: None,
@@ -1089,7 +1087,6 @@ impl SetDisks {
let ExplicitVersionHeal {
opts,
allow_regeneration: allow_explicit_version_regen,
allow_incomplete_overwrite_rollback,
preserve_unrepairable,
commit_fence,
namespace_owner,
@@ -2309,87 +2306,7 @@ impl SetDisks {
Ok((result, None))
}
Err(err) => {
if err == DiskError::ErasureReadQuorum
&& !opts.dry_run
&& allow_incomplete_overwrite_rollback
&& self.may_have_incomplete_null_overwrite(bucket, version_id, &disks, &parts_metadata, &errs)
{
let mut upgraded_write_guard = None;
let mut active_errs = errs.clone();
if read_repair_uses_shared_lock {
drop(_read_repair_read_lock_guard.take());
let guard = Arc::new(
self.acquire_heal_object_lock(
bucket,
object,
version_id,
HealObjectLockKind::Write,
"heal_object_overwrite_rollback",
)
.await?,
);
upgraded_write_guard = Some(guard);
let (fresh_meta, fresh_errs, _) =
Self::read_metadata(&disks, "", bucket, object, version_id, true, true, false)
.await?
.into_legacy();
parts_metadata = fresh_meta;
active_errs = fresh_errs;
}
let active_guard = upgraded_write_guard.as_ref().or(_write_lock_guard.as_ref());
let undo_owner: Arc<dyn Send + Sync> = Arc::new((
namespace_owner.cloned(),
active_guard.cloned(),
bucket_heal_scope.clone(),
self.ctx.begin_namespace_commit_for_bucket(bucket),
));
let recovered = self
.try_recover_incomplete_overwrite_meta(
bucket,
object,
version_id,
&parts_metadata,
&active_errs,
&disks,
commit_fence,
Some(undo_owner),
)
.await?;
if recovered {
if active_guard.is_some_and(|guard| guard.is_lock_lost()) {
return Err(DiskError::DiskOngoingReq);
}
let retry_opts = HealOpts {
no_lock: true,
read_repair: false,
..*opts
};
let retry_commit_fence = || {
commit_fence.is_none_or(|check| check())
&& !active_guard.is_some_and(|guard| guard.is_lock_lost())
};
let retry_namespace_owner: Arc<dyn Send + Sync> =
Arc::new((namespace_owner.cloned(), active_guard.cloned()));
return Box::pin(self.heal_object_with_explicit_version_regen(
bucket,
object,
version_id,
ExplicitVersionHeal {
opts: &retry_opts,
allow_regeneration: false,
allow_incomplete_overwrite_rollback: false,
commit_fence: Some(&retry_commit_fence),
namespace_owner: Some(&retry_namespace_owner),
..run
},
absence,
))
.await;
}
}
Ok((result, Some(err)))
}
Err(err) => Ok((result, Some(err))),
}
}
Err(err) => {
@@ -2458,85 +2375,8 @@ impl SetDisks {
))
.await;
}
if err == DiskError::ErasureReadQuorum
&& !opts.dry_run
&& allow_incomplete_overwrite_rollback
&& self.may_have_incomplete_null_overwrite(bucket, version_id, &disks, &parts_metadata, &errs)
{
let mut upgraded_write_guard = None;
let mut active_errs = errs.clone();
if read_repair_uses_shared_lock {
drop(_read_repair_read_lock_guard.take());
let guard = Arc::new(
self.acquire_heal_object_lock(
bucket,
object,
version_id,
HealObjectLockKind::Write,
"heal_object_overwrite_rollback",
)
.await?,
);
upgraded_write_guard = Some(guard);
let (fresh_meta, fresh_errs, _) =
Self::read_metadata(&disks, "", bucket, object, version_id, true, true, false)
.await?
.into_legacy();
parts_metadata = fresh_meta;
active_errs = fresh_errs;
}
let active_guard = upgraded_write_guard.as_ref().or(_write_lock_guard.as_ref());
let undo_owner: Arc<dyn Send + Sync> = Arc::new((
namespace_owner.cloned(),
active_guard.cloned(),
bucket_heal_scope.clone(),
self.ctx.begin_namespace_commit_for_bucket(bucket),
));
let recovered = self
.try_recover_incomplete_overwrite_meta(
bucket,
object,
version_id,
&parts_metadata,
&active_errs,
&disks,
commit_fence,
Some(undo_owner),
)
.await?;
if recovered {
if active_guard.is_some_and(|guard| guard.is_lock_lost()) {
return Err(DiskError::DiskOngoingReq);
}
let retry_opts = HealOpts {
no_lock: true,
read_repair: false,
..*opts
};
let retry_commit_fence = || {
commit_fence.is_none_or(|check| check()) && !active_guard.is_some_and(|guard| guard.is_lock_lost())
};
let retry_namespace_owner: Arc<dyn Send + Sync> =
Arc::new((namespace_owner.cloned(), active_guard.cloned()));
return Box::pin(self.heal_object_with_explicit_version_regen(
bucket,
object,
version_id,
ExplicitVersionHeal {
opts: &retry_opts,
allow_regeneration: false,
allow_incomplete_overwrite_rollback: false,
commit_fence: Some(&retry_commit_fence),
namespace_owner: Some(&retry_namespace_owner),
..run
},
absence,
))
.await;
}
}
if opts.dry_run || read_repair_uses_shared_lock || preserve_unrepairable || !opts.remove {
if opts.dry_run || preserve_unrepairable || !opts.remove {
return Ok((
self.default_heal_result(FileInfo::default(), &errs, bucket, object, version_id)
.await,
@@ -2809,57 +2649,6 @@ impl SetDisks {
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn try_recover_incomplete_overwrite_meta(
&self,
bucket: &str,
object: &str,
version_id: &str,
parts_metadata: &[FileInfo],
errs: &[Option<DiskError>],
disks: &[Option<DiskStore>],
commit_fence: Option<&(dyn Fn() -> bool + Sync)>,
undo_owner: Option<Arc<dyn Send + Sync>>,
) -> disk::error::Result<bool> {
if !self.may_have_incomplete_null_overwrite(bucket, version_id, disks, parts_metadata, errs) {
return Ok(false);
}
let Some(resolution) = self
.discover_incomplete_overwrite_rollbacks(disks, bucket, object, version_id, parts_metadata, errs, false, false)
.await
else {
return Ok(false);
};
if resolution.rollbacks.is_empty() {
return Ok(false);
}
if commit_fence.is_some_and(|check| !check()) {
return Err(DiskError::DiskOngoingReq);
}
for rollback in resolution.rollbacks {
if commit_fence.is_some_and(|check| !check()) {
return Err(DiskError::DiskOngoingReq);
}
let Some(disk) = disks.get(rollback.slot_index).and_then(Option::as_ref) else {
return Err(DiskError::DiskNotFound);
};
disk.undo_write_with_namespace_owner(
bucket,
object,
rollback.undo_file_info,
DeleteOptions {
undo_write: true,
old_data_dir: Some(rollback.rollback_dir),
..Default::default()
},
undo_owner.clone(),
)
.await?;
}
self.invalidate_get_object_metadata_cache(bucket, object).await;
Ok(true)
}
async fn try_regenerate_explicit_version_meta(
&self,
bucket: &str,
@@ -3940,7 +3729,6 @@ impl SetDisks {
ExplicitVersionHeal {
opts: &opts,
allow_regeneration: false,
allow_incomplete_overwrite_rollback: false,
preserve_unrepairable: true,
commit_fence: Some(can_commit),
namespace_owner,
@@ -3998,7 +3786,6 @@ impl SetDisks {
ExplicitVersionHeal {
opts: &read_opts,
allow_regeneration: false,
allow_incomplete_overwrite_rollback: true,
preserve_unrepairable: true,
commit_fence: Some(&can_commit),
namespace_owner: None,
@@ -4226,7 +4013,6 @@ impl SetDisks {
ExplicitVersionHeal {
opts: &inner_opts,
allow_regeneration: true,
allow_incomplete_overwrite_rollback: true,
preserve_unrepairable: false,
commit_fence: Some(&commit_fence),
namespace_owner: namespace_owner.as_ref(),
@@ -4251,7 +4037,6 @@ impl SetDisks {
ExplicitVersionHeal {
opts: &inner_opts,
allow_regeneration: true,
allow_incomplete_overwrite_rollback: true,
preserve_unrepairable: false,
commit_fence: Some(&commit_fence),
namespace_owner: namespace_owner.as_ref(),
@@ -7107,7 +6892,6 @@ mod heal_result_report_tests {
ExplicitVersionHeal {
opts: &opts,
allow_regeneration: true,
allow_incomplete_overwrite_rollback: true,
preserve_unrepairable: false,
commit_fence: Some(&can_commit),
namespace_owner: None,
@@ -12788,458 +12572,4 @@ mod shard_identity_tests {
}
}
}
#[tokio::test]
async fn incomplete_null_overwrite_rollback_recovers_read_and_heal_without_resurrecting_committed_write() {
use crate::set_disk::{STORAGE_FORMAT_FILE, StorageError, Uuid};
for (label, v1, v2, v3) in [
("inline", vec![0x11; 138], vec![0x22; 138], vec![0x33; 138]),
(
"non-inline",
vec![0x11; 1024 * 1024 + 137],
vec![0x22; 1024 * 1024 + 137],
vec![0x33; 1024 * 1024 + 137],
),
] {
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
let bucket = format!("incomplete-overwrite-{label}");
let object = "coh-copy-0";
for disk in &disks {
disk.make_volume(&bucket).await.expect("bucket");
}
let opts = ObjectOptions {
no_lock: true,
metadata_cache_safe: false,
..Default::default()
};
// 1. V1 commits across all 6 drives.
set.put_object(&bucket, object, &mut PutObjReader::from_vec(v1.clone()), &opts)
.await
.expect("PUT V1");
let mut v1_metas = Vec::new();
for dir in &dirs {
v1_metas.push(
tokio::fs::read(dir.path().join(&bucket).join(object).join(STORAGE_FORMAT_FILE))
.await
.expect("read V1 xl.meta"),
);
}
// 2. V2 commits across drives 0..4 (write_quorum = 4), while drives 4..6 stay on stale V1.
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
set.put_object(&bucket, object, &mut PutObjReader::from_vec(v2.clone()), &opts)
.await
.expect("PUT V2");
let mut v2_metas = Vec::new();
let mut v2_parts = Vec::new();
for (idx, dir) in dirs.iter().enumerate() {
let obj_dir = dir.path().join(&bucket).join(object);
let bytes = tokio::fs::read(obj_dir.join(STORAGE_FORMAT_FILE))
.await
.expect("read V2 xl.meta");
let fm = rustfs_filemeta::FileMeta::load(&bytes).expect("parse V2 xl.meta");
let old_dir = fm.find_unshared_data_dir_for_version(Some(Uuid::nil()));
let saved_part = if let Some(d) = old_dir {
Some((
d,
tokio::fs::read(obj_dir.join(d.to_string()).join("part.1"))
.await
.expect("read V2 part.1"),
))
} else {
None
};
v2_metas.push((bytes, fm));
v2_parts.push(saved_part);
if idx >= 4 {
tokio::fs::write(obj_dir.join(STORAGE_FORMAT_FILE), &v1_metas[idx])
.await
.expect("keep drives 4..6 on V1");
}
}
// 3. V3 attempts an overwrite, publishes only on drives 2..4 (< write_quorum = 4) with
// preserved `<rollback_dir>/xl.meta.bkp` of V2, while drives 0..2 stay on V2 and
// drives 4..6 stay on V1 (exact 2-2-2 split!).
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
set.put_object(&bucket, object, &mut PutObjReader::from_vec(v3.clone()), &opts)
.await
.expect("stage V3");
set.invalidate_get_object_metadata_cache(&bucket, object).await;
for idx in 0..2 {
let obj_dir = dirs[idx].path().join(&bucket).join(object);
tokio::fs::write(obj_dir.join(STORAGE_FORMAT_FILE), &v2_metas[idx].0)
.await
.expect("restore V2 on drives 0..2");
if let Some((d, part_bytes)) = &v2_parts[idx] {
let d_path = obj_dir.join(d.to_string());
tokio::fs::create_dir_all(&d_path).await.expect("recreate V2 data dir");
tokio::fs::write(d_path.join("part.1"), part_bytes)
.await
.expect("restore V2 part.1 on drives 0..2");
}
}
for idx in 4..6 {
let obj_dir = dirs[idx].path().join(&bucket).join(object);
tokio::fs::write(obj_dir.join(STORAGE_FORMAT_FILE), &v1_metas[idx])
.await
.expect("restore V1 on drives 4..6");
}
let mut backup_paths = Vec::new();
for idx in 2..4 {
let obj_dir = dirs[idx].path().join(&bucket).join(object);
let rollback_dir = v2_metas[idx]
.1
.find_unshared_data_dir_for_version(Some(Uuid::nil()))
.unwrap_or_else(|| crate::disk::local::inline_metadata_rollback_dir(Uuid::nil(), &v2_metas[idx].1));
let r_path = obj_dir.join(rollback_dir.to_string());
tokio::fs::create_dir_all(&r_path).await.expect("create rollback dir");
if let Some((_, part_bytes)) = &v2_parts[idx] {
tokio::fs::write(r_path.join("part.1"), part_bytes)
.await
.expect("preserve V2 part.1 prior to post-quorum cleanup");
}
let bkp_path = r_path.join(crate::disk::STORAGE_FORMAT_FILE_BACKUP);
tokio::fs::write(&bkp_path, &v2_metas[idx].0)
.await
.expect("preserve V2 xl.meta.bkp");
backup_paths.push(bkp_path);
}
// Negative safety gate: if a drive is offline (incomplete set visibility), read must NOT
// roll back V3 because V3 could have committed on the offline drives.
{
let saved = set.disks.write().await[5].take();
let res = set
.get_object_info(
&bucket,
object,
&ObjectOptions {
suppress_read_repair: true,
..opts.clone()
},
)
.await;
set.disks.write().await[5] = saved;
assert!(
matches!(res, Err(StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(..))),
"{label}: offline set must fail closed with read quorum error, got {res:?}"
);
}
// Positive read gate (before heal runs): GET and HEAD serve committed V2 immediately.
let info = set
.get_object_info(
&bucket,
object,
&ObjectOptions {
suppress_read_repair: true,
..opts.clone()
},
)
.await
.expect("HEAD must resolve past uncommitted V3 to V2");
assert_eq!(info.size as usize, v2.len(), "{label}: HEAD size");
let mut reader = set
.get_object_reader(
&bucket,
object,
None,
Default::default(),
&ObjectOptions {
suppress_read_repair: true,
..opts.clone()
},
)
.await
.expect("GET must resolve past uncommitted V3 to V2");
let mut body = Vec::new();
reader.stream.read_to_end(&mut body).await.expect("read V2 body");
assert_eq!(body, v2, "{label}: GET body before heal");
// Positive heal gate: heal rolls back V3 on drives 2..4, repairs drives 4..6 to V2,
// and consumes all preserved `xl.meta.bkp` files.
let (_, heal_err) = set
.heal_object(
&bucket,
object,
"",
&HealOpts {
no_lock: true,
scan_mode: HealScanMode::Normal,
..Default::default()
},
)
.await
.expect("heal split set");
assert!(heal_err.is_none(), "{label}: heal error {heal_err:?}");
for bkp in &backup_paths {
assert!(!bkp.exists(), "{label}: heal must consume rollback backup {bkp:?}");
}
let mut post_reader = set
.get_object_reader(&bucket, object, None, Default::default(), &opts)
.await
.expect("GET after heal");
let mut post_body = Vec::new();
post_reader.stream.read_to_end(&mut post_body).await.expect("post-heal body");
assert_eq!(post_body, v2, "{label}: GET body after heal");
}
}
#[tokio::test]
async fn incomplete_null_overwrite_rollback_fails_closed_when_replacement_drives_missing_metadata() {
use crate::set_disk::{AbsenceProofRequest, STORAGE_FORMAT_FILE, StorageError, Uuid};
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
let bucket = "incomplete-overwrite-replacement-drive";
let object = "coh-copy-replacement";
for disk in &disks {
disk.make_volume(bucket).await.expect("bucket");
}
let opts = ObjectOptions {
no_lock: true,
metadata_cache_safe: false,
..Default::default()
};
let v1 = vec![0x11; 138];
let v2 = vec![0x22; 138];
// 1. V1 commits across all 6 drives.
set.put_object(bucket, object, &mut PutObjReader::from_vec(v1), &opts)
.await
.expect("PUT V1");
let mut v1_metas = Vec::new();
for dir in &dirs {
let bytes = tokio::fs::read(dir.path().join(bucket).join(object).join(STORAGE_FORMAT_FILE))
.await
.expect("read V1 xl.meta");
let fm = rustfs_filemeta::FileMeta::load(&bytes).expect("parse V1 xl.meta");
v1_metas.push((bytes, fm));
}
// 2. V2 commits across drives 0..4 (write_quorum = 4), while drives 4..6 stay on V1.
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
set.put_object(bucket, object, &mut PutObjReader::from_vec(v2), &opts)
.await
.expect("PUT V2");
set.invalidate_get_object_metadata_cache(bucket, object).await;
// Drives 4..6 stay on V1; drives 2..4 keep V2 with surviving V1 rollback backups;
// drives 0..2 simulate freshly replaced drives returning FileNotFound.
let mut v2_meta_before = Vec::new();
let mut backup_paths = Vec::new();
for idx in 2..4 {
let obj_dir = dirs[idx].path().join(bucket).join(object);
v2_meta_before.push(
tokio::fs::read(obj_dir.join(STORAGE_FORMAT_FILE))
.await
.expect("read V2 xl.meta"),
);
let rollback_dir = v1_metas[idx]
.1
.find_unshared_data_dir_for_version(Some(Uuid::nil()))
.unwrap_or_else(|| crate::disk::local::inline_metadata_rollback_dir(Uuid::nil(), &v1_metas[idx].1));
let r_path = obj_dir.join(rollback_dir.to_string());
tokio::fs::create_dir_all(&r_path).await.expect("create V1 rollback dir");
let bkp_path = r_path.join(crate::disk::STORAGE_FORMAT_FILE_BACKUP);
tokio::fs::write(&bkp_path, &v1_metas[idx].0)
.await
.expect("preserve surviving V1 xl.meta.bkp");
backup_paths.push(bkp_path);
}
for idx in 4..6 {
let obj_dir = dirs[idx].path().join(bucket).join(object);
tokio::fs::write(obj_dir.join(STORAGE_FORMAT_FILE), &v1_metas[idx].0)
.await
.expect("keep drives 4..6 on V1");
}
for idx in 0..2 {
tokio::fs::remove_dir_all(dirs[idx].path().join(bucket).join(object))
.await
.expect("blank replaced drives 0..2");
}
// Neither read nor heal may roll back acknowledged V2 to V1 when any member is missing.
let read_res = set
.get_object_info(
bucket,
object,
&ObjectOptions {
suppress_read_repair: true,
..opts.clone()
},
)
.await;
assert!(
matches!(read_res, Err(StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(..))),
"replacement-drive missing metadata must fail closed on read, got {read_res:?}"
);
let (_, heal_err) = set
.heal_object_with_retirement(
bucket,
object,
"",
&HealOpts {
no_lock: true,
scan_mode: HealScanMode::Normal,
..Default::default()
},
&mut None,
AbsenceProofRequest {
retirement: None,
allow_unversioned: false,
},
)
.await
.expect("heal should fail closed rather than panic");
assert!(
matches!(heal_err, Some(crate::error::Error::ErasureReadQuorum)),
"replacement-drive missing metadata must fail closed on heal, got {heal_err:?}"
);
for (offset, idx) in (2..4).enumerate() {
let current_meta = tokio::fs::read(dirs[idx].path().join(bucket).join(object).join(STORAGE_FORMAT_FILE))
.await
.expect("read V2 xl.meta after fail-closed heal");
assert_eq!(
current_meta, v2_meta_before[offset],
"committed V2 metadata on drive {idx} must never be rolled back to V1"
);
assert!(
backup_paths[offset].exists(),
"rollback backup on drive {idx} must remain untouched on fail-closed heal"
);
}
}
#[tokio::test]
async fn incomplete_null_overwrite_rollback_recovers_via_read_repair_entry_point() {
use crate::set_disk::{AbsenceProofRequest, STORAGE_FORMAT_FILE, Uuid};
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
let bucket = "incomplete-overwrite-read-repair";
let object = "coh-copy-read-repair";
for disk in &disks {
disk.make_volume(bucket).await.expect("bucket");
}
let opts = ObjectOptions {
no_lock: true,
metadata_cache_safe: false,
..Default::default()
};
let v1 = vec![0x11; 138];
let v2 = vec![0x22; 138];
let v3 = vec![0x33; 138];
// 1. V1 commits on all 6 drives.
set.put_object(bucket, object, &mut PutObjReader::from_vec(v1), &opts)
.await
.expect("PUT V1");
let mut v1_metas = Vec::new();
for dir in &dirs {
v1_metas.push(
tokio::fs::read(dir.path().join(bucket).join(object).join(STORAGE_FORMAT_FILE))
.await
.expect("read V1 xl.meta"),
);
}
// 2. V2 commits across drives 0..4 while drives 4..6 remain on V1.
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
set.put_object(bucket, object, &mut PutObjReader::from_vec(v2.clone()), &opts)
.await
.expect("PUT V2");
let mut v2_metas = Vec::new();
for dir in &dirs {
let bytes = tokio::fs::read(dir.path().join(bucket).join(object).join(STORAGE_FORMAT_FILE))
.await
.expect("read V2 xl.meta");
let fm = rustfs_filemeta::FileMeta::load(&bytes).expect("parse V2 xl.meta");
v2_metas.push((bytes, fm));
}
// 3. Uncommitted V3 lands on drives 2..4 with V2 rollback backups, leaving a 2-2-2 split.
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
set.put_object(bucket, object, &mut PutObjReader::from_vec(v3), &opts)
.await
.expect("stage V3");
set.invalidate_get_object_metadata_cache(bucket, object).await;
for idx in 0..2 {
tokio::fs::write(dirs[idx].path().join(bucket).join(object).join(STORAGE_FORMAT_FILE), &v2_metas[idx].0)
.await
.expect("restore V2 on drives 0..2");
}
for idx in 4..6 {
tokio::fs::write(dirs[idx].path().join(bucket).join(object).join(STORAGE_FORMAT_FILE), &v1_metas[idx])
.await
.expect("restore V1 on drives 4..6");
}
let mut backup_paths = Vec::new();
for idx in 2..4 {
let obj_dir = dirs[idx].path().join(bucket).join(object);
let rollback_dir = v2_metas[idx]
.1
.find_unshared_data_dir_for_version(Some(Uuid::nil()))
.unwrap_or_else(|| crate::disk::local::inline_metadata_rollback_dir(Uuid::nil(), &v2_metas[idx].1));
let r_path = obj_dir.join(rollback_dir.to_string());
tokio::fs::create_dir_all(&r_path).await.expect("create rollback dir");
let bkp_path = r_path.join(crate::disk::STORAGE_FORMAT_FILE_BACKUP);
tokio::fs::write(&bkp_path, &v2_metas[idx].0)
.await
.expect("preserve V2 xl.meta.bkp");
backup_paths.push(bkp_path);
}
// Exercise the exact read-repair entry point (`heal_object_with_retirement` with
// `read_repair: true, no_lock: false`), which previously set `allow_regeneration: false`.
let (_, heal_err) = set
.heal_object_with_retirement(
bucket,
object,
"",
&HealOpts {
read_repair: true,
no_lock: false,
scan_mode: HealScanMode::Normal,
..Default::default()
},
&mut None,
AbsenceProofRequest {
retirement: None,
allow_unversioned: false,
},
)
.await
.expect("read-repair heal on split set");
assert!(heal_err.is_none(), "read-repair heal error: {heal_err:?}");
for bkp in &backup_paths {
assert!(!bkp.exists(), "read-repair must consume rollback backup {bkp:?}");
}
let mut post_reader = set
.get_object_reader(
bucket,
object,
None,
Default::default(),
&ObjectOptions {
suppress_read_repair: true,
..opts
},
)
.await
.expect("GET after read-repair");
let mut post_body = Vec::new();
post_reader
.stream
.read_to_end(&mut post_body)
.await
.expect("post-read-repair body");
assert_eq!(post_body, v2, "read-repair must recover committed V2");
}
}
+3 -27
View File
@@ -447,21 +447,19 @@ impl SetDisks {
let mut reconnects = stream::iter(disks.into_iter().enumerate())
.map(|(i, opdisk)| async move {
if let Some(disk) = opdisk {
let local_retired = disk.local_retirement_token().is_some_and(|token| token.is_cancelled());
if !local_retired
&& !active_monitoring
if !active_monitoring
&& disk.get_disk_location().set_idx.is_some()
&& let disk::Disk::Local(local) = disk.as_ref()
&& local.can_skip_background_probe().await
{
return None;
}
if !local_retired && disk.is_online().await && disk.get_disk_location().set_idx.is_some() {
if disk.is_online().await && disk.get_disk_location().set_idx.is_some() {
return None;
}
// A failed remote reconnect must retain its existing recovery monitor.
if disk.is_local() && !local_retired {
if disk.is_local() {
let _ = disk.close().await;
}
}
@@ -1317,28 +1315,6 @@ mod tests {
assert!(Arc::ptr_eq(&registered, renewed_again));
assert!(!current.retirement_token().is_cancelled());
// Simulate a transient drive fault where a failed reconnect attempt
// retired the attached local wrapper before the underlying directory
// became accessible again and runtime health returned to Online.
renewed_again.close().await.expect("retire attached local wrapper");
assert!(current.retirement_token().is_cancelled());
assert!(renewed_again.is_online().await);
set_disks.connect_disks_with_active_monitoring(false).await;
let disks_after_recover = set_disks.get_disks_internal().await;
let recovered = disks_after_recover[0]
.as_ref()
.expect("connect_disks must replace a retired local wrapper once accessible");
assert!(!Arc::ptr_eq(recovered, renewed_again));
let disk::Disk::Local(recovered_local) = recovered.as_ref() else {
panic!("recovered slot must remain local");
};
assert!(!recovered_local.retirement_token().is_cancelled());
recovered_local
.check_scanner_handle()
.expect("recovered local wrapper must be usable by the data scanner");
drop(temp_dirs);
}
@@ -3922,6 +3922,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: Some(OffsetDateTime::now_utc()),
size: w_size,
actual_size,
checksums: part_info.checksums,
};
// error!("put_object_part ret {:?}", &ret);
@@ -4020,6 +4021,19 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
bucket: owner.bucket,
object: owner.object,
});
// The upload records its checksum algorithm and type at CreateMultipartUpload.
// ListParts echoes them like CreateMultipartUpload and CompleteMultipartUpload do,
// so a client that resumes an upload can state the same checksum contract.
let checksum_algorithm = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM)
.cloned()
.unwrap_or_default();
let checksum_type = fi
.metadata
.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE)
.cloned()
.unwrap_or_default();
let mut ret = ListPartsInfo {
recorded_owner,
bucket: bucket.to_owned(),
@@ -4028,6 +4042,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
storage_class,
max_parts,
part_number_marker,
checksum_algorithm,
checksum_type,
user_defined: {
let mut metadata = fi.metadata.clone();
strip_internal_multipart_metadata(&mut metadata);
@@ -4120,6 +4136,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
last_mod: part.mod_time,
size: part.size,
actual_size: part.actual_size,
checksums: part.checksums.clone(),
});
count -= 1;
@@ -7607,6 +7624,35 @@ mod tests {
}
}
#[tokio::test]
async fn list_object_parts_echoes_upload_and_part_checksums() {
let (_temp_dirs, disks, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-checksum-listing";
let object = "object";
make_bucket_on_all(&disks, bucket).await;
let payloads: [&[u8]; 2] = [b"first checksummed part", b"second checksummed part"];
let (upload_id, _, checksums) =
stage_checksummed_multipart_upload(&set_disks, bucket, object, Some(rustfs_rio::ChecksumType::SHA256), &payloads)
.await;
let page = set_disks
.list_object_parts(bucket, object, &upload_id, None, 10, &ObjectOptions::default())
.await
.expect("checksummed parts should be listable");
assert_eq!(page.checksum_algorithm, "SHA256");
assert_eq!(page.checksum_type, "COMPOSITE");
assert_eq!(page.parts.len(), payloads.len());
for (part, checksum) in page.parts.iter().zip(&checksums) {
assert_eq!(
part.checksums.as_ref().and_then(|checksums| checksums.get("SHA256")),
Some(&checksum.encoded),
"part {} must echo its recorded checksum",
part.part_num
);
}
}
#[tokio::test]
async fn list_parts_baseline_legacy_owner_metadata() {
let (_roots, disks, set) = hermetic_set_disks(4).await;
+10 -48
View File
@@ -11166,11 +11166,9 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
// needs below. These reads are pure quorum lookups under the locks
// already held; sequencing one metadata fan-out per key made a
// 1000-key batch pay a full round of drive reads at a time.
const DELETE_OBJECTS_SOURCE_READ_CONCURRENCY: usize = 64;
let mut source_reads: HashMap<usize, (ObjectInfo, FileInfo, Option<Error>, bool)> =
const DELETE_OBJECTS_SOURCE_READ_CONCURRENCY: usize = 16;
let mut source_reads: HashMap<usize, (ObjectInfo, FileInfo, Option<Error>)> =
HashMap::with_capacity(DELETE_OBJECTS_SOURCE_READ_CONCURRENCY);
let recovery_prefetch_allowed =
!is_meta_bucketname(bucket) && !opts.data_movement && !opts.replication_request && opts.http_preconditions.is_none();
let mut vers_map: HashMap<&String, FileInfoVersions> = HashMap::new();
let mut tier_reference_leases: Vec<(usize, String, Option<TierDestinationId>)> = Vec::new();
let mut tier_free_version_receipt_candidates: HashMap<usize, TierFreeVersionReceiptCandidate> = HashMap::new();
@@ -11181,7 +11179,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
for (i, dobj) in objects.iter().enumerate() {
if i.is_multiple_of(DELETE_OBJECTS_SOURCE_READ_CONCURRENCY) {
source_reads.clear();
let recovery_work_budget = opts.delete_recovery_work_budget.as_deref();
let mut pending = Vec::new();
for (i, source) in source_inputs
.iter()
@@ -11198,28 +11195,13 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
if !source.needs_source_read {
continue;
}
let guarded_prefetch =
current_generations.is_some_and(|generations| generations.contains_key(&objects[i].object_name));
let can_check_empty_recovery = recovery_prefetch_allowed
&& !guarded_prefetch
&& transaction_guards
.get(lock_names[i].as_ref())
.is_some_and(|guard| !guard.is_lock_lost());
let object_name = objects[i].object_name.clone();
let check_opts = &source.check_opts;
pending.push(async move {
let (goi, file_info, _write_quorum, gerr) = self
.get_object_info_fileinfo_and_quorum(bucket, &object_name, check_opts)
.await;
let confirmed_no_recovery = can_check_empty_recovery
&& goi.name.is_empty()
&& gerr
.as_ref()
.is_some_and(|error| is_err_object_not_found(error) || is_err_version_not_found(error))
&& self
.has_no_pending_delete_recovery_transactions(bucket, &object_name, recovery_work_budget)
.await;
(i, (goi, file_info, gerr, confirmed_no_recovery))
(i, (goi, file_info, gerr))
});
}
let reads = futures::stream::iter(pending)
@@ -11255,26 +11237,25 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
replicate_delete,
needs_source_read,
} = source;
let (mut goi, mut authoritative_file_info, mut gerr, confirmed_no_recovery) = if needs_source_read {
let (mut goi, mut authoritative_file_info, mut gerr) = if needs_source_read {
match source_reads.remove(&i) {
Some(read) => read,
None => {
let (goi, file_info, _write_quorum, gerr) = self
.get_object_info_fileinfo_and_quorum(bucket, &dobj.object_name, &check_opts)
.await;
(goi, file_info, gerr, false)
(goi, file_info, gerr)
}
}
} else {
(ObjectInfo::default(), FileInfo::default(), None, false)
(ObjectInfo::default(), FileInfo::default(), None)
};
// A quorum-resolved marker returns not-found with a populated name.
// Only missing metadata needs recovery; unrelated legacy residue or
// an offline disk must not block a new marker write at quorum.
if !confirmed_no_recovery
&& gerr
.as_ref()
.is_some_and(|error| is_err_object_not_found(error) || is_err_version_not_found(error))
if gerr
.as_ref()
.is_some_and(|error| is_err_object_not_found(error) || is_err_version_not_found(error))
&& !is_meta_bucketname(bucket)
&& !opts.data_movement
&& !opts.replication_request
@@ -11593,26 +11574,15 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
}
let mut vers = Vec::with_capacity(vers_map.len());
let mut coalesced_delete_marker_aliases: Vec<(usize, usize)> = Vec::new();
for (_, mut fi_vers) in vers_map {
fi_vers.versions.sort_by_key(|a| a.deleted);
fi_vers.versions.retain(|fi| del_errs[fi.idx].is_none());
if let Some(index) = fi_vers.versions.iter().position(|fi| fi.deleted) {
let canonical_idx = fi_vers.versions[index].idx;
for dup in &fi_vers.versions[(index + 1)..] {
if dup.deleted {
del_objects[dup.idx] = del_objects[canonical_idx].clone();
coalesced_delete_marker_aliases.push((dup.idx, canonical_idx));
}
}
fi_vers.versions.truncate(index + 1);
}
if !fi_vers.versions.is_empty() {
vers.push(fi_vers);
}
vers.push(fi_vers);
}
let rollback_dir = Uuid::new_v4();
@@ -11889,9 +11859,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
};
group_results.push((true, error));
}
for &(dup_idx, canonical_idx) in &coalesced_delete_marker_aliases {
group_by_object[dup_idx] = group_by_object[canonical_idx];
}
for obj_idx in 0..objects.len() {
let mut has_err = match group_by_object[obj_idx] {
@@ -12019,11 +11986,6 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
}
}
}
for &(dup_idx, canonical_idx) in &coalesced_delete_marker_aliases {
if del_errs[dup_idx].is_none() && del_errs[canonical_idx].is_some() {
del_errs[dup_idx] = del_errs[canonical_idx].clone();
}
}
receipt_summary.log(self.pool_index, self.set_index, None);
}
let mut rollback_futures = Vec::new();
+22 -141
View File
@@ -1113,26 +1113,10 @@ impl SetDisks {
};
let (read_quorum, write_quorum) = match Self::object_quorum_from_meta(&parts_metadata, &errs, self.default_parity_count)
.map_err(|err| dangling_not_found(&err).unwrap_or(err))
.map_err(|err| to_object_err(err.into(), vec![bucket, object, &vid]))
{
Ok(v) => v,
Err(raw_err) => {
if raw_err == DiskError::ErasureReadQuorum
&& vid.is_empty()
&& dangling_read != DanglingRead::KeepQuorumError
&& metadata_fanout_complete
&& !crate::bucket::utils::is_meta_bucketname(bucket)
&& let Some(snapshot) =
Box::pin(self.read_latest_past_dangling_versions(bucket, object, opts, read_data, purpose, &disks)).await
{
rustfs_io_metrics::record_get_object_metadata_quorum_result(metadata_metrics_path, "reached");
record_get_stage_duration_if_enabled(
GET_OBJECT_PATH_SET_DISK,
GET_STAGE_METADATA_RESOLVE,
metadata_resolve_stage_start,
);
return Ok(snapshot);
}
let e = to_object_err(raw_err.into(), vec![bucket, object, &vid]);
Err(e) => {
rustfs_io_metrics::record_get_object_metadata_quorum_result(metadata_metrics_path, metadata_quorum_outcome(&e));
// error!("Self::object_quorum_from_meta: {:?}, bucket: {}, object: {}", &e, bucket, object);
record_get_stage_duration_if_enabled(
@@ -1208,30 +1192,14 @@ impl SetDisks {
&& late_materialization_candidate_is_safe(&fi);
let mut snapshot = if !opts.suppress_read_repair && errs.iter().any(|err| err.is_some()) {
let version_id = resolved_read_repair_version_id(&fi, opts.version_id.as_deref());
let has_metadata_corruption = errs.iter().any(|err| {
matches!(
err,
Some(
DiskError::FileCorrupt
| DiskError::CorruptedFormat
| DiskError::CorruptedBackend
| DiskError::OutdatedXLMeta
)
)
});
submit_read_repair_heal_with_submitter(
ReadRepairHealSubmission {
bucket: &fi.volume,
object: &fi.name,
version_id: version_id.as_deref(),
pool_index: self.pool_index,
set_index: self.set_index,
part_number: None,
reason: "metadata_read_error",
mrf_intent: has_metadata_corruption
.then_some((rustfs_common::mrf_channel::MrfKind::MetadataCorruption, None)),
},
send_read_repair_heal_request,
submit_read_repair_heal(
&fi.volume,
&fi.name,
version_id.as_deref(),
self.pool_index,
self.set_index,
None,
"metadata_read_error",
)
.await;
let mut snapshot = GetObjectFileInfo::owned(fi, parts_metadata, op_online_disks);
@@ -1376,7 +1344,6 @@ impl SetDisks {
let mut best: Option<(Option<time::OffsetDateTime>, GetObjectFileInfo)> = None;
let mut skipped = Vec::new();
let mut recovered_null_overwrite = false;
let mut settled = false;
for (reads, (version_id, newest_mod_time)) in candidates.into_iter().enumerate() {
if best.as_ref().is_some_and(|(selected, _)| newest_mod_time < *selected) {
@@ -1392,7 +1359,7 @@ impl SetDisks {
version_id: Some(version_id.clone()),
..opts.clone()
};
let resolved_snapshot = match Box::pin(self.get_object_fileinfo_gated_inner(
match Box::pin(self.get_object_fileinfo_gated_inner(
bucket,
object,
&exact,
@@ -1403,41 +1370,21 @@ impl SetDisks {
))
.await
{
Ok(snapshot) => Some((snapshot, true)),
Err(StorageError::VersionNotFound(..)) => {
skipped.push(version_id);
None
}
Err(StorageError::ErasureReadQuorum | StorageError::InsufficientReadQuorum(..))
if version_id == uuid::Uuid::nil().to_string() =>
{
let snapshot = self
.read_null_version_past_incomplete_overwrites(bucket, object, &exact, read_data, disks)
.await?;
recovered_null_overwrite = true;
Some((snapshot, false))
}
Err(_) => return None,
};
if let Some((snapshot, require_live_header)) = resolved_snapshot {
let selected = snapshot.fi().mod_time;
let replace = match best.as_ref() {
Some((current, previous)) if selected == *current => {
if require_live_header {
Ok(snapshot) => {
let selected = snapshot.fi().mod_time;
let replace = match best.as_ref() {
Some((current, previous)) if selected == *current => {
selected_header(&snapshot)?.sorts_before(&selected_header(previous)?)
} else {
match (selected_header(&snapshot), selected_header(previous)) {
(Some(left), Some(right)) => left.sorts_before(&right),
_ => false,
}
}
Some((current, _)) => selected > *current,
None => true,
};
if replace {
best = Some((selected, snapshot));
}
Some((current, _)) => selected > *current,
None => true,
};
if replace {
best = Some((selected, snapshot));
}
Err(StorageError::VersionNotFound(..)) => skipped.push(version_id),
Err(_) => return None,
}
}
// Headers past each drive's first few were not compared; only a walk
@@ -1460,76 +1407,10 @@ impl SetDisks {
)
.await;
}
if recovered_null_overwrite {
submit_read_repair_heal(
bucket,
object,
None,
self.pool_index,
self.set_index,
None,
"incomplete_overwrite_rollback",
)
.await;
}
}
Some(snapshot)
}
async fn read_null_version_past_incomplete_overwrites(
&self,
bucket: &str,
object: &str,
opts: &ObjectOptions,
read_data: bool,
disks: &[Option<DiskStore>],
) -> Option<GetObjectFileInfo> {
let metadata_read = Self::read_metadata_observed(
disks,
"",
bucket,
object,
"",
read_data,
false,
opts.incl_free_versions,
false,
self.default_parity_count,
)
.await
.ok()?;
if !metadata_read.is_complete() {
return None;
}
let (parts_metadata, errs, _) = metadata_read.into_legacy();
let include_part_checksums =
opts.include_part_checksums || opts.part_number.is_some() || opts.data_movement || opts.raw_data_movement_read;
let mut resolution = self
.discover_incomplete_overwrite_rollbacks(
disks,
bucket,
object,
"",
&parts_metadata,
&errs,
read_data,
include_part_checksums,
)
.await?;
if include_part_checksums {
Self::hydrate_selected_fileinfo_part_checksums(&mut resolution.fi).ok()?;
} else {
for metadata in std::iter::once(&mut resolution.fi).chain(resolution.parts_metadata.iter_mut()) {
rustfs_utils::http::remove_str(&mut metadata.metadata, rustfs_utils::http::SUFFIX_PART_CHECKSUMS);
}
}
Some(GetObjectFileInfo::owned(
resolution.fi,
resolution.parts_metadata,
resolution.online_disks,
))
}
#[hotpath::measure(impl_type = "SetDisks")]
pub(super) async fn get_object_info_fileinfo_and_quorum(
&self,
-18
View File
@@ -850,24 +850,6 @@ impl ECStore {
.await
}
/// Return online formatted drive counts for every live `(pool_idx, set_idx)` in the cluster.
pub async fn online_drive_counts_by_set(&self) -> Vec<((u32, u32), usize)> {
let mut counts = Vec::new();
for pool in &self.pools {
let Ok(pool_idx) = u32::try_from(pool.pool_idx) else {
continue;
};
for set in &pool.disk_set {
let Ok(set_idx) = u32::try_from(set.set_index) else {
continue;
};
let (disks, _) = set.get_online_disks_with_healing(false).await;
counts.push(((pool_idx, set_idx), disks.len()));
}
}
counts
}
/// Return every live erasure set selected by an object-heal scope.
pub async fn heal_erasure_set_scopes(&self, opts: &HealOpts) -> Result<Vec<(usize, usize)>> {
let pools = self.get_pools_for_heal_object(opts)?;
+5 -20
View File
@@ -439,22 +439,14 @@ async fn resume_rebalance_after_init(store: Arc<ECStore>, rx: CancellationToken)
match store.start_rebalance().await {
Ok(()) => return,
Err(err)
if crate::core::pools::is_pool_activation_fleet_proof_error(&err)
|| crate::services::rebalance::is_transient_rebalance_error(&err) =>
{
let reason = if crate::core::pools::is_pool_activation_fleet_proof_error(&err) {
"fleet_capability_proof_unavailable"
} else {
"transient_rebalance_error"
};
Err(err) if crate::core::pools::is_pool_activation_fleet_proof_error(&err) => {
warn!(
event = EVENT_ECSTORE_INIT_STATUS,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_STORE_INIT,
stage = "start_rebalance",
state = "retrying",
reason = reason,
reason = "fleet_capability_proof_unavailable",
error = %err,
retry_delay_secs = REBALANCE_RESUME_RETRY_DELAY.as_secs(),
"Retrying deferred rebalance auto-start"
@@ -1093,14 +1085,7 @@ impl ECStore {
"Deferred rebalance auto-start until a live fleet capability proof is available"
);
} else if let Err(err) = self.start_rebalance().await {
if crate::core::pools::is_pool_activation_fleet_proof_error(&err)
|| crate::services::rebalance::is_transient_rebalance_error(&err)
{
let reason = if crate::core::pools::is_pool_activation_fleet_proof_error(&err) {
"fleet_capability_proof_changed"
} else {
"transient_rebalance_error"
};
if crate::core::pools::is_pool_activation_fleet_proof_error(&err) {
rebalance_auto_start_deferred = true;
warn!(
event = EVENT_ECSTORE_INIT_STATUS,
@@ -1108,10 +1093,10 @@ impl ECStore {
subsystem = LOG_SUBSYSTEM_STORE_INIT,
stage = "start_rebalance",
state = "deferred",
reason = reason,
reason = "fleet_capability_proof_changed",
error = %err,
retry_delay_secs = REBALANCE_RESUME_RETRY_DELAY.as_secs(),
"Deferred rebalance auto-start after transient startup failure"
"Deferred rebalance auto-start after the fleet capability proof changed"
);
} else {
return resolve_store_init_stage_result(Err(err), "start_rebalance");
+26 -40
View File
@@ -6914,39 +6914,25 @@ impl ECStore {
if !has_conditions {
// Keys whose write lock failed are already reported in `del_errs`;
// deduplicate identical `(object_name, version_id)` actions so a batch
// with duplicate versionless keys creates one persisted delete marker
// and echoes that exact marker VersionId across all duplicate rows.
let mut unconditional_actions = HashMap::with_capacity(objects.len());
let mut indices = Vec::with_capacity(objects.len());
for (idx, object) in objects.iter().enumerate() {
if del_errs[idx].is_some() {
continue;
}
let representative = *unconditional_actions.entry(batch_delete_action_key(object)).or_insert(idx);
representatives[idx] = representative;
if representative == idx {
indices.push(idx);
}
}
if !indices.is_empty() {
let (mut phase_deleted, mut phase_errors, mut phase_accounting) = self
.run_batch_delete_phase(
bucket,
&objects,
&opts,
BatchDeletePhasePlan {
indices: &indices,
pool_generations,
marker_targets: &conditional_marker_targets,
},
)
.await;
for idx in indices {
del_objects[idx] = std::mem::take(&mut phase_deleted[idx]);
del_errs[idx] = phase_errors[idx].take();
accounting[idx] = phase_accounting[idx].take();
}
// the phase only runs for the keys this batch actually holds, and
// only its outcomes replace the outer per-key state.
let indices = (0..objects.len()).filter(|idx| del_errs[*idx].is_none()).collect::<Vec<_>>();
let (mut phase_deleted, mut phase_errors, mut phase_accounting) = self
.run_batch_delete_phase(
bucket,
&objects,
&opts,
BatchDeletePhasePlan {
indices: &indices,
pool_generations,
marker_targets: &conditional_marker_targets,
},
)
.await;
for idx in indices {
del_objects[idx] = std::mem::take(&mut phase_deleted[idx]);
del_errs[idx] = phase_errors[idx].take();
accounting[idx] = phase_accounting[idx].take();
}
} else {
let mut conditional_actions = HashMap::with_capacity(objects.len());
@@ -7027,14 +7013,14 @@ impl ECStore {
}
}
for (idx, representative) in representatives.into_iter().enumerate() {
if representative != idx {
del_objects[idx] = del_objects[representative].clone();
del_errs[idx] = del_errs[representative].clone();
accounting[idx] = None;
}
}
if has_conditions {
for (idx, representative) in representatives.into_iter().enumerate() {
if representative != idx {
del_objects[idx] = del_objects[representative].clone();
del_errs[idx] = del_errs[representative].clone();
accounting[idx] = None;
}
}
let mut first_successes = HashMap::with_capacity(objects.len());
for (idx, object) in objects.iter().enumerate() {
if del_errs[idx].is_none() {
+1 -1
View File
@@ -878,7 +878,7 @@ impl ECStore {
/// Observe every pool for a conditional-write preflight. This does not
/// hold the namespace locks needed to prove a condition at publication.
pub(crate) async fn get_latest_object_info_for_conditional_write(
pub(super) async fn get_latest_object_info_for_conditional_write(
&self,
bucket: &str,
object: &str,
+154 -16
View File
@@ -379,9 +379,9 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
CrashPoint::RenameAfterDataRename,
CrashPoint::RenameAfterBackupBeforeMetaCommit,
CrashPoint::RenameAfterMetaCommit,
CrashPoint::MetaWriteAfterTmpBeforeRename,
];
let mut acknowledged_overwrites = 0;
for (seed_idx, &seed) in [0xC2A5_4001_u64, 0xC2A5_4002_u64, 0xC2A5_4003_u64, 0xC2A5_4004_u64]
.iter()
.enumerate()
@@ -457,8 +457,13 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
}
// 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();
let overwrite = put_bytes(&fixture, bucket, &key, &v2).await;
for slot in 0..affected_drives {
assert!(
!fixture.crash_registry.take_if_armed_on_drive(point, &key, "dst-node0", slot),
"seed={seed:#x} key={key}: {point:?} did not fire on drive {slot}"
);
}
// Simulate simultaneous cluster-wide power outage & ALICE reboot!
fixture.crash_and_reboot_all();
@@ -475,18 +480,19 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
}
}
// 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()
);
let observed = get_bytes(&fixture, bucket, &key).await.unwrap_or_else(|e| {
panic!("committed object {key} unreadable after ALICE crash at {point:?} (seed={seed:#x}): {e:?}")
});
if overwrite.is_ok() {
acknowledged_overwrites += 1;
assert!(observed == v2, "seed={seed:#x} key={key}: acknowledged overwrite lost after {point:?}");
} else {
// A fault can interrupt the reply after local publication completed.
assert!(
observed == v1 || observed == v2,
"seed={seed:#x} key={key}: torn overwrite after {point:?}: {overwrite:?}"
);
}
// INVARIANT 3: Production `heal_object` converges all 4 drives back to unanimous health,
// and previously untouched anchor objects remain 100% bit-exact!
@@ -513,6 +519,38 @@ async fn dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixe
assert_eq!(get_bytes(&fixture, bucket, anchor_large_key).await.unwrap(), anchor_large_v1);
}
}
assert!(acknowledged_overwrites > 0, "no degraded overwrite received an ACK");
}
#[tokio::test]
async fn metadata_write_crash_preserves_published_metadata() {
let fixture = make_dst_sim_set_disks(0xC2A5_4005, 4, 2, None).await.unwrap();
let bucket = "dst-meta-crash";
let key = "metadata.bin";
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.unwrap();
put_bytes(&fixture, bucket, key, b"committed").await.unwrap();
let disk = &fixture.disks[0];
let sim = &fixture.sim_disks[0];
sim.set_crash_semantics(CrashSemantics::DirtySubsetAndSectorTear);
let path = format!("{bucket}/{key}/{STORAGE_FORMAT_FILE}");
let original = sim.sim().read_file(&path).await.unwrap();
let mut next = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
next.metadata.insert("x-amz-meta-probe".into(), "updated".into());
let point = CrashPoint::MetaWriteAfterTmpBeforeRename;
fixture.crash_registry.arm_on_drive(point, key, "dst-node0", 0);
assert!(disk.write_metadata("", bucket, key, next.clone()).await.is_err());
assert!(!fixture.crash_registry.take_if_armed_on_drive(point, key, "dst-node0", 0));
fixture.crash_and_reboot_all();
assert_eq!(sim.sim().read_file(&path).await.unwrap(), original);
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), b"committed");
disk.write_metadata("", bucket, key, next).await.unwrap();
fixture.crash_and_reboot_all();
let updated = disk.read_version("", bucket, key, "", &ReadOptions::default()).await.unwrap();
assert_eq!(updated.metadata.get("x-amz-meta-probe").map(String::as_str), Some("updated"));
}
// ============================================================================
@@ -902,6 +940,10 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
// ------------------------------------------------------------------------
let mut before_cleanup_hits = 0usize;
for &seed in &[0x4D50_0101_u64, 0x4D50_0102_u64, 0x4D50_0103_u64, 0x4D50_0104_u64] {
let opts = ObjectOptions {
versioned: seed % 2 == 0,
..dst_object_options()
};
let fixture = make_dst_sim_set_disks(seed, 4, 2, None)
.await
.expect("dst sim SetDisks for multipart pre-cleanup cutpoint");
@@ -959,7 +1001,7 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
let crashed = fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts.clone(), &opts)
.await;
assert!(
crashed.is_err(),
@@ -985,6 +1027,21 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
"seed={seed:#x}: committed multipart payload must be bit-exact after pre-cleanup crash"
);
// A client that lost the completion response must recover the identity of
// the existing commit, including the version ID on a versioned bucket.
let published = fixture.set_disks.get_object_info(bucket, &key, &opts).await.unwrap();
assert_eq!(published.version_id.is_some(), opts.versioned);
let retried = fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, &key, &upload.upload_id, parts, &opts)
.await
.expect("complete retry after post-commit power loss");
assert!(retried.multipart_completion_replayed, "seed={seed:#x}: upload committed again");
assert_eq!(retried.version_id, published.version_id);
assert_eq!(retried.etag, published.etag);
assert_eq!(get_bytes(&fixture, bucket, &key).await.unwrap(), expected);
// Post-crash heal converges cleanly and every drive verifies both parts!
let (_heal_item, heal_err) = fixture
.set_disks
@@ -1016,6 +1073,13 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
vec![CHECK_PART_SUCCESS, CHECK_PART_SUCCESS],
"drive {slot} must pass HighwayHash256S verification for both parts"
);
let raw = disk.read_all(bucket, &format!("{key}/{STORAGE_FORMAT_FILE}")).await.unwrap();
let versions = FileMeta::load(&raw)
.unwrap()
.get_all_file_info_versions(bucket, &key, true)
.unwrap();
assert_eq!(versions.versions.len(), 1, "drive {slot}: duplicate multipart commit");
assert_eq!(versions.versions[0].version_id, published.version_id);
}
}
assert_eq!(
@@ -1023,3 +1087,77 @@ async fn dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_befor
"fault.multipart_crashed_before_cleanup must hit across all 4 seeds"
);
}
#[tokio::test]
async fn multipart_replay_rejects_missing_or_other_disk_anchor() {
let fixture = make_dst_sim_set_disks(0x671, 4, 2, None).await.unwrap();
let bucket = "dst-mpu-anchor";
let key = "published";
let opts = dst_object_options();
fixture
.set_disks
.make_bucket(bucket, &MakeBucketOptions::default())
.await
.unwrap();
let upload = fixture.set_disks.new_multipart_upload(bucket, key, &opts).await.unwrap();
let expected = deterministic_payload(0x671, key, 128 * 1024);
let mut payload = PutObjReader::from_vec(expected.clone());
let part = fixture
.set_disks
.put_object_part(bucket, key, &upload.upload_id, 1, &mut payload, &opts)
.await
.unwrap();
let parts = vec![CompletePart {
part_num: 1,
etag: part.etag,
..Default::default()
}];
let complete = || {
fixture
.set_disks
.clone()
.complete_multipart_upload(bucket, key, &upload.upload_id, parts.clone(), &opts)
};
let published = complete().await.unwrap();
fixture.crash_and_reboot_all();
let replayed = complete().await.expect("all four witnesses are available");
assert!(replayed.multipart_completion_replayed);
assert_eq!(replayed.etag, published.etag);
let info = fixture.disks[0]
.read_version("", bucket, key, "", &ReadOptions::default())
.await
.unwrap();
let anchor =
rustfs_ecstore::api::dst::DstSimDisk::multipart_retirement_anchor_path(bucket, key, info.data_dir.unwrap()).unwrap();
let (parent, _) = anchor.rsplit_once('/').unwrap();
let disks = &fixture.sim_disks;
let own_0 = disks[0].sim().read_file(&anchor).await.unwrap();
let own_1 = disks[1].sim().read_file(&anchor).await.unwrap();
let foreign = disks[2].sim().read_file(&anchor).await.unwrap();
for disk in &disks[..2] {
disk.sim().remove_file(&anchor).await.unwrap();
disk.sim().fsync_dir(parent).await.unwrap();
}
fixture.crash_and_reboot_all();
assert_eq!(get_bytes(&fixture, bucket, key).await.unwrap(), expected);
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
disks[0].sim().write_file(&anchor, foreign).await.unwrap();
disks[0].sim().fsync_file(&anchor).await.unwrap();
disks[0].sim().fsync_dir(parent).await.unwrap();
fixture.crash_and_reboot_all();
assert!(matches!(complete().await, Err(EcstoreError::ErasureWriteQuorum)));
for (disk, own) in disks[..2].iter().zip([own_0, own_1]) {
disk.sim().write_file(&anchor, own).await.unwrap();
disk.sim().fsync_file(&anchor).await.unwrap();
disk.sim().fsync_dir(parent).await.unwrap();
}
fixture.crash_and_reboot_all();
let replayed = complete()
.await
.expect("each restored witness belongs to its own physical disk");
assert!(replayed.multipart_completion_replayed);
assert_eq!(replayed.etag, published.etag);
}
+1 -10
View File
@@ -885,12 +885,7 @@ fn retry_budget_for_result(task: &HealTask, result: &Result<()>, retryable_batch
tokio::time::Instant::now().checked_add(delay)?;
return Some((delay, err.to_string()));
}
let max_retries = if err.is_slow_down() {
12
} else {
MAX_RECOVERABLE_HEAL_RETRIES
};
if task.retry_attempts >= max_retries {
if task.retry_attempts >= MAX_RECOVERABLE_HEAL_RETRIES {
return None;
}
// Admin traversals already exhaust their per-object retries. Restarting
@@ -2216,10 +2211,6 @@ impl HealManager {
self.submit_heal_request_with_receipt_and_alias(request, false).await
}
pub(crate) async fn online_drive_counts_by_set(&self) -> Vec<((u32, u32), usize)> {
self.storage.online_drive_counts_by_set().await
}
pub(crate) async fn submit_heal_request_with_receipt_and_alias(
&self,
request: HealRequest,
-16
View File
@@ -2389,7 +2389,6 @@ async fn run_mrf_consumer_with_stop(
flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut batch: Vec<MrfIntent> = Vec::with_capacity(runtime.config.replay_batch);
let mut durable_batch = Vec::with_capacity(runtime.config.replay_batch);
let mut observed_online_drives: HashMap<(u32, u32), usize> = HashMap::new();
loop {
if stop.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
@@ -2506,21 +2505,6 @@ async fn run_mrf_consumer_with_stop(
}
}
_ = flush_tick.tick() => {
if runtime.partial_writes.depth() > 0 {
let mut recovered_scopes = HashSet::new();
for (scope, online_count) in manager.online_drive_counts_by_set().await {
if let Some(previous) = observed_online_drives.insert(scope, online_count)
&& online_count > previous
{
recovered_scopes.insert(scope);
}
}
runtime.partial_writes.wake_recovered_scopes(&recovered_scopes);
} else if !observed_online_drives.is_empty() {
for (scope, online_count) in manager.online_drive_counts_by_set().await {
observed_online_drives.insert(scope, online_count);
}
}
runtime.partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
runtime.discharge_durable_replay_anchors();
match tick_action(
@@ -783,35 +783,6 @@ impl PartialWrites {
Ok((entry.intent.clone(), previous))
}
/// Reset exponential retry backoff for active obligations in `(pool, set)`
/// (plus unscoped obligations) whenever an offline drive returns online.
pub(super) fn wake_recovered_scopes(&mut self, recovered_scopes: &HashSet<(u32, u32)>) -> bool {
if recovered_scopes.is_empty() {
return false;
}
let now = Instant::now();
let mut woke = false;
for (key, entry) in &mut self.entries {
if entry.is_parked() || entry.attempt_in_flight || !entry.persisted {
continue;
}
let scope_matches = entry
.intent
.scope
.is_none_or(|scope| recovered_scopes.contains(&(scope.pool_index, scope.set_index)));
if scope_matches && (entry.next_attempt > now || entry.consecutive_unverified_attempts > 0) {
entry.next_attempt = now;
entry.consecutive_unverified_attempts = 0;
if !entry.retry_queued && self.retry_index.insert(key.clone()) {
self.retry_order.push_back(key.clone());
entry.retry_queued = true;
}
woke = true;
}
}
woke
}
pub(super) fn restore_operator_state(
&mut self,
responsibility_id: Uuid,
-10
View File
@@ -738,12 +738,6 @@ pub trait HealStorageAPI: Send + Sync {
Ok(None)
}
/// Return online formatted drive counts per `(pool_index, set_index)` so
/// MRF backoff timers can wake immediately when an offline drive recovers.
async fn online_drive_counts_by_set(&self) -> Vec<((u32, u32), usize)> {
Vec::new()
}
/// List versions for healing via a per-erasure-set DISK-WALK union enumerator
/// (backlog#920). Unlike `list_objects_for_heal_page` (which reflects only the
/// READ-QUORUM metadata view via `list_object_versions`), this surfaces every
@@ -2195,10 +2189,6 @@ impl HealStorageAPI for ECStoreHealStorage {
.map_err(Error::Storage)
}
async fn online_drive_counts_by_set(&self) -> Vec<((u32, u32), usize)> {
self.live_ecstore().online_drive_counts_by_set().await
}
async fn list_versions_for_heal_page_disk_walk(
&self,
set_disk_id: &str,
-3
View File
@@ -946,9 +946,6 @@ impl HealTask {
}
pub(crate) fn should_log_failure(&self, error: &Error) -> bool {
if error.is_slow_down() && self.source == HealRequestSource::Scanner {
return false;
}
if !matches!(error, Error::Storage(crate::heal::StorageError::DeleteRecoveryLegacyAmbiguous)) {
return true;
}
+68 -1
View File
@@ -1428,6 +1428,9 @@ impl VaultTransitKmsClient {
}
})
.await?;
// Transit LIST also returns directory entries, including the BYOK
// wrapping-key directory. Only actual key names belong in the cursor.
all_keys.retain(|key| !key.ends_with('/'));
// Vault's own LIST ordering is not part of its contract, so the sort is
// what makes the marker a stable cursor across calls.
all_keys.sort_unstable();
@@ -2068,6 +2071,70 @@ mod tests {
serde_json::to_value(&response).expect("serialize transit key read response")
}
#[tokio::test]
async fn list_skips_byok_directories_before_pagination() {
let listed = serde_json::json!({ "keys": ["zulu", "import/", "import", "alpha", "versions/"] });
let metadata = metadata_read_data(&TransitKeyMetadata::from_create_request(&CreateKeyRequest::default()));
let (vault, client) = scripted_client(vec![
ScriptedResponse::ok(listed.clone()),
ScriptedResponse::ok(transit_key_read_data("alpha")),
ScriptedResponse::ok(metadata.clone()),
ScriptedResponse::ok(transit_key_read_data("import")),
ScriptedResponse::ok(metadata.clone()),
ScriptedResponse::ok(listed),
ScriptedResponse::ok(transit_key_read_data("zulu")),
ScriptedResponse::ok(metadata),
])
.await;
let first = client
.list_keys(
&ListKeysRequest {
limit: Some(2),
..Default::default()
},
None,
)
.await
.expect("list the first page despite directory entries");
assert_eq!(first.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["alpha", "import"]);
assert_eq!(first.next_marker.as_deref(), Some("import"));
assert!(first.truncated);
assert!(first.unreadable_key_ids.is_empty());
let last = client
.list_keys(
&ListKeysRequest {
limit: Some(2),
marker: first.next_marker,
..Default::default()
},
None,
)
.await
.expect("a sweep can continue past the wrapping-key directory");
assert_eq!(last.keys.iter().map(|key| key.key_id.as_str()).collect::<Vec<_>>(), ["zulu"]);
assert!(last.next_marker.is_none());
assert!(!last.truncated);
assert!(last.unreadable_key_ids.is_empty());
assert_eq!(vault.requests().len(), 8, "only actual keys should be described");
}
#[tokio::test]
async fn list_with_only_the_byok_directory_is_empty() {
let (vault, client) = scripted_client(vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/"] }))]).await;
let listed = client
.list_keys(&ListKeysRequest::default(), None)
.await
.expect("the wrapping-key directory is not a KMS key");
assert!(listed.keys.is_empty());
assert!(listed.next_marker.is_none());
assert!(!listed.truncated);
assert!(listed.unreadable_key_ids.is_empty());
assert_eq!(vault.requests().len(), 1, "a directory must not be described");
}
/// A listing must not silently shrink when the backend is the problem.
///
/// Before the per-key classification this path used `?`, so any describe
@@ -2076,7 +2143,7 @@ mod tests {
/// about it. A transit mount that stops answering must still fail loudly.
#[tokio::test]
async fn list_fails_when_a_transit_key_read_is_unavailable() {
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["key-a"] }))];
let mut responses = vec![ScriptedResponse::ok(serde_json::json!({ "keys": ["import/", "key-a"] }))];
for _ in 0..3 {
responses.push(ScriptedResponse::error(503, "temporarily unavailable"));
}
+4 -262
View File
@@ -72,11 +72,7 @@ impl GuardRegistryState {
let Some(entry) = self.entries.get_mut(lock_id) else {
return false;
};
if entry.is_expired()
|| entry
.owner_incarnation
.is_some_and(|incarnation| is_owner_incarnation_retired(entry.guard.owner().as_ref(), incarnation))
{
if entry.is_expired() {
return false;
}
entry.refresh();
@@ -116,97 +112,6 @@ impl GuardRegistryState {
self.next_expiry = next_expiry;
expired
}
fn extract_by_owner_incarnation(&mut self, owner: &str, old_incarnation: uuid::Uuid) -> Vec<LocalGuardEntry> {
if self.entries.is_empty() {
return Vec::new();
}
let mut next_expiry: Option<Instant> = None;
let matching = self
.entries
.extract_if(|_, entry| {
if entry.guard.owner().as_ref().eq_ignore_ascii_case(owner) && entry.owner_incarnation == Some(old_incarnation) {
true
} else {
next_expiry = Some(next_expiry.map_or(entry.deadline, |deadline| deadline.min(entry.deadline)));
false
}
})
.map(|(_, entry)| entry)
.collect();
self.next_expiry = next_expiry;
matching
}
}
const MAX_RETIRED_INCARNATIONS_PER_OWNER: usize = 64;
static LIVE_GUARD_STORAGES: std::sync::LazyLock<parking_lot::Mutex<Vec<std::sync::Weak<Vec<GuardShard>>>>> =
std::sync::LazyLock::new(|| parking_lot::Mutex::new(Vec::new()));
static RETIRED_OWNER_INCARNATIONS: std::sync::LazyLock<RwLock<HashMap<String, Vec<uuid::Uuid>>>> =
std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
fn normalize_incarnation_owner(owner: &str) -> String {
owner.trim().to_ascii_lowercase()
}
/// Synchronously mark `(owner, old_incarnation)` as retired so in-flight or late
/// lock requests from a restarted peer's previous incarnation cannot be admitted
/// or refreshed, without disturbing locks granted to the peer's newer incarnation.
pub fn retire_local_owner_incarnation(owner: &str, old_incarnation: uuid::Uuid) {
let key = normalize_incarnation_owner(owner);
if key.is_empty() {
return;
}
let mut retired = RETIRED_OWNER_INCARNATIONS.write();
let list = retired.entry(key).or_default();
if !list.contains(&old_incarnation) {
if list.len() >= MAX_RETIRED_INCARNATIONS_PER_OWNER {
list.remove(0);
}
list.push(old_incarnation);
}
}
fn is_owner_incarnation_retired(owner: &str, incarnation: uuid::Uuid) -> bool {
let key = normalize_incarnation_owner(owner);
if key.is_empty() {
return false;
}
RETIRED_OWNER_INCARNATIONS
.read()
.get(&key)
.is_some_and(|list| list.contains(&incarnation))
}
/// Reclaim all active local lock guards owned by `(owner, old_incarnation)` across
/// every live `LocalClient` in this process (used when an internode peer proves a
/// new `boot_epoch` after restart).
pub async fn reclaim_all_local_guards_for_owner_incarnation(owner: &str, old_incarnation: uuid::Uuid) -> usize {
if owner.is_empty() {
return 0;
}
retire_local_owner_incarnation(owner, old_incarnation);
let storages: Vec<GuardStorage> = {
let mut list = LIVE_GUARD_STORAGES.lock();
let mut upgraded = Vec::with_capacity(list.len());
list.retain(|weak| {
if let Some(arc) = weak.upgrade() {
upgraded.push(arc);
true
} else {
false
}
});
upgraded
};
let mut total = 0usize;
for storage in storages {
total = total
.saturating_add(LocalClient::reclaim_storage_guards_for_owner_incarnation(&storage, owner, old_incarnation).await);
}
total
}
/// Registry access never reserves the table for a task that has not resumed.
@@ -315,7 +220,6 @@ struct LocalGrant {
#[derive(Debug)]
struct LocalGuardEntry {
guard: FastLockGuard,
owner_incarnation: Option<uuid::Uuid>,
acquired_at: SystemTime,
last_refreshed: SystemTime,
expires_at: SystemTime,
@@ -331,7 +235,6 @@ enum LocalAcquireFailure {
current_mode: crate::LockMode,
},
InvalidResource,
StaleIncarnation,
}
impl LocalAcquireFailure {
@@ -348,7 +251,6 @@ impl LocalAcquireFailure {
Self::InvalidResource => {
LockResponse::failure("Lock id resource does not match the requested resource", Duration::ZERO)
}
Self::StaleIncarnation => LockResponse::failure("Lock owner incarnation is retired", Duration::ZERO),
}
}
@@ -361,7 +263,7 @@ impl LocalAcquireFailure {
Self::Conflict { current_owner, .. } => BatchAcquireOutcome::RetryableNoGrant {
error: crate::LockError::already_locked(request.resource.to_string(), current_owner.to_string()),
},
Self::InvalidResource | Self::StaleIncarnation => BatchAcquireOutcome::TerminalNoGrant {
Self::InvalidResource => BatchAcquireOutcome::TerminalNoGrant {
error: crate::LockError::invalid_handle(request.lock_id.to_string()),
},
}
@@ -369,12 +271,11 @@ impl LocalAcquireFailure {
}
impl LocalGuardEntry {
fn new(guard: FastLockGuard, ttl: Duration, owner_incarnation: Option<uuid::Uuid>) -> Self {
fn new(guard: FastLockGuard, ttl: Duration) -> Self {
let acquired_at = SystemTime::now();
let monotonic_now = Instant::now();
Self {
guard,
owner_incarnation,
acquired_at,
last_refreshed: acquired_at,
expires_at: acquired_at.checked_add(ttl).unwrap_or(acquired_at),
@@ -407,11 +308,6 @@ impl LocalClient {
if request.lock_id.resource != request.resource {
return Err(LocalAcquireFailure::InvalidResource);
}
if let Some(incarnation) = request.owner_incarnation
&& is_owner_incarnation_retired(&request.owner, incarnation)
{
return Err(LocalAcquireFailure::StaleIncarnation);
}
let lock_manager = self.get_lock_manager();
let initial_remaining = acquire_deadline.saturating_duration_since(Instant::now());
let reclaimed_before_acquire = if initial_remaining.is_zero() {
@@ -452,7 +348,7 @@ impl LocalClient {
let registration_started = Instant::now();
let physical_guard_id = guard.guard_id();
let lock_id = request.lock_id.clone();
let entry = LocalGuardEntry::new(guard, request.ttl, request.owner_incarnation);
let entry = LocalGuardEntry::new(guard, request.ttl);
let acquired_at = entry.acquired_at;
let expires_at = entry.expires_at;
@@ -467,16 +363,6 @@ impl LocalClient {
drop(guards);
return Err(LocalAcquireFailure::Timeout);
}
// Recheck retirement under the shard write lock so a
// concurrent peer restart cannot admit a stale grant
// after `retire_local_owner_incarnation` returns.
if let Some(incarnation) = request.owner_incarnation
&& is_owner_incarnation_retired(&request.owner, incarnation)
{
drop(guards);
drop(entry);
return Err(LocalAcquireFailure::StaleIncarnation);
}
let registration_wait = registration_started.elapsed();
let mutation_started = Instant::now();
let replaced_entry = guards.insert(lock_id.clone(), entry);
@@ -591,11 +477,6 @@ impl LocalClient {
fn with_storage(guard_storage: GuardStorage, manager: Option<Arc<GlobalLockManager>>, reaper_interval: Duration) -> Self {
let shard_count = guard_storage.len();
debug_assert!(shard_count.is_power_of_two());
{
let mut list = LIVE_GUARD_STORAGES.lock();
list.retain(|weak| weak.strong_count() > 0);
list.push(Arc::downgrade(&guard_storage));
}
Self {
guard_storage,
shard_mask: shard_count - 1,
@@ -610,37 +491,6 @@ impl LocalClient {
}
}
/// Reclaim all guards held by `(owner, old_incarnation)` on this `LocalClient`.
pub async fn reclaim_guards_for_owner_incarnation(&self, owner: &str, old_incarnation: uuid::Uuid) -> usize {
retire_local_owner_incarnation(owner, old_incarnation);
Self::reclaim_storage_guards_for_owner_incarnation(&self.guard_storage, owner, old_incarnation).await
}
async fn reclaim_storage_guards_for_owner_incarnation(
storage: &GuardStorage,
owner: &str,
old_incarnation: uuid::Uuid,
) -> usize {
let mut total_reclaimed = 0usize;
for shard in storage.iter() {
let has_match = shard.read().await.entries.values().any(|entry| {
entry.guard.owner().as_ref().eq_ignore_ascii_case(owner) && entry.owner_incarnation == Some(old_incarnation)
});
if !has_match {
continue;
}
let extracted = {
let mut guards = shard.write().await;
guards.extract_by_owner_incarnation(owner, old_incarnation)
};
// Drop physical guards outside the shard lock immediately so contention on a later
// shard cannot delay releasing reclaimed guards extracted from earlier shards.
total_reclaimed += Self::release_reclaimed_guards_unlogged(extracted);
}
Self::log_reclaimed_guards(total_reclaimed);
total_reclaimed
}
fn cache_fence_stamp_for_grant(
&self,
resource: &crate::ObjectKey,
@@ -2241,112 +2091,4 @@ mod tests {
}
assert_eq!(backend.get_shard(&contending_resource).active_guard_count(), 0);
}
#[tokio::test]
async fn reclaim_all_local_guards_for_owner_incarnation_fences_old_epoch_and_preserves_new_epoch() {
let client = LocalClient::with_manager(Arc::new(GlobalLockManager::new()));
let restarted_owner = format!("restarted-peer-{}:9000", uuid::Uuid::new_v4());
let healthy_owner = format!("healthy-peer-{}:9000", uuid::Uuid::new_v4());
let old_epoch = uuid::Uuid::new_v4();
let new_epoch = uuid::Uuid::new_v4();
// 1. Old incarnation acquires a write lock before the peer restarts.
let stale_write_key = crate::ObjectKey::new("bucket", "cross-pool-write-old");
let stale_write = LockRequest::new(stale_write_key.clone(), LockType::Exclusive, &restarted_owner)
.with_owner_incarnation(old_epoch)
.with_ttl(Duration::from_secs(30));
assert!(client.acquire_lock(&stale_write).await.expect("stale write grant").success);
// 2. Peer restarts and its new incarnation acquires a write lock BEFORE the async sweep runs.
let fresh_write_key = crate::ObjectKey::new("bucket", "cross-pool-write-new");
let fresh_write = LockRequest::new(fresh_write_key.clone(), LockType::Exclusive, &restarted_owner)
.with_owner_incarnation(new_epoch)
.with_ttl(Duration::from_secs(30));
assert!(client.acquire_lock(&fresh_write).await.expect("fresh write grant").success);
// 3. Legacy/local guard for the same owner with no incarnation tag, plus an unrelated healthy peer.
let legacy_write_key = crate::ObjectKey::new("bucket", "cross-pool-write-legacy");
let legacy_write =
LockRequest::new(legacy_write_key.clone(), LockType::Exclusive, &restarted_owner).with_ttl(Duration::from_secs(30));
assert!(client.acquire_lock(&legacy_write).await.expect("legacy write grant").success);
let healthy_write_key = crate::ObjectKey::new("bucket", "healthy-write");
let healthy_write = LockRequest::new(healthy_write_key.clone(), LockType::Exclusive, &healthy_owner)
.with_owner_incarnation(old_epoch)
.with_ttl(Duration::from_secs(30));
assert!(
client
.acquire_lock(&healthy_write)
.await
.expect("healthy write grant")
.success
);
// Synchronously retire old_epoch and sweep only (restarted_owner, old_epoch).
retire_local_owner_incarnation(&restarted_owner, old_epoch);
let reclaimed = reclaim_all_local_guards_for_owner_incarnation(&restarted_owner.to_ascii_uppercase(), old_epoch).await;
assert_eq!(reclaimed, 1, "expected only the retired incarnation's guard to be reclaimed");
// Stale key is immediately available to new writers.
let contender = LockRequest::new(stale_write_key, LockType::Exclusive, &healthy_owner)
.with_acquire_timeout(Duration::from_millis(50));
assert!(
client
.acquire_lock(&contender)
.await
.expect("contender after reclaim")
.success,
"reclaimed cross-pool write lock must immediately admit new writers"
);
assert!(client.release(&contender.lock_id).await.expect("release contender"));
// Late RPC carrying the retired old_epoch must be rejected immediately.
let late_stale_key = crate::ObjectKey::new("bucket", "cross-pool-write-late-old");
let late_stale = LockRequest::new(late_stale_key.clone(), LockType::Exclusive, &restarted_owner)
.with_owner_incarnation(old_epoch)
.with_acquire_timeout(Duration::from_millis(50));
assert!(
!client.acquire_lock(&late_stale).await.expect("late stale attempt").success,
"retired incarnation must not be granted new locks"
);
let late_outcomes = client
.acquire_locks_batch_until(std::slice::from_ref(&late_stale), Instant::now() + Duration::from_millis(50))
.await;
assert!(
matches!(late_outcomes.as_slice(), [super::super::BatchAcquireOutcome::TerminalNoGrant { .. }]),
"retired incarnation batch acquire must fail terminally without grant"
);
// New incarnation's lock, legacy untagged lock, and unrelated peer's lock must all remain intact.
for (label, key) in [
("new incarnation", fresh_write_key),
("legacy untagged", legacy_write_key),
("unrelated peer", healthy_write_key),
] {
let blocked =
LockRequest::new(key, LockType::Exclusive, "other-peer:9000").with_acquire_timeout(Duration::from_millis(20));
assert!(
!client.acquire_lock(&blocked).await.expect("blocked check").success,
"{label} guard must remain held after reclaiming old_epoch"
);
}
// New incarnation can still acquire additional locks after old_epoch is retired.
let fresh_after_retire = LockRequest::new(late_stale_key, LockType::Exclusive, &restarted_owner)
.with_owner_incarnation(new_epoch)
.with_acquire_timeout(Duration::from_millis(50));
assert!(
client
.acquire_lock(&fresh_after_retire)
.await
.expect("fresh incarnation after retire")
.success,
"new incarnation must continue acquiring locks cleanly"
);
assert!(client.release(&fresh_after_retire.lock_id).await.expect("release fresh2"));
assert!(client.release(&fresh_write.lock_id).await.expect("release fresh"));
assert!(client.release(&legacy_write.lock_id).await.expect("release legacy"));
assert!(client.release(&healthy_write.lock_id).await.expect("release healthy"));
}
}
+1 -4
View File
@@ -38,10 +38,7 @@ pub mod types;
// Re-export main types for easy access
pub use crate::{
// Client interfaces
client::{
BatchAcquireOutcome, LockCleanupOutcome, LockClient,
local::{LocalClient, reclaim_all_local_guards_for_owner_incarnation, retire_local_owner_incarnation},
},
client::{BatchAcquireOutcome, LockCleanupOutcome, LockClient, local::LocalClient},
distributed_lock::DistributedLockGuard,
// Error types
error::{LockError, Result},
-36
View File
@@ -390,30 +390,6 @@ impl LockMetadata {
}
}
mod option_uuid_serde {
use serde::{Deserialize, Deserializer, Serializer};
use uuid::Uuid;
pub(super) fn serialize<S>(value: &Option<Uuid>, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
match value {
Some(id) => serializer.serialize_some(&id.to_string()),
None => serializer.serialize_none(),
}
}
pub(super) fn deserialize<'de, D>(deserializer: D) -> std::result::Result<Option<Uuid>, D::Error>
where
D: Deserializer<'de>,
{
let raw = Option::<String>::deserialize(deserializer)?;
raw.map(|text| Uuid::parse_str(&text).map_err(serde::de::Error::custom))
.transpose()
}
}
/// Lock request structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockRequest {
@@ -448,11 +424,6 @@ pub struct LockRequest {
/// always advance their voter generation, including for legacy requests.
#[serde(default)]
pub cache_fence_stamp_requested: bool,
/// Optional authenticated caller process incarnation (`boot_epoch`) used to
/// fence stale lock reclamation on peer restart without disturbing locks
/// granted to the restarted peer's newer incarnation.
#[serde(default, skip_serializing_if = "Option::is_none", with = "option_uuid_serde")]
pub owner_incarnation: Option<uuid::Uuid>,
}
impl LockRequest {
@@ -471,16 +442,9 @@ impl LockRequest {
suppress_contention_logs: false,
refresh_interval: None,
cache_fence_stamp_requested: false,
owner_incarnation: None,
}
}
/// Attach the caller's authenticated process incarnation (`boot_epoch`).
pub fn with_owner_incarnation(mut self, incarnation: uuid::Uuid) -> Self {
self.owner_incarnation = Some(incarnation);
self
}
/// Set acquire timeout (how long to wait for lock acquisition)
pub fn with_acquire_timeout(mut self, timeout: Duration) -> Self {
self.acquire_timeout = timeout;
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "metrics"
version = "0.24.6"
publish = false
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
description = "RustFS compatibility facade for dependencies requiring metrics 0.24"
[dependencies]
# Use a distinct extern name when rustdoc also links the facade as metrics.
metrics_025 = { package = "metrics", version = "0.25.1" }
[dev-dependencies]
metrics-util = { workspace = true, features = ["debugging"] }
toml = "1.2.3"
[lints]
workspace = true
+82
View File
@@ -0,0 +1,82 @@
// 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.
//! Share the metrics recorder with dependencies requiring metrics 0.24.
// RUSTFS_COMPAT_TODO(metrics-024-recorder): Share the recorder with 0.24 consumers. Remove after all consumers accept metrics 0.25 directly.
pub use metrics_025::*;
#[cfg(test)]
mod tests {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
#[test]
fn legacy_macros_reach_the_metrics_025_recorder() {
let recorder = DebuggingRecorder::new();
metrics_025::with_local_recorder(&recorder, || {
crate::counter!("messages", "topic" => "events").increment(2);
metrics_025::counter!("messages", "topic" => "events").increment(3);
crate::gauge!("connections").set(4.0);
crate::histogram!("latency").record(5.0);
});
let entries = recorder.snapshotter().snapshot().into_vec();
let expected = [
(
metrics_025::Key::from_parts("messages", vec![metrics_025::Label::new("topic", "events")]),
DebugValue::Counter(5),
),
(metrics_025::Key::from_name("connections"), DebugValue::Gauge(4.0.into())),
(metrics_025::Key::from_name("latency"), DebugValue::Histogram(vec![5.0.into()])),
];
assert_eq!(entries.len(), expected.len());
for (key, value) in expected {
assert!(
entries
.iter()
.any(|(entry, _, _, recorded)| entry.key() == &key && recorded == &value)
);
}
}
#[test]
fn workspace_and_fuzz_use_only_one_recorder_implementation() {
for (lockfile, needs_facade) in [
(include_str!("../../../Cargo.lock"), true),
(include_str!("../../../fuzz/Cargo.lock"), false),
] {
let lock: toml::Value = toml::from_str(lockfile).expect("Cargo lockfile should parse");
let packages = lock["package"].as_array().expect("Cargo lockfile should list packages");
let metrics: Vec<_> = packages
.iter()
.filter(|package| package["name"].as_str() == Some("metrics"))
.collect();
assert_eq!(metrics.len(), 1 + usize::from(needs_facade), "metrics must have one implementation");
assert_eq!(
metrics
.iter()
.any(|package| { package["version"].as_str() == Some("0.24.6") && package.get("source").is_none() }),
needs_facade,
);
assert!(metrics.iter().any(|package| {
package["version"]
.as_str()
.is_some_and(|version| version.starts_with("0.25."))
&& package["source"]
.as_str()
.is_some_and(|source| source.starts_with("registry+"))
}));
}
}
}
+9 -16
View File
@@ -169,34 +169,24 @@ Refreshing only dirty disks is safe only when:
- `disk_cache_complete == true`
- which means the system has already completed at least one full refresh without partial errors
- and the per-disk cache is fully populated
- and the per-disk cache covers the current local disk set
If no aggregate cache exists yet, the system performs a full refresh to establish an initial value. Once an aggregate cache exists, a scheduled refresh with no dirty disks stays idle instead of repeatedly walking unchanged disks. If disks are dirty while the per-disk cache is incomplete, the system performs a full refresh because a subset cannot be merged safely.
The first refresh builds an aggregate baseline. Scheduled refreshes stay idle when there are no dirty disks and the baseline still applies. A change in local disk membership triggers a full refresh, including replacements that keep the same disk count. Dirty disks with an incomplete per-disk baseline also trigger a full refresh.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. That bounded estimate acknowledges dirty marks that predate the scan, while marks recorded during the scan remain pending. This prevents one old dirty mark from causing an endless timeout loop without treating the estimate as exact.
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. A bounded or degraded full refresh after a topology change discards the old per-disk baseline and publishes the available current aggregate. A timeout estimate acknowledges dirty marks that predate the scan. Marks recorded during the scan remain pending.
### Merge Rules After a Subset Refresh
- On a successful full refresh, `per_disk` replaces the entire `disk_cache`.
- On a successful dirty-subset refresh, only the affected per-disk entries are updated.
- The total capacity is recomputed from the updated `disk_cache` instead of trusting the subset sum directly.
- If a dirty-subset refresh reports partial errors, that cycle fails and the caller falls back to a full refresh to recover consistency.
- If a dirty-subset refresh reports partial errors, that cycle fails and preserves the last published cache and pending dirty marks.
## Relationship to the RustFS Main Flow
This crate provides capacity primitives only. The actual RustFS integration lives in `rustfs/src/capacity/service.rs`.
`rustfs/src/capacity/service.rs` starts the background capacity manager with a provider that discovers local disks on each scheduled refresh. The manager publishes the cached estimate as `rustfs_capacity_current_bytes`. The admin storage usage view comes from the storage information API.
The high-level flow is:
1. Startup calls `init_capacity_management_for_local_disks()`.
2. It collects all local disks and calls `capacity_manager::start_background_task(...)`.
3. Admin used-capacity queries first try the `HybridCapacityManager` cache.
4. If the cache is fresh enough, the cached value is returned directly.
5. If the cache is stale but still acceptable, the stale value is served and a background refresh is triggered.
6. If the cache is very stale and the write rate is high, the request blocks on a foreground refresh.
7. If the initial real-time scan fails, the service falls back to externally supplied disk-used capacity and stores it as `Fallback`.
`crates/ecstore/src/set_disk.rs` is responsible for recording capacity scopes during object writes, heal operations, data movement, and related flows, so this crate can learn which disks were affected.
`crates/ecstore/src/set_disk/mod.rs` records capacity scopes so object writes, heal operations, and data movement can mark affected disks dirty.
## Public API
@@ -288,6 +278,7 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | Cache age required before fast refresh is considered |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | Exact-count file threshold |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Base scan timeout |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | On Linux, use filesystem-reported used space on eligible dedicated drive mounts |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | Overflow-file sampling interval |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | Runtime summary emission interval |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | Whether to follow symlinks |
@@ -296,6 +287,8 @@ The configuration constants are defined in `crates/config/src/constants/capacity
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` (`60s` with `RUSTFS_DRIVE_TIMEOUT_PROFILE=high_latency`) | Dynamic-timeout upper bound |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | Stall-detection threshold |
On Linux, `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true` enables direct readings on whole XFS, ext-family, and tmpfs mounts used exclusively by RustFS. The fast path requires kernel mount IDs and the process mount table. A symlink used as the drive root resolves to its target. Subdirectory bind mounts, multiple views of a device, mounts with child mounts, and pooled filesystems such as Btrfs or ZFS use directory scanning. The reading estimates used capacity from allocated filesystem blocks, which can include metadata and differ from summed file lengths. Direct readings do not count files. When a directory scan in this mode times out, it estimates usage from available file samples. Other platforms and configurations that follow symlinks within the drive use the default scan behavior. Restart RustFS after changing this setting.
Explicit `RUSTFS_CAPACITY_STAT_TIMEOUT` and `RUSTFS_CAPACITY_MAX_TIMEOUT` values
take precedence over the drive-timeout profile.
+9 -16
View File
@@ -169,34 +169,24 @@ crate 不是“超时就直接失败”的设计:
- `disk_cache_complete == true`
- 也就是系统已经完成过一次“无部分错误”的全盘刷新
- 并且成功拿到了每盘缓存
- 并且每盘缓存覆盖当前本地盘集合
若当前还没有任何聚合缓存,系统会先执行一次全盘刷新来建立初始值。已有聚合缓存后,定时刷新在没有脏盘时会保持 idle,不再重复遍历未变化的磁盘。若 per-disk cache 尚不完整但存在脏盘,系统仍执行全盘刷新,因为此时不能安全合并子集结果。
首次刷新会建立聚合基线。没有脏盘且原基线仍适用时,定时刷新保持空闲。本地盘成员变化时触发全量刷新,包括盘数相同的替换。存在脏盘但每盘基线不完整时,也执行全量刷新。
全盘刷新达到时间预算后,可以发布估算聚合值,但不会借此建立完整 per-disk 基线。该有界估算会确认扫描开始前的脏标记;扫描过程中记录的新标记仍会保留。这样既不会把估算值当成精确值,也不会让一个旧脏标记永久触发超时循环。
全盘刷新达到时间预算后,可以发布估算聚合值。拓扑变化后的全量刷新若超时或降级,会丢弃旧的每盘基线,并发布当前可用的聚合值。超时估算会确认扫描开始前的脏标记,扫描过程中记录的新标记仍会保留。
### 子集刷新后的合并规则
- 全盘刷新成功时,`per_disk` 会完整替换 `disk_cache`。
- dirty subset 刷新成功时,只更新对应脏盘的缓存条目。
- 总容量会基于更新后的 `disk_cache` 重新求和,而不是盲信子集扫描返回的局部和。
- 若 dirty subset 刷新出现 partial errors,则当前轮次失败,并回退到全盘刷新恢复一致性。
- 若脏盘子集刷新出现部分错误,则本轮失败,保留上次发布的缓存和待处理脏标记。
## 与 RustFS 主流程的关系
这个 crate 本身只提供容量能力,真正把它接到 RustFS 主流程的是 `rustfs/src/capacity/service.rs`。
`rustfs/src/capacity/service.rs` 启动后台容量管理器,并在每轮定时刷新时发现当前本地盘。管理器通过 `rustfs_capacity_current_bytes` 发布缓存的容量估算值。管理接口的存储用量取自存储信息 API。
上层使用方式大致如下:
1. 启动时调用 `init_capacity_management_for_local_disks()`。
2. 它收集所有本地盘,调用 `capacity_manager::start_background_task(...)`。
3. 管理接口查询 used capacity 时,优先读 `HybridCapacityManager` 缓存。
4. 缓存足够新时直接返回。
5. 缓存过旧但还可容忍时,先返回 stale cache,再后台刷新。
6. 缓存极旧且写入频率高时,前台阻塞刷新。
7. 若首次实时扫描失败,则退回外部已有的磁盘 used capacity,并写入 `Fallback` 缓存。
`crates/ecstore/src/set_disk.rs` 中则负责在对象写入、heal、data movement 等流程里记录 capacity scope,把“这次写影响了哪些盘”传播给本 crate。
`crates/ecstore/src/set_disk/mod.rs` 记录容量作用域,以便对象写入、修复和数据迁移标记受影响的磁盘。
## 公开 API
@@ -288,6 +278,7 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_FAST_UPDATE_THRESHOLD` | `120s` | 缓存超过该年龄后才考虑快速刷新 |
| `RUSTFS_CAPACITY_MAX_FILES_THRESHOLD` | `200000` | 精确统计文件数阈值 |
| `RUSTFS_CAPACITY_STAT_TIMEOUT` | `3s` | 基础扫描超时 |
| `RUSTFS_CAPACITY_USE_MOUNT_USAGE` | `false` | 在 Linux 上直接读取符合条件的独占挂载用量 |
| `RUSTFS_CAPACITY_SAMPLE_RATE` | `200` | overflow 文件采样间隔 |
| `RUSTFS_CAPACITY_METRICS_INTERVAL` | `600s` | runtime summary 打点间隔 |
| `RUSTFS_CAPACITY_FOLLOW_SYMLINKS` | `false` | 是否跟随符号链接 |
@@ -296,6 +287,8 @@ get_capacity_manager()
| `RUSTFS_CAPACITY_MAX_TIMEOUT` | `15s` | 动态超时上界 |
| `RUSTFS_CAPACITY_STALL_TIMEOUT` | `20s` | 无进展 stall 判定阈值 |
在 Linux 上设置 `RUSTFS_CAPACITY_USE_MOUNT_USAGE=true`,可直接读取 RustFS 独占的 XFS、ext 系列和 tmpfs 整卷挂载。快速路径依赖内核挂载 ID 和进程挂载表,磁盘根路径是符号链接时会解析到目标。子目录 bind mount、同一设备的多个挂载视图、带子挂载的卷,以及 Btrfs、ZFS 等共享池文件系统走目录扫描。直接读取按已分配块估算容量,可能包含元数据,也可能与文件长度之和不同,无文件计数。此模式下目录扫描超时时,使用已有的文件样本估算。其他平台或启用盘内符号链接跟随时走默认扫描。更改设置后需重启 RustFS。
### 配置缓存注意事项
在非测试构建中,配置通过 `OnceLock` 缓存:
+161 -52
View File
@@ -29,6 +29,8 @@ use rustfs_config::{
ENV_CAPACITY_STAT_TIMEOUT, ENV_CAPACITY_WRITE_FREQUENCY_THRESHOLD, ENV_CAPACITY_WRITE_TRIGGER_DELAY,
ENV_DRIVE_TIMEOUT_PROFILE,
};
#[cfg(target_os = "linux")]
use rustfs_config::{DEFAULT_CAPACITY_USE_MOUNT_USAGE, ENV_CAPACITY_USE_MOUNT_USAGE};
use rustfs_io_metrics::capacity_metrics::{
record_capacity_current_bytes, record_capacity_degraded_reading, record_capacity_dirty_disk_count,
record_capacity_refresh_inflight, record_capacity_refresh_joiner, record_capacity_refresh_result,
@@ -86,6 +88,8 @@ struct CachedCapacityConfig {
metrics_interval: Duration,
/// Follow symlinks flag
follow_symlinks: bool,
#[cfg(target_os = "linux")]
use_mount_usage: bool,
/// Enable dynamic timeout flag
enable_dynamic_timeout: bool,
/// Min timeout
@@ -153,6 +157,8 @@ impl CachedCapacityConfig {
DEFAULT_CAPACITY_METRICS_INTERVAL_SECS,
)),
follow_symlinks: get_env_bool(ENV_CAPACITY_FOLLOW_SYMLINKS, DEFAULT_CAPACITY_FOLLOW_SYMLINKS),
#[cfg(target_os = "linux")]
use_mount_usage: get_env_bool(ENV_CAPACITY_USE_MOUNT_USAGE, DEFAULT_CAPACITY_USE_MOUNT_USAGE),
enable_dynamic_timeout: get_env_bool(ENV_CAPACITY_ENABLE_DYNAMIC_TIMEOUT, DEFAULT_CAPACITY_ENABLE_DYNAMIC_TIMEOUT),
min_timeout: Duration::from_secs(env_u64_at_least(ENV_CAPACITY_MIN_TIMEOUT, DEFAULT_CAPACITY_MIN_TIMEOUT_SECS, 1)),
max_timeout: Duration::from_secs(env_u64_at_least(
@@ -285,6 +291,11 @@ pub fn get_follow_symlinks() -> bool {
get_cached_config().follow_symlinks
}
#[cfg(target_os = "linux")]
pub(crate) fn get_use_mount_usage() -> bool {
get_cached_config().use_mount_usage
}
/// Get enable dynamic timeout flag from environment or default
#[cfg(not(test))]
pub fn get_enable_dynamic_timeout() -> bool {
@@ -353,8 +364,7 @@ pub struct CapacityUpdate {
/// Whether the value is estimated instead of exact.
pub is_estimated: bool,
/// Whether the refresh behind this update had partial disk failures.
/// `is_estimated` only reflects sampling; this flag is the only carrier of
/// the "some disks failed to scan" fact (backlog#1014).
/// Independent of `is_estimated`, which describes how bytes were measured.
pub degraded: bool,
/// Whether the scan reached its time budget and returned a fallback estimate.
pub timed_out: bool,
@@ -754,7 +764,6 @@ pub struct HybridCapacityManager {
/// Per-disk cache populated after a successful full refresh and updated by dirty subset refreshes.
disk_cache: Arc<RwLock<HashMap<CapacityScopeDisk, CachedDiskCapacity>>>,
/// Whether the per-disk cache currently covers all known disks.
disk_cache_complete: Arc<RwLock<bool>>,
/// Configuration
config: HybridStrategyConfig,
/// Shared singleflight refresh state
@@ -787,7 +796,6 @@ impl HybridCapacityManager {
write_record: Arc::new(WriteRecord::new()),
dirty_disks: Arc::new(RwLock::new(HashMap::new())),
disk_cache: Arc::new(RwLock::new(HashMap::new())),
disk_cache_complete: Arc::new(RwLock::new(false)),
config,
refresh_state: Arc::new(Mutex::new(RefreshState::default())),
}
@@ -811,57 +819,62 @@ impl HybridCapacityManager {
/// only the scanned subset's totals; callers that publish or return this value (e.g. the
/// `refresh_or_join` leader and joiners, admin used-capacity) must use the reconciled copy
/// so they never report the subset bytes as the whole-cluster total.
pub async fn update_capacity(&self, mut update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
pub async fn update_capacity(&self, update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
self.commit_capacity(update, source, None).await
}
async fn commit_capacity(
&self,
mut update: CapacityUpdate,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
) -> CapacityUpdate {
let start = Instant::now();
if !update.per_disk.is_empty() || update.degraded {
let mut disk_cache = self.disk_cache.write().await;
let mut disk_cache_complete = self.disk_cache_complete.write().await;
let recompute = if !update.per_disk.is_empty()
let replaces_cache = !update.per_disk.is_empty()
&& update.replaces_disk_cache
&& update.expected_disk_count == Some(update.per_disk.len())
{
&& update.expected_disk_count == Some(update.per_disk.len());
if replaces_cache {
disk_cache.clear();
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
} else if !disk_cache.is_empty()
&& let Some(disks) = full_scan_disks
{
// A bounded full scan may publish bytes without establishing a
// baseline. Do not merge a previous topology into that result.
let local: HashSet<_> = disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
if disk_cache.len() != local.len()
|| !disk_cache
.keys()
.all(|disk| local.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
{
disk_cache.clear();
}
*disk_cache_complete = true;
true
} else if *disk_cache_complete {
// Merging over a complete cache also covers a degraded
// (partial-failure) full refresh: successfully scanned disks
// are refreshed while failed disks keep their last-known
// values, so the published total does not dip to the
// surviving-subset sum and bounce back on the next refresh.
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
true
} else {
false
};
}
if recompute {
// Reconcile cluster-wide aggregates from the full per-disk cache so a
// dirty-subset refresh reports the merged cluster totals, not the subset sum.
update.total_used = disk_cache.values().map(|entry| entry.used_bytes).sum();
update.file_count = disk_cache.values().map(|entry| entry.file_count).sum();
update.is_estimated = disk_cache.values().any(|entry| entry.is_estimated);
// A nonempty disk cache always covers one complete topology. A
// degraded refresh on that topology keeps last-known disk entries.
if replaces_cache || !disk_cache.is_empty() {
for entry in &update.per_disk {
disk_cache.insert(
entry.disk.clone(),
CachedDiskCapacity {
used_bytes: entry.used_bytes,
file_count: entry.file_count,
is_estimated: entry.is_estimated,
},
);
}
let (bytes, files, estimated) = disk_cache.values().fold((0, 0, false), |(bytes, files, estimated), entry| {
(bytes + entry.used_bytes, files + entry.file_count, estimated || entry.is_estimated)
});
update.total_used = bytes;
update.file_count = files;
update.is_estimated = estimated;
}
}
@@ -1051,15 +1064,33 @@ impl HybridCapacityManager {
/// Returns true if the manager has a complete per-disk cache and can safely refresh only dirty disks.
pub async fn can_refresh_dirty_subset(&self) -> bool {
*self.disk_cache_complete.read().await
!self.disk_cache.read().await.is_empty()
}
pub(crate) async fn disk_cache_matches(&self, local: &HashSet<CapacityScopeDisk>) -> Option<bool> {
let cache = self.disk_cache.read().await;
(!cache.is_empty()).then(|| cache.len() == local.len() && cache.keys().all(|disk| local.contains(disk)))
}
/// Run a singleflight refresh. Callers either join an existing in-flight refresh or become the leader.
///
/// Joiners subscribe to the watch channel *before* releasing the mutex, which guarantees
/// they cannot miss the completion notification even if the leader finishes very quickly.
#[hotpath::measure]
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
{
self.refresh_or_join_for_disks(source, None, refresh_fn).await
}
#[hotpath::measure]
async fn refresh_or_join_for_disks<F, Fut>(
&self,
source: DataSource,
full_scan_disks: Option<&[CapacityDiskRef]>,
refresh_fn: F,
) -> Result<CapacityUpdate, String>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Result<CapacityUpdate, String>>,
@@ -1141,7 +1172,7 @@ impl HybridCapacityManager {
// returned to this caller and the one published to joiners carry the cluster totals
// rather than a dirty-subset's partial bytes.
let result = match result {
Ok(update) => Ok(self.update_capacity(update, source).await),
Ok(update) => Ok(self.commit_capacity(update, source, full_scan_disks).await),
Err(err) => Err(err),
};
let refresh_duration = refresh_start.elapsed();
@@ -1427,8 +1458,8 @@ async fn run_scheduled_capacity_refresh(manager: Arc<HybridCapacityManager>, dis
"capacity refresh scheduled"
);
let result = manager
.refresh_or_join(DataSource::Scheduled, move || async move {
refresh_capacity_with_scope(disks, dirty_subset).await
.refresh_or_join_for_disks(DataSource::Scheduled, (!dirty_subset).then_some(disks.as_slice()), || {
refresh_capacity_with_scope(&disks, dirty_subset)
})
.await;
scheduled_refresh_was_clean(&result)
@@ -2476,6 +2507,84 @@ mod tests {
assert!(!cached.degraded);
}
#[tokio::test]
async fn test_degraded_refresh_after_replacement_drops_retired_capacity() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
let temp = tempfile::TempDir::new().expect("create capacity fixture");
let active = temp.path().join("active");
let replacement = temp.path().join("replacement");
std::fs::create_dir(&active).expect("create active disk");
std::fs::write(active.join("object"), b"abc").expect("write active disk data");
let active = active.to_str().expect("UTF-8 active path");
let replacement_path = replacement.to_str().expect("UTF-8 replacement path");
let mut old = full_two_disk_update();
old.per_disk[0] = disk_entry("active", active, 100, 1);
manager.update_capacity(old, DataSource::Scheduled).await;
let current = vec![
CapacityDiskRef {
endpoint: "active".into(),
drive_path: active.into(),
},
CapacityDiskRef {
endpoint: "replacement".into(),
drive_path: replacement_path.into(),
},
];
assert!(!run_scheduled_capacity_refresh(manager.clone(), current.clone()).await);
let published = manager.get_capacity().await.expect("publish degraded refresh");
assert!(published.degraded);
assert_eq!(published.total_used, 3);
assert!(!manager.can_refresh_dirty_subset().await);
assert_eq!(
select_scheduled_capacity_refresh(&manager, &current).await,
ScheduledCapacityRefresh::Idle
);
std::fs::create_dir(&replacement).expect("make replacement readable");
std::fs::write(replacement.join("object"), b"12345").expect("write replacement disk data");
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![scope_disk("replacement", replacement_path)],
})
.await;
assert!(run_scheduled_capacity_refresh(manager.clone(), current).await);
let published = manager.get_capacity().await.expect("publish recovered refresh");
assert_eq!(published.total_used, 8);
assert!(!published.degraded);
assert!(manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_timed_out_full_refresh_after_replacement_uses_current_estimate() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
manager.update_capacity(full_two_disk_update(), DataSource::Scheduled).await;
let current = [
CapacityDiskRef {
endpoint: "node-a".into(),
drive_path: "/tmp/disk-a".into(),
},
CapacityDiskRef {
endpoint: "node-c".into(),
drive_path: "/tmp/disk-c".into(),
},
];
let mut timed_out = CapacityUpdate::estimated(160, 2);
timed_out.timed_out = true;
timed_out.per_disk = vec![
disk_entry("node-a", "/tmp/disk-a", 60, 1),
disk_entry("node-c", "/tmp/disk-c", 100, 1),
];
let published = manager
.refresh_or_join_for_disks(DataSource::Scheduled, Some(&current), || async { Ok(timed_out) })
.await
.expect("publish bounded full refresh");
assert_eq!(published.total_used, 160);
assert!(published.timed_out);
assert!(published.is_estimated);
assert!(!manager.can_refresh_dirty_subset().await);
}
#[tokio::test]
async fn test_update_capacity_degraded_with_empty_per_disk_serves_merged_cache() {
let manager = create_isolated_manager(HybridStrategyConfig::default());
+168 -52
View File
@@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(target_os = "linux")]
use super::capacity_manager::get_use_mount_usage;
use super::capacity_manager::{
CapacityUpdate, DiskCapacityUpdate, HybridCapacityManager, get_enable_dynamic_timeout, get_follow_symlinks,
get_max_files_threshold, get_max_timeout, get_min_timeout, get_sample_rate, get_stat_timeout,
@@ -23,6 +25,8 @@ use rustfs_io_metrics::capacity_metrics::{
record_capacity_dynamic_timeout, record_capacity_scan_disk, record_capacity_scan_mode, record_capacity_scan_sampling,
record_capacity_timeout_fallback,
};
#[cfg(target_os = "linux")]
use rustfs_utils::os::MountUsageSnapshot;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::{Component, Path};
@@ -198,10 +202,10 @@ fn is_tmp_trash_metadata_not_found(scan_root: &Path, entry_path: &Path, error_ki
&& components.all(|component| matches!(component, Component::Normal(_)))
}
async fn scan_disk_used_capacity(disk: CapacityDiskRef) -> DiskScanOutcome {
async fn scan_disk_used_capacity(disk: CapacityDiskRef, limits: ScanLimits) -> DiskScanOutcome {
let disk_label = disk_metric_label(&disk);
let start = Instant::now();
let result = get_dir_size_async(Path::new(&disk.drive_path)).await;
let result = get_dir_size_async(Path::new(&disk.drive_path), limits).await;
let disk = CapacityScopeDisk {
endpoint: disk.endpoint,
drive_path: disk.drive_path,
@@ -232,7 +236,14 @@ async fn calculate_data_dir_used_capacity_report(
let mut per_disk = Vec::with_capacity(disks.len());
let concurrency_limit = disks.len().clamp(1, MAX_CAPACITY_SCAN_CONCURRENCY);
let mut scans = stream::iter(disks.iter().cloned().map(scan_disk_used_capacity)).buffer_unordered(concurrency_limit);
let limits = ScanLimits::from_env();
let mut scans = stream::iter(
disks
.iter()
.cloned()
.map(|disk| scan_disk_used_capacity(disk, limits.clone())),
)
.buffer_unordered(concurrency_limit);
while let Some(outcome) = scans.next().await {
match outcome.result {
@@ -351,38 +362,43 @@ pub(crate) async fn select_scheduled_capacity_refresh(
// entries so the dirty gauge reflects local pending work (backlog#1020).
let local_set: HashSet<CapacityScopeDisk> = disks.iter().map(disk_scope_key).collect();
capacity_manager.retain_dirty_disks_within(&local_set).await;
if disks.is_empty() {
return ScheduledCapacityRefresh::Idle;
}
let full_scan = || ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
let cached_topology_matches = capacity_manager.disk_cache_matches(&local_set).await;
if cached_topology_matches == Some(false) {
return full_scan();
}
let dirty_disks = capacity_manager.get_dirty_disks().await;
if dirty_disks.is_empty() {
return if disks.is_empty() || capacity_manager.get_capacity().await.is_some() {
return if capacity_manager.get_capacity().await.is_some() {
ScheduledCapacityRefresh::Idle
} else {
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
full_scan()
};
}
if !capacity_manager.can_refresh_dirty_subset().await {
return ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
};
if cached_topology_matches.is_none() {
return full_scan();
}
let dirty_set: HashSet<CapacityScopeDisk> = dirty_disks.into_iter().collect();
let dirty_set: HashSet<_> = dirty_disks
.iter()
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
.collect();
let selected: Vec<_> = disks
.iter()
.filter(|disk| dirty_set.contains(&disk_scope_key(disk)))
.filter(|disk| dirty_set.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
.cloned()
.collect();
if selected.is_empty() || selected.len() >= disks.len() {
ScheduledCapacityRefresh::Scan {
disks: disks.to_vec(),
dirty_subset: false,
}
full_scan()
} else {
ScheduledCapacityRefresh::Scan {
disks: selected,
@@ -404,9 +420,13 @@ pub async fn select_capacity_refresh_disks(
}
#[hotpath::measure]
pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subset: bool) -> Result<CapacityUpdate, String> {
pub async fn refresh_capacity_with_scope(
disks: impl AsRef<[CapacityDiskRef]>,
dirty_subset: bool,
) -> Result<CapacityUpdate, String> {
let disks = disks.as_ref();
let scan_started_at = Instant::now();
let report = calculate_data_dir_used_capacity_report(&disks)
let report = calculate_data_dir_used_capacity_report(disks)
.await
.map_err(|e| e.to_string())?;
@@ -421,8 +441,8 @@ pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subs
/// Scan the provided local disk roots and return a summarized used-capacity result.
///
/// This is primarily intended for benchmarks and operational tooling that need to exercise
/// the same scan path as admin capacity queries without going through the full admin stack.
/// This is intended for benchmarks and operational tooling that need the same scan path
/// as background capacity refreshes. Direct filesystem readings do not count files.
pub async fn scan_used_capacity_disks(
disks: &[CapacityDiskRef],
) -> Result<CapacityScanSummary, Box<dyn std::error::Error + Send + Sync>> {
@@ -551,6 +571,8 @@ struct ScanLimits {
sample_rate: usize,
enable_dynamic_timeout: bool,
follow_symlinks: bool,
#[cfg(target_os = "linux")]
mount_usage: Option<Arc<MountUsageSnapshot>>,
}
impl ScanLimits {
@@ -572,6 +594,7 @@ impl ScanLimits {
sample_rate
};
let follow_symlinks = get_follow_symlinks();
Self {
max_files_threshold: get_max_files_threshold(),
base_timeout: get_stat_timeout(),
@@ -579,15 +602,15 @@ impl ScanLimits {
max_timeout: get_max_timeout(),
sample_rate: effective_sample_rate,
enable_dynamic_timeout: get_enable_dynamic_timeout(),
follow_symlinks: get_follow_symlinks(),
follow_symlinks,
#[cfg(target_os = "linux")]
mount_usage: (get_use_mount_usage() && !follow_symlinks).then(|| Arc::new(MountUsageSnapshot::default())),
}
}
}
/// Filesystem-level used bytes for `path`, only when `path` is a dedicated
/// mount point. On a shared filesystem (several logical disks per filesystem,
/// common in dev deployments) statvfs counts unrelated data and would badly
/// overcount, so `None` is returned and callers keep scan-based estimates.
/// Filesystem usage at a device boundary. This check cannot establish sole
/// ownership or distinguish a whole filesystem from a cross-device bind mount.
fn mount_point_used_bytes(path: &Path) -> Option<u64> {
let parent = path.parent()?;
let dedicated = !rustfs_utils::os::same_disk(path.to_str()?, parent.to_str()?).ok()?;
@@ -624,7 +647,7 @@ fn combine_timeout_estimates(seen_estimate: Option<u64>, disk_used: Option<u64>,
/// then propagates the original error, as before.
#[allow(clippy::too_many_arguments)]
fn timeout_fallback_estimate(
path: &Path,
fallback_mount_path: Option<&Path>,
reason: &'static str,
exact_prefix_bytes: u64,
overflow_sampled_bytes: u64,
@@ -639,7 +662,7 @@ fn timeout_fallback_estimate(
let estimated_overflow = estimate_overflow_bytes(overflow_sampled_bytes, overflow_count as u64, sampled_count as u64);
exact_prefix_bytes.saturating_add(estimated_overflow)
});
let disk_used = mount_point_used_bytes(path);
let disk_used = fallback_mount_path.and_then(mount_point_used_bytes);
let used_bytes = combine_timeout_estimates(seen_estimate, disk_used, exact_prefix_bytes)?;
info!(
@@ -699,9 +722,8 @@ impl Drop for ScanCancellationGuard {
}
}
async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::Error> {
async fn get_dir_size_async(path: &Path, limits: ScanLimits) -> Result<CapacityScanResult, std::io::Error> {
let path = path.to_path_buf();
let limits = ScanLimits::from_env();
let budget = outer_scan_budget(&limits);
// The blocking thread cannot be killed; on ceiling expiry the caller (and
@@ -734,6 +756,13 @@ async fn get_dir_size_async(path: &Path) -> Result<CapacityScanResult, std::io::
}
fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -> Result<CapacityScanResult, std::io::Error> {
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled before starting",
));
}
let ScanLimits {
max_files_threshold,
base_timeout,
@@ -742,13 +771,28 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
sample_rate: effective_sample_rate,
enable_dynamic_timeout,
follow_symlinks,
..
} = *limits;
{
if !path.exists() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Directory not found: {:?}", path),
));
#[cfg(target_os = "linux")]
if let Some(mount_usage) = &limits.mount_usage {
let start_time = Instant::now();
let used_bytes = mount_usage.used_bytes(path);
if cancelled.load(Ordering::Relaxed) {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"capacity scan cancelled while reading mount usage",
));
}
if let Some(used_bytes) = used_bytes {
record_capacity_scan_mode("mount_usage");
return Ok(CapacityScanResult {
used_bytes,
is_estimated: true,
scan_duration: start_time.elapsed(),
..Default::default()
});
}
}
// Resolve the scan root before walking. A drive_path that is itself a
@@ -761,7 +805,13 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
.map_err(|err| std::io::Error::new(err.kind(), format!("failed to resolve scan root {path:?}: {err}")))?;
let path = resolved_root.as_path();
// Opt-in scans that rejected a mount must not count its whole filesystem on timeout.
#[cfg(target_os = "linux")]
let fallback_mount_path = limits.mount_usage.is_none().then_some(path);
#[cfg(not(target_os = "linux"))]
let fallback_mount_path = Some(path);
let start_time = Instant::now();
let mut exact_prefix_bytes = 0u64;
let mut overflow_sampled_bytes = 0u64;
let mut file_count = 0usize;
@@ -816,7 +866,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
Ok(half_elapsed) => half_elapsed,
Err(e) => {
if let Some(result) = timeout_fallback_estimate(
path,
fallback_mount_path,
"timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -989,7 +1039,7 @@ fn scan_dir_blocking(path: &Path, limits: &ScanLimits, cancelled: &AtomicBool) -
if let Err(e) = progress_monitor.update_and_check_timeout(file_count, avg_size) {
if let Some(result) = timeout_fallback_estimate(
path,
fallback_mount_path,
"final_timeout",
exact_prefix_bytes,
overflow_sampled_bytes,
@@ -1220,6 +1270,8 @@ mod tests {
sample_rate: 3,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
};
let result =
@@ -1236,7 +1288,7 @@ mod tests {
#[test]
fn test_timeout_fallback_is_marked_for_scheduler_backoff() {
let temp_dir = tempfile::TempDir::new().expect("capacity scan tempdir should be created");
let result = timeout_fallback_estimate(temp_dir.path(), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
let result = timeout_fallback_estimate(Some(temp_dir.path()), "timeout", 10, 5, 2, 1, 1, false, Instant::now())
.expect("sampled timeout should produce a fallback estimate");
assert!(result.timed_out);
@@ -1248,7 +1300,7 @@ mod tests {
use tempfile::TempDir;
let temp_dir = TempDir::new().unwrap();
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 0);
assert_eq!(size.file_count, 0);
}
@@ -1265,7 +1317,7 @@ mod tests {
file.write_all(b"Hello, World!").unwrap();
drop(file);
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 13);
assert_eq!(size.file_count, 1);
}
@@ -1284,7 +1336,7 @@ mod tests {
file.write_all(b"test").unwrap();
}
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 40);
assert_eq!(size.file_count, 10);
}
@@ -1309,14 +1361,14 @@ mod tests {
f2.write_all(b"content2").unwrap();
drop(f2);
let size = get_dir_size_async(temp_dir.path()).await.unwrap();
let size = get_dir_size_async(temp_dir.path(), ScanLimits::from_env()).await.unwrap();
assert_eq!(size.used_bytes, 16);
assert_eq!(size.file_count, 2);
}
#[tokio::test]
async fn test_get_dir_size_async_nonexistent_directory() {
let result = get_dir_size_async(Path::new("/nonexistent/path")).await;
let result = get_dir_size_async(Path::new("/nonexistent/path"), ScanLimits::from_env()).await;
assert!(result.is_err());
}
@@ -1424,12 +1476,45 @@ mod tests {
assert_eq!(combine_timeout_estimates(None, None, 40), None);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_point_used_bytes_rejects_shared_filesystem_path() {
// A tempdir lives on the same filesystem as its parent, so statvfs
// must not be trusted as a per-disk proxy there.
let temp_dir = tempfile::TempDir::new().unwrap();
assert_eq!(mount_point_used_bytes(temp_dir.path()), None);
fn test_mount_usage_keeps_directory_scan_on_shared_filesystem() {
let temp_dir = tempfile::TempDir::new().expect("create shared-filesystem scan root");
std::fs::write(temp_dir.path().join("object"), b"object bytes").expect("write object fixture");
let limits = ScanLimits {
mount_usage: Some(Arc::new(MountUsageSnapshot::default())),
..tight_limits(Duration::from_secs(60))
};
let scan = scan_dir_blocking(temp_dir.path(), &limits, &AtomicBool::new(false)).expect("scan shared directory");
assert_eq!(scan.used_bytes, 12);
assert_eq!(scan.file_count, 1);
assert!(!scan.is_estimated);
}
#[cfg(target_os = "linux")]
#[test]
fn test_mount_usage_completes_without_walk_budget() {
// Docker and normal Linux hosts mount /dev/shm as a separate tmpfs.
let path = Path::new("/dev/shm");
let mount_usage = Arc::new(MountUsageSnapshot::default());
if mount_usage.used_bytes(path).is_none() {
return;
}
let limits = ScanLimits {
mount_usage: Some(mount_usage),
..tight_limits(Duration::ZERO)
};
let temp_dir = tempfile::TempDir::new().expect("create symlink fixture directory");
let drive_link = temp_dir.path().join("drive");
std::os::unix::fs::symlink(path, &drive_link).expect("link to mount root");
for root in [path, drive_link.as_path()] {
let scan = scan_dir_blocking(root, &limits, &AtomicBool::new(false)).expect("read usage at a mount root");
assert!(scan.is_estimated);
assert!(!scan.timed_out);
assert!(!scan.metadata_incomplete);
assert_eq!(scan.file_count, 0);
assert_eq!(scan.metadata_reads, 0);
}
}
#[test]
@@ -1452,6 +1537,8 @@ mod tests {
sample_rate: 1,
enable_dynamic_timeout: false,
follow_symlinks: false,
#[cfg(target_os = "linux")]
mount_usage: None,
}
}
@@ -1851,6 +1938,35 @@ mod tests {
assert_eq!(selected.len(), 1);
assert_eq!(selected[0].endpoint, "disk-2");
assert_eq!(selected[0].drive_path, "/tmp/disk-2");
let replacement = vec![
disks[0].clone(),
CapacityDiskRef {
endpoint: "disk-3".into(),
drive_path: "/tmp/disk-3".into(),
},
];
// Replacing a disk changes membership even when the disk count stays
// the same and the only dirty mark belonged to the removed disk.
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement.clone(),
dirty_subset: false,
}
);
manager
.mark_dirty_scope(&CapacityScope {
disks: vec![disk_scope_key(&replacement[1])],
})
.await;
assert_eq!(
select_scheduled_capacity_refresh(manager.as_ref(), &replacement).await,
ScheduledCapacityRefresh::Scan {
disks: replacement,
dirty_subset: false,
}
);
}
#[cfg(unix)]
@@ -1869,7 +1985,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("false"))], async {
get_dir_size_async(scan_dir.path()).await
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
})
.await
.unwrap();
@@ -1894,7 +2010,7 @@ mod tests {
symlink(&target_path, scan_dir.path().join("external-link")).unwrap();
let size = temp_env::async_with_vars([(ENV_CAPACITY_FOLLOW_SYMLINKS, Some("true"))], async {
get_dir_size_async(scan_dir.path()).await
get_dir_size_async(scan_dir.path(), ScanLimits::from_env()).await
})
.await
.unwrap();
+19 -38
View File
@@ -523,21 +523,9 @@ pub fn assign_site_replication_rule_priorities(
}
}
fn is_iam_role_arn(role: &str) -> bool {
let trimmed = role.trim();
trimmed
.strip_prefix("arn:")
.and_then(|rest| rest.split_once(':'))
.is_some_and(|(_, service_and_rest)| service_and_rest.starts_with("iam:"))
}
pub fn legacy_role_target_arn(role: &str) -> Option<&str> {
let trimmed = role.trim();
(!trimmed.is_empty() && !is_iam_role_arn(trimmed)).then_some(trimmed)
}
pub fn replication_target_arns(config: &PersistedReplicationConfiguration) -> HashSet<String> {
if let Some(role) = legacy_role_target_arn(&config.role) {
let role = config.role.trim();
if !role.is_empty() {
return HashSet::from([role.to_string()]);
}
@@ -550,8 +538,9 @@ pub fn validate_replication_config_target_arns<'a>(
) -> std::result::Result<(), ReplicationTargetValidationError> {
let configured_arns = configured_arns.into_iter().collect::<HashSet<_>>();
let role = config.role.trim();
let destination_arns = active_replication_rule_destination_arns(config);
if legacy_role_target_arn(&config.role).is_some() && destination_arns.len() > 1 {
if !role.is_empty() && destination_arns.len() > 1 {
return Err(ReplicationTargetValidationError::RoleWithMultipleDestinations);
}
@@ -701,7 +690,7 @@ fn actionable_rules_refs<'a>(
}
let target_arn = obj.target_arn.trim();
let role_arn = legacy_role_target_arn(&config.role);
let role_arn = config.role.trim();
let mut rules = Vec::with_capacity(config.rules.len());
let mut decoded_tags: Option<HashMap<String, String>> = None;
@@ -710,7 +699,7 @@ fn actionable_rules_refs<'a>(
continue;
}
if !obj.target_arn.is_empty() && rule.destination.bucket.trim() != target_arn && role_arn != Some(target_arn) {
if !obj.target_arn.is_empty() && rule.destination.bucket.trim() != target_arn && role_arn != target_arn {
continue;
}
@@ -750,10 +739,9 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
fn has_existing_object_replication(&self, arn: &str) -> (bool, bool) {
let mut has_arn = false;
let arn = arn.trim();
let role_arn = legacy_role_target_arn(&self.role);
for rule in &self.rules {
if rule.destination.bucket.trim() == arn || role_arn == Some(arn) {
if rule.destination.bucket.trim() == arn || self.role.trim() == arn {
if !has_arn {
has_arn = true;
}
@@ -829,7 +817,8 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
/// Filter target ARNs and return a slice of the distinct values in the config
fn configured_target_arns(&self) -> HashSet<String> {
if let Some(role) = legacy_role_target_arn(&self.role) {
let role = self.role.trim();
if !role.is_empty() {
return HashSet::from([role.to_string()]);
}
self.rules
@@ -841,7 +830,8 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
}
fn filter_target_arns(&self, obj: &ObjectOpts) -> Vec<String> {
if let Some(role) = legacy_role_target_arn(&self.role) {
let role = self.role.trim();
if !role.is_empty() {
return vec![role.to_string()];
}
@@ -862,7 +852,7 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
}
fn filter_force_delete_target_arns(&self, prefix: &str) -> Vec<String> {
let role = legacy_role_target_arn(&self.role);
let role = self.role.trim();
let mut selected = BTreeMap::<String, (&PersistedReplicationRule, bool)>::new();
for rule in &self.rules {
@@ -875,7 +865,11 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
continue;
}
let target = role.unwrap_or_else(|| rule.destination.bucket.trim());
let target = if role.is_empty() {
rule.destination.bucket.trim()
} else {
role
};
if target.is_empty() {
continue;
}
@@ -905,7 +899,8 @@ impl ReplicationConfigurationExt for PersistedReplicationConfiguration {
fn filter_target_replication_decisions(&self, obj: &ObjectOpts) -> Vec<(String, bool)> {
let rules = self.filter_actionable_rules(obj);
if let Some(role) = legacy_role_target_arn(&self.role) {
let role = self.role.trim();
if !role.is_empty() {
let mut selected = None;
for rule in &rules {
if selected.is_none_or(|current: &PersistedReplicationRule| rule.priority > current.priority) {
@@ -1435,20 +1430,6 @@ mod tests {
.expect("disabled rules should not require live targets");
}
#[test]
fn validate_replication_config_target_arns_ignores_aws_iam_role_arn() {
let arn_a = "arn:rustfs:replication:us-east-1:target-a:bucket";
let arn_b = "arn:rustfs:replication:us-east-1:target-b:bucket";
let config = PersistedReplicationConfiguration {
role: "arn:aws:iam::123456789012:role/s3-replication".to_string(),
rules: vec![replication_rule("rule-a", arn_a), replication_rule("rule-b", arn_b)],
};
validate_replication_config_target_arns([arn_a, arn_b], &config)
.expect("AWS IAM role ARN should delegate target resolution to rule destination ARNs");
assert_eq!(replication_target_arns(&config), HashSet::from([arn_a.to_string(), arn_b.to_string()]));
}
#[test]
fn should_remove_replication_target_only_matches_replication_target_arns() {
let target_arns = HashSet::from(["arn:rustfs:replication:us-east-1:removed:bucket".to_string()]);
+4 -4
View File
@@ -35,10 +35,10 @@ pub use config::{
REPLICATION_READ_ONLY_HISTORICAL_FIELDS, REPLICATION_WRITABLE_FIELDS, ReplicationConfigStructureError,
ReplicationConfigurationExt, ReplicationTargetValidationError, active_replication_rule_destination_arns,
assign_site_replication_rule_priorities, invalid_replication_config_status_field, is_reconciler_owned_site_replication_rule,
is_site_replication_role, is_site_replication_rule, legacy_role_target_arn, merge_incoming_replication_config,
merge_user_replication_config, replication_target_arn_deployment_id, replication_target_arns,
should_remove_replication_target, site_replication_rule_deployment_id, unsupported_replication_config_field,
validate_replication_config_structure, validate_replication_config_target_arns,
is_site_replication_role, is_site_replication_rule, merge_incoming_replication_config, merge_user_replication_config,
replication_target_arn_deployment_id, replication_target_arns, should_remove_replication_target,
site_replication_rule_deployment_id, unsupported_replication_config_field, validate_replication_config_structure,
validate_replication_config_target_arns,
};
pub use delete::{
DeletedObjectReplicationInfo, delete_marker_purge_mrf_entry, delete_marker_purge_version_id,
-11
View File
@@ -295,17 +295,6 @@ impl Settlement {
counter!("rustfs_scanner_heal_candidate_terminal_total",
"disposition" => self.disposition, "scope" => self.scope, "scan_mode" => self.mode.as_str())
.increment(self.candidates);
if self.scope != "dry_run" {
let source = match self.mode {
HealScanMode::Deep => rustfs_scanner_metrics::metrics::ScannerWorkSource::Bitrot,
HealScanMode::Unknown | HealScanMode::Normal => rustfs_scanner_metrics::metrics::ScannerWorkSource::Heal,
};
if self.execution == "completed" {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_executed(source, self.candidates);
} else if self.execution == "failed" {
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_source_failed(source, self.candidates);
}
}
if self.first_task_observation {
counter!("rustfs_scanner_heal_task_terminal_observations_total").increment(1);
}
-40
View File
@@ -1926,43 +1926,6 @@ where
select_scanner_pause_backlog_replicas(replicas).map_err(|failure| failure.to_string())
}
async fn ensure_no_pending_retiring_pool_handoff<S>(storeapi: Arc<S>, loaded: &LoadedScannerPauseBacklog) -> Result<(), String>
where
S: ScannerStorage,
{
if loaded.durable {
return Ok(());
}
// When a newly expanded cluster immediately starts decommissioning the
// source pool before the scanner has repaired membership onto the new
// writable pool(s), all writable sets read as `Missing` while the
// retiring source pool still holds the authoritative native ledger.
// Bootstrapping an independent generation on the new writable pool(s)
// here would create equal-size or competing source/target commit proofs
// that block decommission retirement (`HandoffConflict`). Defer writer
// bootstrap until decommission hands off and retires the source replica.
let writable_ids = loaded.replicas.iter().map(|replica| replica.id).collect::<BTreeSet<_>>();
let mut retiring_sets = Vec::new();
for set in storeapi.all_set_disks() {
let id = ScannerPauseBacklogReplicaId::from_set(&set).map_err(|err| err.to_string())?;
if !writable_ids.contains(&id) {
retiring_sets.push(set);
}
}
if !retiring_sets.is_empty() {
let retiring_replicas = join_all(retiring_sets.into_iter().map(read_scanner_pause_backlog_replica)).await;
if retiring_replicas
.iter()
.any(|replica| !matches!(replica.state, ScannerPauseBacklogReplicaState::Missing))
{
return Err(
"scanner pause backlog handoff from a retiring pool is still pending on surviving writable sets".to_string(),
);
}
}
Ok(())
}
async fn read_scanner_pause_backlog_replicas<S>(storeapi: Arc<S>) -> Vec<ScannerPauseBacklogReplica>
where
S: ScannerStorage,
@@ -2155,8 +2118,6 @@ where
};
if base.durable && !base.all_current_replicas_stable() {
base = stabilize_scanner_pause_backlog(storeapi.clone(), &base).await?;
} else if !base.durable {
ensure_no_pending_retiring_pool_handoff(storeapi.clone(), &base).await?;
}
let replicas = scanner_pause_backlog_replica_ids(&base.replicas);
@@ -2185,7 +2146,6 @@ where
{
pub(super) async fn claim(storeapi: Arc<S>, now: u64) -> Result<Self, String> {
let loaded = load_scanner_pause_backlog(storeapi.clone()).await?;
ensure_no_pending_retiring_pool_handoff(storeapi.clone(), &loaded).await?;
let ledger = claim_scanner_pause_backlog_writer(&loaded.ledger, now)?;
let loaded = persist_scanner_pause_backlog(storeapi.clone(), &loaded, ledger).await?;
set_runtime_error(None);
+10 -37
View File
@@ -263,15 +263,10 @@ pub fn heal_object_select_prob() -> u32 {
}
fn deep_verify_cooldown() -> Duration {
let default_secs = if rustfs_utils::get_env_opt_str(rustfs_config::ENV_SCANNER_BITROT_CYCLE_SECS)
.and_then(|raw| raw.trim().parse::<u64>().ok())
== Some(0)
{
0
} else {
DEFAULT_SCANNER_DEEP_VERIFY_COOLDOWN_SECS
};
Duration::from_secs(rustfs_utils::get_env_u64(ENV_SCANNER_DEEP_VERIFY_COOLDOWN_SECS, default_secs))
Duration::from_secs(rustfs_utils::get_env_u64(
ENV_SCANNER_DEEP_VERIFY_COOLDOWN_SECS,
DEFAULT_SCANNER_DEEP_VERIFY_COOLDOWN_SECS,
))
}
fn object_is_within_deep_verify_cooldown(mod_time: Option<OffsetDateTime>, now: OffsetDateTime, cooldown: Duration) -> bool {
@@ -377,23 +372,6 @@ fn record_scanner_replication_admission(metrics: &Metrics, roi: &ReplicationHeal
}
}
fn record_scanner_site_replication_admission(
metrics: &Metrics,
roi: &ReplicationHealObject,
admission: ReplicationQueueAdmission,
) {
let work = scanner_replication_work_update(admission);
metrics.record_scanner_source_work(ScannerWorkSource::SiteReplication, work);
if !roi.is_empty_identity() {
let kind = if roi.is_existing_object_repair() {
ScannerReplicationRepairKind::SiteActiveResync
} else {
ScannerReplicationRepairKind::SitePassiveRequeue
};
metrics.record_scanner_replication_repair_work(kind, work);
}
}
fn scanner_heal_source(scan_mode: HealScanMode) -> ScannerWorkSource {
match scan_mode {
HealScanMode::Deep => ScannerWorkSource::Bitrot,
@@ -2644,13 +2622,10 @@ impl FolderScanner {
let work_started = tokio::time::Instant::now();
let heal_bitrot = self.scan_mode == HealScanMode::Deep;
let selected_for_heal = heal_bitrot
|| this_hash.mod_alt(
self.old_cache.info.next_cycle as u32 / folder.object_heal_prob_div,
self.heal_object_select / folder.object_heal_prob_div,
);
let heal_enabled = selected_for_heal && self.try_should_heal().await?;
let heal_enabled = this_hash.mod_alt(
self.old_cache.info.next_cycle as u32 / folder.object_heal_prob_div,
self.heal_object_select / folder.object_heal_prob_div,
) && self.try_should_heal().await?;
let mut item = ScannerItem {
path: file_path,
@@ -2662,7 +2637,7 @@ impl FolderScanner {
replication: active_replication.clone(),
heal_scope: None,
heal_enabled,
heal_bitrot,
heal_bitrot: self.scan_mode == HealScanMode::Deep,
debug: self.data_usage_scanner_debug,
file_type: entry_type,
notification_bucket_incarnation: self.notification_bucket_incarnation,
@@ -2859,9 +2834,7 @@ impl FolderScanner {
self.coverage_gap |= self.old_cache.info.scan_progress.is_some();
}
self.apply_size_reconciliation(&sz);
if !sz.all_versions_queued_for_delete {
into.objects += 1;
}
into.objects += 1;
object_count += 1;
self.budget.record_object_scanned();
self.checkpoint_objects = self.checkpoint_objects.saturating_add(1);
@@ -844,10 +844,6 @@ impl ScannerItem {
|| event.action == IlmAction::DelMarkerDeleteAllVersionsAction
{
remaining_versions = 0;
} else if !versioning_config.prefix_enabled(&object_path)
&& event.action == IlmAction::DeleteAction
{
remaining_versions = remaining_versions.saturating_sub(1);
}
} else if matches!(
event.action,
@@ -985,9 +981,8 @@ impl ScannerItem {
if record_scanner_ilm_action_if_queued(global_metrics(), event.action, 1, queued) {
done_ilm(1)();
if !versioning_config.prefix_enabled(&object_path) && event.action == IlmAction::DeleteAction {
remaining_versions = remaining_versions.saturating_sub(1);
remaining_versions -= 1;
size = 0;
account_now = false;
}
}
}
@@ -1081,9 +1076,6 @@ impl ScannerItem {
}
}
}
if !object_infos.is_empty() && remaining_versions == 0 {
size_summary.all_versions_queued_for_delete = true;
}
if !cancellation.is_some_and(CancellationToken::is_cancelled) {
self.alert_excessive_versions(remaining_versions, cumulative_size, notification_bucket_incarnation);
}
@@ -1129,28 +1121,12 @@ impl ScannerItem {
None if !oi.version_purge_status.is_empty() => ReplicationConfig::new(None, None),
None => return,
};
let has_site_targets = replication.has_site_replication_targets();
let has_bucket_targets = replication.has_bucket_replication_targets() || !has_site_targets;
let done_replication = if has_bucket_targets {
Some(Metrics::time(Metric::CheckReplication))
} else {
None
};
if has_site_targets {
global_metrics().record_scanner_source_checked(ScannerWorkSource::SiteReplication, 1);
}
let done_replication = Metrics::time(Metric::CheckReplication);
let replication_result = queue_replication_heal(&oi.bucket, oi.clone(), replication, 0).await;
if let Some(done_replication) = done_replication {
done_replication();
}
done_replication();
let roi = replication_result.object_info;
if has_bucket_targets {
record_scanner_replication_admission(global_metrics(), &roi, replication_result.admission);
}
if has_site_targets {
record_scanner_site_replication_admission(global_metrics(), &roi, replication_result.admission);
}
record_scanner_replication_admission(global_metrics(), &roi, replication_result.admission);
if !Self::should_account_replication_stats(oi) {
return;
}
@@ -1219,7 +1195,6 @@ impl ScannerItem {
let now = OffsetDateTime::now_utc();
let scan_mode = effective_object_heal_scan_mode(self.heal_bitrot, oi.mod_time, now);
global_metrics().record_scanner_source_checked(scanner_heal_source(scan_mode), 1);
if self.heal_bitrot && scan_mode != HealScanMode::Deep {
let cooldown = deep_verify_cooldown();
let age_secs = oi.mod_time.map(|mod_time| {
+1 -27
View File
@@ -80,7 +80,7 @@ pub(crate) use rustfs_ecstore::api::bucket::replication::{
ReplicationConfigurationExt as EcstoreReplicationConfigurationExt,
ReplicationHealQueueResult as EcstoreReplicationHealQueueResult,
ReplicationQueueAdmission as EcstoreReplicationQueueAdmission, ReplicationScannerBridge as EcstoreReplicationScannerBridge,
ReplicationType, is_site_replication_rule as ecstore_is_site_replication_rule,
ReplicationType,
};
pub(crate) use rustfs_ecstore::api::bucket::replication::{ReplicationStatusType, VersionPurgeStatusType};
pub(crate) use rustfs_ecstore::api::bucket::target::BucketTargets as EcstoreBucketTargets;
@@ -284,32 +284,6 @@ impl ScannerReplicationConfig {
.is_some_and(|config| EcstoreReplicationConfigurationExt::has_active_rules(config, prefix, recursive))
}
pub(crate) fn has_site_replication_targets(&self) -> bool {
self.0
.remotes
.as_ref()
.is_some_and(|remotes| remotes.targets.iter().any(|target| !target.deployment_id.trim().is_empty()))
|| self.0.config.as_ref().is_some_and(|config| {
config
.rules
.iter()
.any(|rule| !rule.status.eq_ignore_ascii_case("Disabled") && ecstore_is_site_replication_rule(rule))
})
}
pub(crate) fn has_bucket_replication_targets(&self) -> bool {
self.0
.remotes
.as_ref()
.is_some_and(|remotes| remotes.targets.iter().any(|target| target.deployment_id.trim().is_empty()))
|| self.0.config.as_ref().is_some_and(|config| {
config
.rules
.iter()
.any(|rule| !rule.status.eq_ignore_ascii_case("Disabled") && !ecstore_is_site_replication_rule(rule))
})
}
pub(crate) fn into_ecstore(self) -> EcstoreReplicationConfig {
self.0
}
+2
View File
@@ -70,6 +70,8 @@ pub struct PartInfo {
pub size: usize,
pub etag: Option<String>,
pub actual_size: i64,
/// Checksums recorded when the part was uploaded, keyed by algorithm name.
pub checksums: Option<HashMap<String, String>>,
}
#[derive(Debug, Clone, Default)]
+109 -23
View File
@@ -13,8 +13,8 @@
// limitations under the License.
use super::{DiskInfo, IOStats, fs_type::get_fs_type};
use rustix::fs::statfs;
use std::collections::BTreeSet;
use rustix::fs::{AtFlags, Mode, OFlags, StatFs, StatxAttributes, StatxFlags, fstatfs, open, statfs, statx};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs;
use std::fs::File;
use std::io::{self, BufRead, Error, ErrorKind, Read};
@@ -27,27 +27,10 @@ static BAVAIL_GT_BFREE_WARNING_PATHS: OnceLock<Mutex<BTreeSet<PathBuf>>> = OnceL
/// Returns total and free bytes available in a directory, e.g. `/`.
pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
// Use statfs on Linux to get access to f_type (filesystem magic number)
let stat = statfs(p.as_ref())?;
// Linux statfs:
// f_bsize: Optimal transfer block size
// f_blocks: Total data blocks in file system
// f_frsize: Fragment size (since Linux 2.6) - unit for blocks
//
// If f_frsize is > 0, it is the unit for f_blocks, f_bfree, f_bavail.
// Otherwise f_bsize is used.
let bsize = if stat.f_frsize > 0 {
stat.f_frsize as u64
} else {
stat.f_bsize as u64
};
let bfree = stat.f_bfree as u64;
let bavail = stat.f_bavail as u64;
let blocks = stat.f_blocks as u64;
let (total, free, used) = calculate_space_usage(blocks, bfree, bavail, bsize, p.as_ref())?;
let st = rustix::fs::stat(p.as_ref())?;
let path = p.as_ref();
let stat = statfs(path)?;
let (total, free, used) = statfs_space_usage(&stat, path)?;
let st = rustix::fs::stat(path)?;
Ok(DiskInfo {
total,
@@ -62,6 +45,84 @@ pub fn get_info(p: impl AsRef<Path>) -> std::io::Result<DiskInfo> {
})
}
fn statfs_space_usage(stat: &StatFs, path: &Path) -> io::Result<(u64, u64, u64)> {
// Block counts are in fragment-size units when the kernel provides them.
let block_size = if stat.f_frsize > 0 { stat.f_frsize } else { stat.f_bsize };
calculate_space_usage(stat.f_blocks, stat.f_bfree, stat.f_bavail, block_size as u64, path)
}
/// Snapshot of Linux whole-filesystem mount eligibility for one refresh.
///
/// The mount table is read lazily when the first candidate mount root is
/// probed. The caller is responsible for ensuring exclusive use of the filesystem.
#[derive(Debug, Default)]
pub struct MountUsageSnapshot(OnceLock<Option<HashMap<u64, (u32, u32)>>>);
impl MountUsageSnapshot {
/// Return filesystem-reported used bytes for a directory at an eligible mount root.
///
/// Direct accounting is supported for XFS, the ext family, and tmpfs.
/// Returns `None` when the mount or its filesystem type is ineligible
/// or the kernel cannot identify or read the mounted filesystem.
pub fn used_bytes(&self, path: &Path) -> Option<u64> {
let directory = open(path, OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).ok()?;
let stat = statx(&directory, "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID).ok()?;
if !StatxFlags::from_bits_retain(stat.stx_mask).contains(StatxFlags::MNT_ID)
|| !stat.stx_attributes.contains(StatxAttributes::MOUNT_ROOT)
{
return None;
}
let mounts = self
.0
.get_or_init(|| {
let mountinfo = fs::read("/proc/self/mountinfo").ok()?;
eligible_usage_mounts(&String::from_utf8_lossy(&mountinfo))
})
.as_ref()?;
if mounts.get(&stat.stx_mnt_id) != Some(&(stat.stx_dev_major, stat.stx_dev_minor)) {
return None;
}
// Read the same mount that was classified, even if the path was replaced.
let stat = fstatfs(directory).ok()?;
if !supports_direct_mount_usage(stat.f_type as u64) {
return None;
}
let (_, _, used) = statfs_space_usage(&stat, path).ok()?;
Some(used)
}
}
fn supports_direct_mount_usage(fs_type: u64) -> bool {
// Distinct mount and device IDs do not establish independent block
// accounting on filesystems that share a pool across subvolumes.
matches!(get_fs_type(fs_type), "XFS" | "EXT4" | "TMPFS")
}
fn eligible_usage_mounts(mountinfo: &str) -> Option<HashMap<u64, (u32, u32)>> {
let mut devices = HashMap::new();
let mut parents = HashSet::new();
for line in mountinfo.lines() {
let mut fields = line.split_ascii_whitespace();
let id: u64 = fields.next()?.parse().ok()?;
let parent: u64 = fields.next()?.parse().ok()?;
let (major, minor) = fields.next()?.split_once(':')?;
let device = (major.parse().ok()?, minor.parse().ok()?);
let root = fields.next()?;
parents.insert(parent);
// A second view of the same device may alias accounting for the whole filesystem.
devices
.entry(device)
.and_modify(|mount| *mount = None)
.or_insert((root == "/").then_some(id));
}
Some(
devices
.into_iter()
.filter_map(|(device, id)| id.filter(|id| !parents.contains(id)).map(|id| (id, device)))
.collect(),
)
}
fn calculate_space_usage(blocks: u64, bfree: u64, bavail: u64, bsize: u64, path: &Path) -> std::io::Result<(u64, u64, u64)> {
let available = if bfree < bavail {
if should_warn_bavail_greater_than_bfree(path) {
@@ -450,6 +511,31 @@ mod tests {
assert_eq!(mountinfo_path(line), Some("/data/replacement"));
}
#[test]
fn mount_usage_requires_a_unique_whole_filesystem_with_no_child_mounts() {
let mountinfo = "\
1 0 0:1 / / rw - overlay overlay rw\n\
2 1 0:2 / /data/whole rw - tmpfs tmpfs rw\n\
3 1 0:3 /subdir /data/bind rw - tmpfs tmpfs rw\n\
4 1 0:4 / /data/parent rw - tmpfs tmpfs rw\n\
5 4 0:5 / /data/parent/child rw - tmpfs tmpfs rw\n\
6 1 0:6 / /data/alias1 rw - tmpfs tmpfs rw\n\
7 1 0:6 / /data/alias2 rw - tmpfs tmpfs rw";
assert_eq!(eligible_usage_mounts(mountinfo), Some(HashMap::from([(2, (0, 2)), (5, (0, 5))])));
assert!(eligible_usage_mounts("1 0 no-device /").is_none());
}
#[test]
fn mount_usage_uses_only_filesystems_with_independent_block_accounting() {
assert!(supports_direct_mount_usage(0x58465342)); // XFS
assert!(supports_direct_mount_usage(0xEF53)); // ext family
assert!(supports_direct_mount_usage(0x01021994)); // tmpfs
assert!(!supports_direct_mount_usage(0x9123683E)); // Btrfs
assert!(!supports_direct_mount_usage(0x2FC12FC1)); // ZFS
assert!(!supports_direct_mount_usage(0x794C7630)); // OverlayFS
assert!(!supports_direct_mount_usage(0x6969)); // NFS
}
#[test]
fn reject_relative_path_for_cross_device_validation() {
let err = ensure_no_sub_mounts("relative/path", &[]).unwrap_err();
+3 -1
View File
@@ -24,7 +24,9 @@ mod unix;
mod windows;
#[cfg(target_os = "linux")]
pub use linux::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
pub use linux::{
MountUsageSnapshot, check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk,
};
#[cfg(all(unix, not(target_os = "linux")))]
pub use unix::{check_cross_device_mounts, get_drive_stats, get_info, get_physical_device_ids, is_mount_point, same_disk};
+32 -36
View File
@@ -13,7 +13,7 @@
# limitations under the License.
services:
# RustFS main service
# RustFS single-node single-disk (SNSD) service
rustfs:
image: rustfs/rustfs:latest
container_name: rustfs-server
@@ -23,31 +23,29 @@ services:
security_opt:
- "no-new-privileges:true"
ports:
- "9000:9000" # S3 API port
- "9001:9001" # Console port
- "${RUSTFS_S3_PORT:-9000}:9000" # S3 API port
- "${RUSTFS_CONSOLE_PORT:-9001}:9001" # Console port
environment:
- RUSTFS_VOLUMES=/data/rustfs{0...3}
- RUSTFS_VOLUMES=/data
- RUSTFS_ADDRESS=0.0.0.0:9000
- RUSTFS_CONSOLE_ADDRESS=0.0.0.0:9001
- RUSTFS_CONSOLE_ENABLE=true
- RUSTFS_CONSOLE_CORS_ALLOWED_ORIGINS=*
- RUSTFS_ACCESS_KEY=rustfsadmin # CHANGEME
- RUSTFS_SECRET_KEY=rustfsadmin # CHANGEME
- RUSTFS_ACCESS_KEY=${RUSTFS_ACCESS_KEY:-rustfsadmin} # CHANGEME
- RUSTFS_SECRET_KEY=${RUSTFS_SECRET_KEY:-rustfsadmin} # CHANGEME
- RUSTFS_OBS_LOGGER_LEVEL=info
- RUSTFS_OBS_LOG_DIRECTORY=/app/logs
- RUSTFS_OBS_LOG_DIRECTORY=/logs
# Optional TLS:
# - mount your cert directory to /opt/tls
# - set RUSTFS_TLS_PATH=/opt/tls
# - when TLS is enabled, health checks automatically switch to HTTPS
# Keep strict disk topology checks enabled by default.
# For local testing only, set `RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true` explicitly.
- RUSTFS_UNSAFE_BYPASS_DISK_CHECK=${RUSTFS_UNSAFE_BYPASS_DISK_CHECK:-false}
volumes:
- rustfs_data_0:/data/rustfs0
- rustfs_data_1:/data/rustfs1
- rustfs_data_2:/data/rustfs2
- rustfs_data_3:/data/rustfs3
- logs:/app/logs
- rustfs_data:/data
- logs:/logs
ulimits:
nofile:
soft: 65535
hard: 65535
networks:
- rustfs-network
restart: unless-stopped
@@ -63,21 +61,21 @@ services:
test:
[
"CMD",
"sh", "-ec",
"host=\"$${RUSTFS_HEALTHCHECK_HOST:-127.0.0.1}\"; scheme=\"http\"; set -- -fsS; \
"sh",
"-ec",
"host=\"$${RUSTFS_HEALTHCHECK_HOST:-127.0.0.1}\"; scheme=\"http\"; set -- -fsS --connect-timeout 3 --max-time 5; \
if [ -n \"$${RUSTFS_TLS_PATH:-}\" ]; then \
scheme=\"https\"; \
ca_path=\"$${RUSTFS_HEALTHCHECK_CA:-}\"; \
if [ -z \"$${ca_path}\" ] && [ -f /opt/tls/ca.crt ]; then ca_path=/opt/tls/ca.crt; fi; \
case \"$${host}\" in 127.0.0.1|localhost) strict_host=false ;; *) strict_host=true ;; esac; \
if [ \"$${strict_host}\" = true ] && [ -n \"$${ca_path}\" ]; then \
set -- \"$${@}\" --cacert \"$${ca_path}\" --resolve \"$${host}:9000:127.0.0.1\" --resolve \"$${host}:9001:127.0.0.1\"; \
set -- \"$${@}\" --cacert \"$${ca_path}\" --resolve \"$${host}:9000:127.0.0.1\"; \
else \
set -- \"$${@}\" -k; \
fi; \
fi; \
curl \"$${@}\" \"$${scheme}://$${host}:9000/health\" && \
curl \"$${@}\" \"$${scheme}://$${host}:9001/rustfs/console/health\""
curl \"$${@}\" \"$${scheme}://$${host}:9000/health/ready\""
]
interval: 30s
timeout: 10s
@@ -86,30 +84,28 @@ services:
# RustFS volume permissions fixer service
volume-permission-helper:
image: alpine
image: alpine:3.24
network_mode: none
volumes:
- rustfs_data_0:/data/rustfs0
- rustfs_data_1:/data/rustfs1
- rustfs_data_2:/data/rustfs2
- rustfs_data_3:/data/rustfs3
- logs:/app/logs
- rustfs_data:/data
- logs:/logs
command: >
sh -c "
chown -R 10001:10001 /data/rustfs0 /data/rustfs1 /data/rustfs2 /data/rustfs3 /app/logs &&
echo 'Volume Permissions fixed' &&
exit 0
"
sh -ec '
for dir in /data /logs; do
if [ "$$(stat -c %u:%g "$$dir")" != "10001:10001" ]; then
chown -R 10001:10001 "$$dir"
fi
done
echo "Volume permissions ready"
'
# Permission baseline:
# - default RustFS runtime user is 10001:10001
# - alternatively, run rustfs service with host-matched `user: \"<uid>:<gid>\"`
# - alternatively, run rustfs service with host-matched `user: "<uid>:<gid>"`
restart: "no"
networks:
rustfs-network:
volumes:
rustfs_data_0:
rustfs_data_1:
rustfs_data_2:
rustfs_data_3:
rustfs_data:
logs:
@@ -11,6 +11,10 @@
## Open Items
- `http-opaque-response-headers` HTTP response encoding. Preserve UTF-8 lifecycle rule IDs in x-amz-expiration and UTF-8 Content-Type parameters while the gateway string encoder accepts only ASCII. Remove the RustFS projection after the gateway emits the original opaque bytes in these response headers.
- `metrics-024-recorder` dependency constraint bridge. The workspace still resolves metrics 0.24 for Metrique and its metrics utility. The local crate re-exports metrics 0.25 so all producers share the same recorder. Remove the crate and workspace Cargo patch after every resolved consumer accepts metrics 0.25 directly.
- `9526` NIXL shard reads recognize the exact file-missing response from peers that predate the disk error header. Remove the response-body check once all supported NIXL peers send the header.
- `openidconnect-hmac-signature-width` ID token verification guard: openidconnect 4.1.0 converts decoded HMAC signatures to fixed-size arrays, which panic on unexpected lengths. Check HS256, HS384, and HS512 signature widths before delegating all cryptographic, issuer, audience, expiry, and nonce checks to the upstream verifier. Remove the guard after a supported upstream release returns verification errors for arbitrary HMAC signature lengths.
@@ -98,6 +98,8 @@ For a dedicated Linux test cluster, add the following flags to the ABBA command
Repeat the SSH target and device mapping for every node. Specify the Linux kernel device names of the benchmark volumes. With the queue check enabled, each PUT attempt waits for two consecutive rounds of parallel five-second sampling. Each node must have mean queue depth at most 0.25 and no listed device above 0.75. Queue depth uses the change in weighted I/O milliseconds divided by elapsed monotonic milliseconds. Each attempt records the collected samples in its cell's `node_telemetry/queue_*.tsv`. An unavailable node, invalid counter or timeout fails the attempt before Warp starts. The ABBA drift and regression budgets still apply. [Linux block device counters](https://docs.kernel.org/admin-guide/iostats.html)
The queue TSV also records `completed_writes`, `write_ms_per_op`, and `peak_write_ms_per_op` for the same samples. Write latency divides the change in milliseconds spent writing by the change in completed writes. The node average is weighted by completed writes, and the peak is the highest per-device average among devices with write completions. A window with no completed writes reports zero completions and `NA` for both latency fields. Compare the last two samples of successful attempts across legs to check for different write completion behavior at similarly low queue depths. These fields are diagnostic and the existing queue and drift thresholds still apply.
Use the same persistent lock file for cooperating commands on the same controller. An occupied lock makes the runner exit before deployment. Keep the lock file in place so every command locks the same inode. The controller runs the restore hook once after any deployment attempt, including a failed deploy, interrupted workload or failed gate. The hook receives `HOTPATH_ABBA_DATASET_NAMESPACE` and `HOTPATH_ABBA_OUT_DIR`. It owns the site-specific cleanup and must reconcile partially completed remote deployment, restore services and verify readiness before returning. Use bounded, synchronous hooks on the controller. The runner stops the active controller process group before restoration, holds the lock through restoration and records `restore.log` and `restore.status`. Managed runs require `flock` and a `timeout` implementation supporting `--foreground` and `--kill-after`.
For diagnostic PUT runs using `--service-prometheus-query-url`, add `--require-rename-rank-metrics` after enabling PUT stage metrics and warming that deployment. The service snapshots must include `rustfs_s3_put_object_rename_disk_wait_completion_ms_count` for both `position="quorum_first"` and `position="quorum_tail"`. Each group must advance across the attempt without series resets or changes in membership. Use the existing query or service-name filter to scope snapshots to the benchmark service. These counters describe completion order. Per-request attribution also needs a join with the coordinator's ACK decision.
+2
View File
@@ -22,6 +22,8 @@ Specialized boundary, hardware and alternate-feature lanes run only on the sched
Workspace Clippy runs on every event with a selected workspace Rust job, pull requests included, in its own `Workspace Clippy` job. It runs beside `Workspace Lint and Build` instead of in front of it, because check-mode metadata and the linked test binaries share no compiler output; `scripts/ci_gate.py --check-workflow` rejects a workflow in which the archive producer or any archive consumer waits for the lint, or in which the lint leaves the aggregate. `Workspace Lint and Build` keeps its name as the archive producer: it creates the exact test archive and runs doctests; `Workspace tests` consumes the archive without rebuilding it. `cache-warm.yml` warms Clippy's check artifacts under `ci-dev` with the same invocation to reuse compatible dependency artifacts. `make pre-commit` does not run Clippy. Select local Clippy targets, features, and documentation exemptions from the root `AGENTS.md` verification tier; the workspace command below reproduces the CI lane and is not a universal pre-push requirement.
Full-scope runs also execute the production ECStore suite in `dst_production_ecstore` against simulated disks with `--features dst`. It checks the durability of acknowledged writes, metadata publication, and multipart retries with valid, missing, or misplaced per-drive evidence. The workspace producer retains the nextest listing and JUnit report and verifies that every required case passed.
Serial ILM tests run at the end of `workspace-tests` for the `full` scope, consuming the same verified archive as ordinary workspace tests. The existing ignored-test filter and `-j1` remain; `--profile default` keeps the no-retry execution and preserves the separate core CI JUnit report. Any ILM failure fails the consumer and required aggregate. Logs remain in the workspace test evidence artifact. There is no separate ILM compilation or cache restore.
`required-checks` runs even after failed or skipped dependencies. `scripts/ci_gate.py verify` rejects missing jobs, unexpected jobs, failure, cancellation, and unexpected skips; optional lanes are required only on their declared events. `Workspace Clippy` is the workspace lint, `Workspace Lint and Build` and `Workspace tests` are the ordinary Rust producer and consumer, while `Test and Lint` uniquely names the aggregate. New validation jobs must update both its direct dependencies and the script contract. A report-only lane is registered in `REPORT_ONLY_JOBS` instead: it stays out of the aggregate, must keep its distinguishing environment, and must keep the steps it reruns identical to the required job it mirrors. Test this wiring and its failure cases with `python3 scripts/ci_gate.py --self-test`.
+238 -97
View File
@@ -796,9 +796,9 @@ dependencies = [
[[package]]
name = "aws-sdk-s3"
version = "1.162.0"
version = "1.163.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ffd93a622eaef65d9dee213b1c8afb8b5d999aa2020fe1c9ba6a94ec5e973e4"
checksum = "e9765cbe48081570df401ebc65cae8a9e32912fac5f4cf3c6bdb2547b8ecb62c"
dependencies = [
"arc-swap",
"aws-credential-types",
@@ -825,7 +825,7 @@ dependencies = [
"lru",
"percent-encoding",
"regex-lite",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
"url",
]
@@ -924,7 +924,7 @@ dependencies = [
"http",
"p256",
"percent-encoding",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"time",
"tracing",
@@ -959,7 +959,7 @@ dependencies = [
"md-5",
"pin-project-lite",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"tracing",
]
@@ -1364,9 +1364,9 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "byteorder"
version = "1.5.0"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
[[package]]
name = "bytes"
@@ -1512,7 +1512,7 @@ dependencies = [
"num-traits",
"serde",
"wasm-bindgen",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -3014,7 +3014,7 @@ checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"subtle",
]
@@ -3636,7 +3636,7 @@ checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd"
dependencies = [
"cfg-if",
"libc",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -3656,9 +3656,9 @@ checksum = "b4db3c637c6c3cf7120ab641f12f83aa19dfa015679ac1b29e16b15684c7a3e3"
[[package]]
name = "http"
version = "1.5.0"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05"
dependencies = [
"bytes",
"itoa",
@@ -3804,7 +3804,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core",
"windows-core 0.62.2",
]
[[package]]
@@ -3957,9 +3957,9 @@ dependencies = [
[[package]]
name = "io-uring"
version = "0.7.15"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb"
checksum = "42a8b27af47f173c8ccb750868620435d2afc8190ca314356f9dc29470274123"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@@ -3975,7 +3975,7 @@ dependencies = [
"socket2",
"widestring",
"windows-registry",
"windows-result",
"windows-result 0.4.1",
"windows-sys 0.61.2",
]
@@ -4041,23 +4041,23 @@ dependencies = [
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "jiff"
version = "1.0.3"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f"
checksum = "379ed44bd4e16d3926160e2b3a78b79ca0952ef5c037f124f554842ba272ef92"
dependencies = [
"jiff-core 1.0.2",
"jiff-static 1.0.3",
"jiff-core 1.1.0",
"jiff-static 1.1.0",
"jiff-tzdb-platform 1.0.0",
"log",
"portable-atomic",
"portable-atomic-util",
"serde_core",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4072,9 +4072,9 @@ dependencies = [
[[package]]
name = "jiff-core"
version = "1.0.2"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f"
checksum = "0df46fc314b4f458aee614afcd8676ed6cb3637413aa359d47d2646cbc038b79"
dependencies = [
"log",
]
@@ -4093,11 +4093,11 @@ dependencies = [
[[package]]
name = "jiff-static"
version = "1.0.3"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8"
checksum = "27b729c549d3efb5855b3c80b0ee8ee1850d56330a127382fe2760965741c1f3"
dependencies = [
"jiff-core 1.0.2",
"jiff-core 1.1.0",
"proc-macro2",
"quote",
"syn 3.0.9",
@@ -4147,7 +4147,7 @@ dependencies = [
"simd_cesu8",
"thiserror",
"walkdir",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -4527,9 +4527,9 @@ dependencies = [
[[package]]
name = "metrics"
version = "0.24.6"
version = "0.25.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2"
checksum = "eb1b882a87a42420c952fbb7173ff4fa5d380b51eb26c95bf77435811201db7a"
dependencies = [
"portable-atomic",
"rapidhash",
@@ -5055,7 +5055,7 @@ dependencies = [
"elliptic-curve",
"primefield",
"primeorder",
"sha2 0.11.2",
"sha2 0.11.3",
]
[[package]]
@@ -5094,7 +5094,7 @@ dependencies = [
"libc",
"redox_syscall 0.5.18",
"smallvec",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -5106,7 +5106,7 @@ dependencies = [
"libc",
"redox_syscall 0.9.5",
"smallvec",
"windows-link",
"windows-link 0.2.1",
]
[[package]]
@@ -5422,7 +5422,7 @@ dependencies = [
"md-5",
"memchr",
"rand 0.10.4",
"sha2 0.11.2",
"sha2 0.11.3",
"stringprep",
]
@@ -6170,7 +6170,7 @@ dependencies = [
"pkcs1",
"pkcs8 0.11.0",
"rand_core 0.10.1",
"sha2 0.11.2",
"sha2 0.11.3",
"signature 3.0.0",
"spki 0.8.1",
"zeroize",
@@ -6253,7 +6253,7 @@ dependencies = [
"http",
"md-5",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"xxhash-rust",
]
@@ -6299,7 +6299,7 @@ dependencies = [
"rand 0.10.4",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
]
@@ -6317,7 +6317,7 @@ dependencies = [
"rsa",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
]
@@ -6362,7 +6362,7 @@ dependencies = [
"hyper",
"hyper-rustls",
"hyper-util",
"jiff 1.0.3",
"jiff 1.1.0",
"lazy_static",
"libc",
"md-5",
@@ -6414,7 +6414,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"shadow-rs",
"slab",
"smallvec",
@@ -6432,7 +6432,7 @@ dependencies = [
"urlencoding",
"uuid",
"winapi-util",
"windows-sys 0.61.2",
"windows-sys 0.101.0",
"xxhash-rust",
]
@@ -6476,7 +6476,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"time",
"tokio",
@@ -6492,7 +6492,7 @@ dependencies = [
"arbitrary",
"bytes",
"http",
"jiff 1.0.3",
"jiff 1.1.0",
"libfuzzer-sys",
"quick-xml 0.42.0",
"rustfs-ecstore",
@@ -6510,7 +6510,7 @@ dependencies = [
"rustfs-utils",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"tokio",
"uuid",
@@ -6542,7 +6542,7 @@ dependencies = [
"rustfs-gateway-stream",
"rustfs-gateway-xml",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"time",
"twox-hash",
"unicode-normalization",
@@ -6592,9 +6592,9 @@ dependencies = [
[[package]]
name = "rustfs-kafka"
version = "1.4.1"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82dc39ba1a5a9f6b2e49decb0b54c23ebaebdfb08a899307c266694bfd269bf9"
checksum = "d66b41fff6ef985a310f7dac070fda947b7588e56decd837084c41edc24841a0"
dependencies = [
"base64 0.23.1",
"bytes",
@@ -6606,7 +6606,7 @@ dependencies = [
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"socket2",
"thiserror",
"tracing",
@@ -6617,20 +6617,21 @@ dependencies = [
[[package]]
name = "rustfs-kafka-async"
version = "1.4.1"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "684f5e78ea1421bbf915e4cd0515bdefd587cfa281da000e41ae4a434f90195a"
checksum = "7ceb19d7045aa067259792637be2f72c971aece9ccaf7f6c76ec7ac272904d37"
dependencies = [
"base64 0.23.1",
"bytes",
"hmac 0.13.0",
"indexmap",
"kafka-protocol",
"metrics",
"pbkdf2 0.13.0",
"rand 0.10.4",
"rustfs-kafka",
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-rustls",
"tracing",
@@ -6654,7 +6655,7 @@ dependencies = [
"chacha20poly1305",
"hex-simd",
"hotpath",
"jiff 1.0.3",
"jiff 1.1.0",
"md-5",
"metrics",
"moka",
@@ -6665,7 +6666,7 @@ dependencies = [
"serde",
"serde_ignored",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"subtle",
"thiserror",
"tokio",
@@ -6724,7 +6725,7 @@ dependencies = [
"http",
"humantime",
"hyper",
"jiff 1.0.3",
"jiff 1.1.0",
"reqwest",
"rustfs-signer",
"serde",
@@ -6742,7 +6743,7 @@ dependencies = [
"form_urlencoded",
"hashbrown 0.17.2",
"hotpath",
"jiff 1.0.3",
"jiff 1.1.0",
"metrics",
"percent-encoding",
"quick-xml 0.42.0",
@@ -6795,7 +6796,7 @@ dependencies = [
"base64-simd",
"futures",
"ipnetwork",
"jiff 1.0.3",
"jiff 1.1.0",
"jsonwebtoken",
"moka",
"regex",
@@ -6878,7 +6879,7 @@ dependencies = [
"serde",
"serde_json",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"tokio",
"tokio-util",
@@ -6919,7 +6920,7 @@ dependencies = [
"rustls-pki-types",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"time",
"tokio",
@@ -6971,7 +6972,7 @@ dependencies = [
"futures-core",
"hotpath",
"http",
"jiff 1.0.3",
"jiff 1.1.0",
"lz4",
"lz4_flex",
"memchr",
@@ -7016,7 +7017,7 @@ dependencies = [
name = "rustfs-scanner-metrics"
version = "1.0.8"
dependencies = [
"jiff 1.0.3",
"jiff 1.1.0",
"metrics",
"rmp-serde",
"rustfs-heal-contracts",
@@ -7092,7 +7093,7 @@ dependencies = [
"hotpath",
"hyper",
"hyper-rustls",
"jiff 1.0.3",
"jiff 1.1.0",
"lapin",
"libc",
"metrics",
@@ -7114,7 +7115,7 @@ dependencies = [
"rustls-native-certs",
"serde",
"serde_json",
"sha2 0.11.2",
"sha2 0.11.3",
"snap",
"sysinfo",
"thiserror",
@@ -7139,7 +7140,7 @@ dependencies = [
"rustls",
"rustls-pki-types",
"serde",
"sha2 0.11.2",
"sha2 0.11.3",
"thiserror",
"tokio",
"tracing",
@@ -7148,8 +7149,9 @@ dependencies = [
[[package]]
name = "rustfs-uring"
version = "0.3.0"
source = "git+https://github.com/rustfs/uring.git?rev=eb8fc160e71d804427de1e905f5c226d580f71bf#eb8fc160e71d804427de1e905f5c226d580f71bf"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5d9b7f02481f7a178db09da8dc3ed63c85debb370ecfa8b5a015706b58025ba"
dependencies = [
"io-uring",
"libc",
@@ -7183,14 +7185,14 @@ dependencies = [
"rustix",
"serde",
"sha1 0.11.0",
"sha2 0.11.2",
"sha2 0.11.3",
"siphasher",
"snap",
"tokio",
"tracing",
"transform-stream",
"url",
"windows",
"windows 0.101.0",
"zstd 0.14.5",
]
@@ -7551,9 +7553,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.11.2"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
checksum = "820083d430c52864bf834423fc988cbcf61685d6f9d22a765a64e3f6cfe3521c"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
@@ -7784,9 +7786,9 @@ dependencies = [
[[package]]
name = "starshard"
version = "2.4.1"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0883700b50fd0b62120ebc4c07230e02f0cf1ead474c3b3b44eaa13e0a999ea"
checksum = "adc82b6d069d07eb9b6433ccabdaf31ea1508cd240f6fe12284e0dd3d7609bd5"
dependencies = [
"async-trait",
"hashbrown 0.17.2",
@@ -7902,9 +7904,9 @@ dependencies = [
[[package]]
name = "sysinfo"
version = "0.40.4"
version = "0.40.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e80749408e2d8bec0ffa303012cf4e1b3b355f4a09087b4fdf7473680f6a2de"
checksum = "0ebe31c61260d7bc4bfc204a2d096c428a4c9ef59ca48bfa693d17fec4f129ad"
dependencies = [
"libc",
"memchr",
@@ -7913,7 +7915,7 @@ dependencies = [
"objc2-io-kit",
"objc2-open-directory",
"rayon",
"windows",
"windows 0.62.2",
]
[[package]]
@@ -8156,7 +8158,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c2ad44aa0ae96db89c4742212ed41645b2f597311ff6e1945542a4d9fadc2fb"
dependencies = [
"rustls",
"sha2 0.11.2",
"sha2 0.11.3",
"tokio",
"tokio-postgres",
"tokio-rustls",
@@ -8847,10 +8849,24 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections",
"windows-core",
"windows-future",
"windows-numerics",
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
]
[[package]]
name = "windows"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa86febe1d5f623619e56067e9c6f84c368cf94f9f36df738875a0dc5affd752"
dependencies = [
"windows-collections 0.101.0",
"windows-core 0.101.0",
"windows-future 0.101.0",
"windows-numerics 0.101.0",
"windows-reference",
"windows-time",
]
[[package]]
@@ -8859,7 +8875,16 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core",
"windows-core 0.62.2",
]
[[package]]
name = "windows-collections"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c988c3f56b2a0cf740d2837950f25c43539ea6c004a5244085ce6749e1c61f29"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
@@ -8868,11 +8893,24 @@ version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link",
"windows-result",
"windows-strings",
"windows-implement 0.60.2",
"windows-interface 0.59.3",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-core"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27abecb0bac0f1602c4e0d0c885aca58e9a2a25d852135b96e4d0f9daf989aac"
dependencies = [
"windows-implement 0.101.0",
"windows-interface 0.101.0",
"windows-link 0.101.0",
"windows-result 0.101.0",
"windows-strings 0.101.0",
]
[[package]]
@@ -8881,9 +8919,20 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core",
"windows-link",
"windows-threading",
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
]
[[package]]
name = "windows-future"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c1de418ec955682054a08c9a2925719c76af9408397fd89fc7c2418bd3b2551"
dependencies = [
"windows-core 0.101.0",
"windows-link 0.101.0",
"windows-threading 0.101.0",
]
[[package]]
@@ -8897,6 +8946,17 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-implement"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33a7f9008fbe08b219a4d9b2db1ceff71b9ed7f0e02472a3bf2046a2b258f933"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.59.3"
@@ -8908,20 +8968,56 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "windows-interface"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67d1b654cf5aa8120c8c796fe6c88f0e0407512c341e83ea7bb65b933b596474"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-link"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core",
"windows-link",
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]]
name = "windows-numerics"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d54e417b9761be91da0ab663a5e393e9e54820e55fa9a1d902b978bda3a71ba"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
name = "windows-reference"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0a017bb8eab108f37103deaa4eaad24ce324c30c6f72628a59250be24c87466"
dependencies = [
"windows-core 0.101.0",
"windows-time",
]
[[package]]
@@ -8930,9 +9026,9 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link",
"windows-result",
"windows-strings",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
@@ -8941,7 +9037,16 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-result"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a02baed928b12dbc90e3a37d1504af179d275e13427510f6bcded0607c9251a7"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8950,7 +9055,16 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3301e29c2a308301e0e84fe4242684b1310864f3e15aba65b4ae41f1a44f7f95"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8968,7 +9082,16 @@ version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
@@ -8993,7 +9116,25 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link",
"windows-link 0.2.1",
]
[[package]]
name = "windows-threading"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e1e41d72a0564ebe2cbb9487ed918acfc71d541683b84816a424dc3c7939592"
dependencies = [
"windows-link 0.101.0",
]
[[package]]
name = "windows-time"
version = "0.101.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "186ef23b1710095987bf5281bd19e3669934d4353946f24cbdcfd0ed4f2deff6"
dependencies = [
"windows-core 0.101.0",
]
[[package]]
+1 -1
View File
@@ -16,7 +16,7 @@ path = "src/lib.rs"
[dependencies]
arbitrary = { version = "1", features = ["derive"] }
bytes = "1.12.2"
http = "1.5.0"
http = "1.6.0"
jiff = { version = "1.0.2", features = ["serde"] }
libfuzzer-sys = "0.4"
quick-xml = { version = "0.42.0", features = ["serialize", "serde-types", "encoding"] }
+1 -1
View File
@@ -422,7 +422,7 @@ rustfs-mimalloc = { workspace = true }
[target.'cfg(target_os = "linux")'.dependencies]
libsystemd.workspace = true
rustfs-mimalloc = { workspace = true, features = ["no_thp"] }
rustfs-mimalloc-sys = "0.7.5"
rustfs-mimalloc-sys = "0.7.6"
[target.'cfg(any(all(target_os = "macos", any(target_arch = "x86_64", target_arch = "aarch64")), all(target_os = "linux", target_env = "gnu", any(target_arch = "x86_64", target_arch = "aarch64"))))'.dependencies]
pyroscope = { workspace = true, optional = true, features = ["backend-pprof-rs"] }
@@ -405,18 +405,17 @@ fn collect_resettable_replication_target_arns(config: &PersistedReplicationConfi
continue;
}
let legacy_role = replication::legacy_role_target_arn(&config.role);
let arn = if let Some(role) = legacy_role {
role.to_string()
} else {
let arn = if config.role.trim().is_empty() {
rule.destination.bucket.trim().to_string()
} else {
config.role.trim().to_string()
};
if seen.insert(arn.clone()) {
arns.push(arn);
}
if legacy_role.is_some() {
if !config.role.trim().is_empty() {
break;
}
}
@@ -271,7 +271,8 @@ fn validate_replication_check_config_targets(
}
}
if let Some(role) = crate::admin::storage_api::bucket::replication::legacy_role_target_arn(&config.role) {
let role = config.role.trim();
if !role.is_empty() {
if !configured_arns.contains(role) {
return Err(S3Error::with_message(
S3ErrorCode::InvalidRequest,
+1 -2
View File
@@ -568,8 +568,7 @@ pub(crate) mod replication {
OperatorRuleContract, REMOTE_TARGET_CAPABILITY_CONTRACT_VERSION, REMOTE_TARGET_READ_ONLY_HISTORICAL_FIELDS,
REMOTE_TARGET_UNSUPPORTED_FIELDS, REMOTE_TARGET_WRITABLE_FIELDS, REPLICATION_CAPABILITY_CONTRACT_VERSION,
REPLICATION_READ_ONLY_HISTORICAL_FIELDS, REPLICATION_WRITABLE_FIELDS, assign_site_replication_rule_priorities,
legacy_role_target_arn, merge_incoming_replication_config, replication_target_arn_deployment_id,
site_replication_rule_deployment_id,
merge_incoming_replication_config, replication_target_arn_deployment_id, site_replication_rule_deployment_id,
};
pub(crate) type BucketReplicationResyncStatus = super::ecstore_bucket::replication::BucketReplicationResyncStatus;
pub(crate) type BucketStats = super::ecstore_bucket::replication::BucketStats;
+1 -25
View File
@@ -5140,12 +5140,6 @@ impl DefaultObjectUsecase {
// Clone ObjectInfo for event notification only when an event will
// actually be built — the clone is expensive for multipart objects.
let event_info = helper.wants_object_info().then(|| info.clone());
let has_version_id = input.version_id.is_some();
let raw_tag_count = if !info.user_tags.is_empty() {
decode_tags(&info.user_tags).len()
} else {
0
};
let output_build_start = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
let output_context = self
@@ -5211,31 +5205,13 @@ impl DefaultObjectUsecase {
);
}
let GetObjectOutputContext {
mut output,
output,
event_info,
effective_ec_block_size,
response_content_length,
optimal_buffer_size,
extra_checksum_headers,
} = output_context;
if raw_tag_count > 0 {
let tagging_action = if has_version_id {
S3Action::GetObjectVersionTaggingAction
} else {
S3Action::GetObjectTaggingAction
};
let replication_check = replication_request_authorized(&envelope)
&& get_header(envelope.headers(), SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() == Some("true");
let tag_count_allowed = match head::head_metadata_action_allowed(&envelope, tagging_action).await {
Ok(allowed) => allowed,
Err(err) => {
return Self::complete_get_object_error(helper.version_id(version_id_for_event), err);
}
};
if replication_check || tag_count_allowed {
output.dto.tag_count = i32::try_from(raw_tag_count).ok();
}
}
let total_duration = request_start.elapsed();
Self::finalize_get_object_completion(
+18 -67
View File
@@ -53,7 +53,7 @@ pub(crate) struct ResponseEtag {
impl ResponseEtag {
pub(crate) fn to_http_header(&self) -> Result<http::HeaderValue, http::header::InvalidHeaderValue> {
let prefix = if self.weak { "W/" } else { "" };
http::HeaderValue::from_str(&format!("{prefix}\"{}\"", self.opaque))
http::HeaderValue::from_bytes(format!("{prefix}\"{}\"", self.opaque).as_bytes())
}
pub(super) fn from_stored(value: &str) -> Self {
@@ -123,7 +123,7 @@ fn tagging_directive_is_access(headers: &http::HeaderMap) -> bool {
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"ACCESS"))
}
pub(super) async fn head_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
async fn head_metadata_action_allowed(req: &RequestEnvelope, action: S3Action) -> S3Result<bool> {
// Metadata permissions still bind the owner when a policy explicitly denies them.
let mut probe = req.fork_for_authorization();
let Some(info) = probe.req_info_mut() else {
@@ -138,32 +138,6 @@ pub(super) async fn head_metadata_action_allowed(req: &RequestEnvelope, action:
}
}
async fn maybe_insert_head_tag_count_header(
req: &RequestEnvelope,
headers: &mut HeaderMap,
tag_count: usize,
has_version_id: bool,
replication_check: bool,
) -> S3Result<bool> {
if tag_count == 0 {
return Ok(false);
}
let tagging_action = if has_version_id {
S3Action::GetObjectVersionTaggingAction
} else {
S3Action::GetObjectTaggingAction
};
if !(replication_check || head_metadata_action_allowed(req, tagging_action).await?) {
return Ok(false);
}
if let Ok(header_value) = tag_count.to_string().parse::<HeaderValue>() {
headers.insert(http::HeaderName::from_static(AMZ_TAG_COUNT), header_value);
} else {
warn!("Failed to parse x-amz-tagging-count header; skipping");
}
Ok(true)
}
/// Source HEAD seam for the on-demand migration passthrough: production goes
/// through [`SourceClient`], tests script the answers.
pub(super) trait OdmHeadSource {
@@ -364,7 +338,7 @@ impl DefaultObjectUsecase {
key: &str,
opts: &ObjectOptions,
part_number: Option<i32>,
) -> Option<(HeadObjectOutputFacts, Option<i32>)> {
) -> Option<HeadObjectOutputFacts> {
let targets = get_read_proxy_targets(bucket, key, opts).await;
if targets.is_empty() {
return None;
@@ -392,8 +366,7 @@ impl DefaultObjectUsecase {
// MinIO-aligned accounting: one total per proxy attempt,
// one failed when no target served it.
record_replication_proxy(bucket, "HeadObject", false).await;
let remote_tag_count = remote.tag_count;
return Some((Self::proxy_sdk_head_output(remote), remote_tag_count));
return Some(Self::proxy_sdk_head_output(remote));
}
Err(err) if Self::proxy_sdk_error_is_not_found(&err) => {
debug!(bucket, key, arn = %target.arn, "read proxy: target does not have the object");
@@ -591,7 +564,7 @@ impl DefaultObjectUsecase {
// locally may still be served by proxying the HEAD to a
// replication target (backlog#1675 P1-5).
if req.object_tag_conditions().is_none()
&& let Some((output, remote_tag_count)) = Box::pin(Self::proxy_head_object_to_replication_targets(
&& let Some(output) = Box::pin(Self::proxy_head_object_to_replication_targets(
&req,
&bucket,
&key,
@@ -600,19 +573,7 @@ impl DefaultObjectUsecase {
))
.await
{
let mut response = read_answer(&bucket, req.method(), req.headers(), output).await;
if let Some(tag_count) = remote_tag_count.and_then(|count| usize::try_from(count).ok()) {
let replication_check = replication_request_authorized(&req)
&& get_header(req.headers(), SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() == Some("true");
maybe_insert_head_tag_count_header(
&req,
&mut response.headers,
tag_count,
version_id.is_some(),
replication_check,
)
.await?;
}
let response = read_answer(&bucket, req.method(), req.headers(), output).await;
let result = Ok(response);
complete_read(helper.version_id(version_id.unwrap_or_default()), &result);
return result;
@@ -807,7 +768,18 @@ impl DefaultObjectUsecase {
// Add x-amz-tagging-count header if object has tags
// Per S3 API spec, this header should be present in HEAD object response when tags exist
if maybe_insert_head_tag_count_header(&req, &mut response.headers, tag_count, has_version_id, replication_check).await? {
let tagging_action = if has_version_id {
S3Action::GetObjectVersionTaggingAction
} else {
S3Action::GetObjectTaggingAction
};
if tag_count > 0 && (replication_check || head_metadata_action_allowed(&req, tagging_action).await?) {
let header_name = http::HeaderName::from_static(AMZ_TAG_COUNT);
if let Ok(header_value) = tag_count.to_string().parse::<HeaderValue>() {
response.headers.insert(header_name, header_value);
} else {
warn!("Failed to parse x-amz-tagging-count header; skipping");
}
// MinIO `x-amz-tagging-directive: ACCESS`: a replication source
// compares the replica's tag set, which the count cannot express.
// Gated by the same authorization as the count above.
@@ -1495,27 +1467,6 @@ mod tests {
authorize_head_object(&slot, &mut envelope, &bucket, "protected", version.as_deref())
.await
.expect("ordinary HEAD read is permitted");
// Proxied HEAD tag-count insertion must enforce the same
// version-aware tagging authorization and replication-check
// exception as local HEAD responses.
let mut proxied_headers = HeaderMap::new();
let proxied_replication_check = replication_request_authorized(&envelope)
&& get_header(envelope.headers(), SUFFIX_SOURCE_REPLICATION_CHECK).as_deref() == Some("true");
let proxied_inserted = maybe_insert_head_tag_count_header(
&envelope,
&mut proxied_headers,
2,
version.is_some(),
proxied_replication_check,
)
.await
.expect("proxied HEAD tag-count check");
assert_eq!(proxied_inserted, replica || (grant && !explicit_deny));
assert_eq!(
proxied_headers.get(AMZ_TAG_COUNT).map(HeaderValue::as_bytes),
(replica || (grant && !explicit_deny)).then_some(b"2".as_slice()),
"proxied HEAD x-amz-tagging-count header"
);
let input = head_object_input(&bucket, "protected", version);
let response = Box::pin(usecase.execute_head_object_fields(envelope, input.into()))
.await
+2 -1
View File
@@ -85,7 +85,8 @@ pub(crate) fn post_metadata_headers(
}
}
if let Some(value) = content_type {
let wire = HeaderValue::from_str(value).map_err(|_| s3_error!(InvalidArgument, "Invalid POST content field"))?;
let wire =
HeaderValue::from_bytes(value.as_bytes()).map_err(|_| s3_error!(InvalidArgument, "Invalid POST content field"))?;
let base = value.split(';').next().unwrap_or(value).trim();
if !base.is_ascii() {
return Err(s3_error!(InvalidArgument, "Invalid POST content field"));
+2 -2
View File
@@ -740,7 +740,7 @@ fn build_put_object_expiration_header(event: &lifecycle::Event) -> Option<String
// parser, which rejects `2026-10-02T00:00:00Z` and drops the metadata.
let expiry_date = format_http_date(&expire_time).ok()?;
let value = format!("expiry-date=\"{}\", rule-id=\"{}\"", expiry_date, event.rule_id);
http::HeaderValue::from_str(&value).is_ok().then_some(value)
http::HeaderValue::from_bytes(value.as_bytes()).is_ok().then_some(value)
}
pub(super) fn internal_object_info_lookup_opts(mut opts: ObjectOptions) -> ObjectOptions {
@@ -2278,7 +2278,7 @@ mod tests {
}
event.rule_id = "保留策略".to_owned();
let header = build_put_object_expiration_header(&event).expect("valid UTF-8 IDs remain supported");
assert!(http::HeaderValue::from_str(&header).is_ok());
assert!(http::HeaderValue::from_bytes(header.as_bytes()).is_ok());
assert!(header.contains("保留策略"));
}
@@ -152,6 +152,14 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
.user_defined
.keys()
.any(|key| rustfs_utils::http::is_object_encryption_marker(key));
// The upload's checksum contract, recorded at CreateMultipartUpload, is echoed here so a
// client resuming from ListParts sees the same algorithm and type.
let checksum_algorithm = (!page.checksum_algorithm.is_empty())
.then_some(page.checksum_algorithm)
.map(dto::ChecksumAlgorithm::custom);
let checksum_type = (!page.checksum_type.is_empty())
.then_some(page.checksum_type)
.map(dto::ChecksumType::custom);
let parts = page
.parts
.into_iter()
@@ -168,12 +176,23 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
i64::try_from(part.size)
.map_err(|_| s3_error!(InternalError, "a stored part size is outside the ListParts response range"))?
};
let checksums = part.checksums.unwrap_or_default();
let checksum = |algorithm: &str| checksums.get(algorithm).cloned();
Ok(dto::Part {
e_tag: dto_values::stored_etag(tag),
last_modified: part.last_mod.map(dto_values::timestamp),
part_number,
size,
..Default::default()
checksum_crc32: checksum("CRC32"),
checksum_crc32c: checksum("CRC32C"),
checksum_crc64nvme: checksum("CRC64NVME"),
checksum_sha1: checksum("SHA1"),
checksum_sha256: checksum("SHA256"),
checksum_sha512: checksum("SHA512"),
checksum_md5: checksum("MD5"),
checksum_xxhash3: checksum("XXHASH3"),
checksum_xxhash64: checksum("XXHASH64"),
checksum_xxhash128: checksum("XXHASH128"),
})
})
.collect::<S3Result<_>>()?;
@@ -192,6 +211,8 @@ fn list_parts_output(page: ListPartsInfo) -> S3Result<dto::ListPartsOutput> {
storage_class: Some(dto::StorageClass::custom(
effective_class(Some(page.storage_class.as_str()), None).to_owned(),
)),
checksum_algorithm,
checksum_type,
..Default::default()
})
}
@@ -84,6 +84,36 @@ fn test_list_parts_output_maps_parts_and_owner() {
assert_eq!(initiator.display_name, owner.display_name);
}
#[test]
fn test_list_parts_output_maps_recorded_checksums() {
let output = list_parts_output(ListPartsInfo {
checksum_algorithm: "SHA256".into(),
checksum_type: "COMPOSITE".into(),
parts: vec![PartInfo {
size: 5,
checksums: Some(std::collections::HashMap::from([
("CRC32".to_owned(), "part-crc32".to_owned()),
("SHA256".to_owned(), "part-sha256".to_owned()),
])),
..part(1)
}],
..page()
})
.unwrap();
assert_eq!(output.checksum_algorithm.as_ref().map(|value| value.as_str()), Some("SHA256"));
assert_eq!(output.checksum_type.as_ref().map(|value| value.as_str()), Some("COMPOSITE"));
assert_eq!(output.parts[0].checksum_crc32.as_deref(), Some("part-crc32"));
assert_eq!(output.parts[0].checksum_sha256.as_deref(), Some("part-sha256"));
assert!(output.parts[0].checksum_sha1.is_none());
let xml = encode_xml(output);
assert!(xml.contains("<ChecksumAlgorithm>SHA256</ChecksumAlgorithm>"), "{xml}");
assert!(xml.contains("<ChecksumType>COMPOSITE</ChecksumType>"), "{xml}");
assert!(xml.contains("<ChecksumCRC32>part-crc32</ChecksumCRC32>"), "{xml}");
assert!(xml.contains("<ChecksumSHA256>part-sha256</ChecksumSHA256>"), "{xml}");
}
#[test]
fn test_list_parts_output_xml_omits_terminal_marker() {
for (marker, parts) in [(0, vec![]), (3, vec![10]), (0, vec![1, 3])] {
+23
View File
@@ -135,6 +135,18 @@ fn resp<O: Served>(answered: Answered<O::Output>) -> Resp<O> {
.with_extra_headers(headers)
}
// RUSTFS_COMPAT_TODO(http-opaque-response-headers): Preserve UTF-8 response values. Remove after the gateway codec emits opaque bytes.
fn preserve_opaque_header(headers: &mut http::HeaderMap, name: impl http::header::IntoHeaderName, field: Option<&str>) {
// Keep the typed field so the encoder does not write a default Content-Type.
// Its ASCII constructor skips the opaque value, leaving the extra header to supply it.
if let Some(value) = field
&& !value.is_ascii()
&& let Ok(value) = http::HeaderValue::from_bytes(value.as_bytes())
{
headers.insert(name, value);
}
}
impl<O: Served> Handler<O> for GatewayBackend {
async fn call(&self, request: Req<O>) -> HandlerResult<O> {
self.serve(request).await
@@ -270,6 +282,17 @@ mod tests {
assert_eq!(registered, rows(OPERATIONS).map(|row| row.name).collect());
}
#[test]
fn expiration_projection_preserves_utf8_without_accepting_controls() {
let mut headers = http::HeaderMap::new();
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, Some("rule-id=\"保留策略\""));
assert_eq!(headers[rustfs_utils::http::AMZ_EXPIRATION].as_bytes(), "rule-id=\"保留策略\"".as_bytes());
headers.clear();
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, Some("rule-id=\"保留\n策略\""));
assert!(headers.is_empty());
}
/// An invalid header value does not alter the response status or other headers.
#[test]
fn a_stored_tag_a_header_cannot_hold_is_left_out_and_the_answer_stands() {
@@ -14,7 +14,7 @@
//! The gateway operations of migration batch C (rustfs/backlog#2765): GetObject, HeadObject and GetObjectAttributes.
use super::{OpRow, Served, resp, row};
use super::{OpRow, Served, preserve_opaque_header, resp, row};
use crate::app::object_usecase::{
DefaultObjectUsecase, GetObjectAttributesFields, GetObjectAttributesOutputFacts, GetObjectBody, GetObjectOutputFacts,
HeadObjectOutputFacts, ResponseEtag,
@@ -28,7 +28,7 @@ use crate::storage_api::server::http::access::access_owned::object_read::{
use rustfs_gateway::{Req, Resp, dto};
use rustfs_s3_ops::S3Operation;
use rustfs_s3_types::{S3ErrorCode, S3Result, s3_error};
use rustfs_utils::http::{SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
use rustfs_utils::http::{AMZ_EXPIRATION, SUFFIX_SOURCE_REPLICATION_CHECK, get_header};
use std::sync::Arc;
pub(super) const ROWS: &[OpRow] = &[
@@ -63,9 +63,18 @@ impl Served for dto::HeadObject {
authorize_head_object(&server_ctx, envelope, bucket, key, version_id).await
}
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
let preserve_content_type = request.input().response_content_type.is_none();
let result = DefaultObjectUsecase::with_context(context)
.execute_head_object(envelope, request.into_input())
.await;
.await
.map(|mut answered| {
preserve_opaque_header(
&mut answered.headers,
http::header::CONTENT_TYPE,
answered.output.dto.content_type.as_deref().filter(|_| preserve_content_type),
);
answered
});
head_result(result)
}
}
@@ -95,10 +104,19 @@ impl Served for dto::GetObject {
}
async fn execute(context: Option<Arc<AppContext>>, envelope: RequestEnvelope, request: Req<Self>) -> S3Result<Resp<Self>> {
let log_error = super::error::object_error_logger("GetObject", request.context().transport_extensions().clone());
let preserve_content_type = request.input().response_content_type.is_none();
let result = get_result(
DefaultObjectUsecase::with_context(context)
.execute_gateway_get_object(envelope, request.into_input())
.await,
.await
.map(|mut answered| {
preserve_opaque_header(
&mut answered.headers,
http::header::CONTENT_TYPE,
answered.output.dto.content_type.as_deref().filter(|_| preserve_content_type),
);
answered
}),
);
result.inspect_err(log_error)
}
@@ -222,6 +240,7 @@ pub(super) fn get_response(answered: Answered<GetObjectOutputFacts>) -> S3Result
} = answered;
insert_etag(&mut headers, output.etag)
.map_err(|_| s3_error!(InternalError, "We encountered an internal error. Please try again."))?;
preserve_opaque_header(&mut headers, AMZ_EXPIRATION, output.dto.expiration.as_ref().map(AsRef::as_ref));
output.dto.body = output
.body
.map(|body| match body {
@@ -271,6 +290,7 @@ pub(super) fn head_response(answered: Answered<HeadObjectOutputFacts>) -> S3Resu
mut headers,
} = answered;
insert_etag(&mut headers, output.etag)?;
preserve_opaque_header(&mut headers, AMZ_EXPIRATION, output.dto.expiration.as_ref().map(AsRef::as_ref));
Ok(resp::<dto::HeadObject>(Answered {
output: output.dto,
status,
@@ -14,7 +14,7 @@
//! PutObject gateway registration and native request/response projection.
use super::{OpRow, Served, row};
use super::{OpRow, Served, preserve_opaque_header, row};
use crate::app::RequestEnvelope;
use crate::app::multipart_usecase::{DefaultMultipartUsecase, UploadPartTarget, UploadPartWriteInput, UploadPartWriteOutput};
use crate::app::object::FrameTrailers;
@@ -275,6 +275,7 @@ fn native_output(output: PutObjectWriteOutput) -> S3Result<Resp<dto::PutObject>>
output.checksum_crc64nvme,
],
)?;
preserve_opaque_header(&mut headers, rustfs_utils::http::AMZ_EXPIRATION, output.expiration.as_deref());
let dto = dto::PutObjectOutput {
e_tag: crate::app::dto_values::stored_etag(
output
+3 -26
View File
@@ -195,7 +195,7 @@ impl GatewayStack {
let iam = Arc::new(ServerIam {
server_ctx: Arc::clone(&assembly.server_ctx),
});
let root = Arc::new(control_plane_root(&assembly)?);
let root = Arc::new(live_root(Arc::clone(&assembly.server_ctx)));
admin::assemble(assembly, iam, root)
}
@@ -207,7 +207,7 @@ impl GatewayStack {
let iam = Arc::new(ServerIam {
server_ctx: Arc::clone(&assembly.server_ctx),
});
let root = Arc::new(control_plane_root(&assembly)?);
let root = Arc::new(live_root(Arc::clone(&assembly.server_ctx)));
control_plane::assemble(assembly, iam, root, router)
}
@@ -217,7 +217,7 @@ impl GatewayStack {
let iam = Arc::new(ServerIam {
server_ctx: Arc::clone(&assembly.server_ctx),
});
let root = Arc::new(control_plane_root(&assembly)?);
let root = Arc::new(live_root(Arc::clone(&assembly.server_ctx)));
reserved_console::assemble(assembly, iam, root)
}
@@ -728,29 +728,6 @@ impl EarlyAuthHandoff {
}
}
/// Control-plane and admin hosts bypass `ReadinessGateLayer` so their own admission gates
/// (`AdminBridge`, `S3Router::admit`, `ReservedConsole`) can return an audited `503
/// ServiceUnavailable` after signature verification. While `server_ctx` has no installed
/// `AppContext`, verify root signatures against this server's configured `GatewayAssembly`
/// credentials; once `AppContext` is installed, delegate strictly to `live_root`.
pub(super) fn control_plane_root(
assembly: &GatewayAssembly,
) -> Result<impl Fn() -> Option<Arc<RootCredentials>> + Send + Sync + 'static, GatewayAssemblyError> {
let startup_root = Arc::new(
RootCredentials::new(&assembly.root_access_key, &assembly.root_secret_key, &assembly.root_secret_key)
.map_err(GatewayAssemblyError::RootCredentials)?,
);
let server_ctx = Arc::clone(&assembly.server_ctx);
let live = live_root(Arc::clone(&server_ctx));
Ok(move || {
if server_ctx.installed_app_context().is_some() {
live()
} else {
Some(Arc::clone(&startup_root))
}
})
}
/// The root credentials of one server as they are now, read strictly from this server's installed
/// `AppContext` (never falling back to process-global credentials or token-signing keys). `None`
/// while this server context is uninstalled, lacks root credentials, or cannot verify a signature,
@@ -1128,34 +1128,3 @@ async fn typed_admin_routes_enforce_pre_body_iam_target_validation_and_presigned
Box::pin(assert_typed_admin_target_replication_and_heal_writes(&stack)).await;
Box::pin(assert_typed_admin_gets_and_object_lambda_fallback(&stack)).await;
}
#[tokio::test]
async fn pre_install_assembled_admin_and_control_plane_answer_503_not_500() {
let slot = ServerContextSlot::new();
let mut not_ready_assembly = assembly();
not_ready_assembly.server_ctx = Arc::clone(&slot);
let mut router = S3Router::new(false);
router.set_server_ctx(Arc::clone(&slot));
router
.insert(Method::GET, "/rustfs/admin/v3/pools/list", AdminOperation(&PROBE))
.expect("pools/list probe route");
let control_plane =
GatewayStack::assemble_control_plane(not_ready_assembly.clone(), Arc::new(router)).expect("control plane assembles");
let (status, _, body) = answer_request(&control_plane, signed(Method::GET, "/rustfs/admin/v3/pools/list", "")).await;
assert_eq!(
status,
StatusCode::SERVICE_UNAVAILABLE,
"pre-install control-plane request must return 503 ServiceUnavailable instead of 500: {body}"
);
assert!(body.contains("ServiceUnavailable"), "unexpected body: {body}");
let admin_stack = GatewayStack::assemble_admin(not_ready_assembly).expect("admin stack assembles");
let (admin_status, _, admin_body) = answer_request(&admin_stack, signed(Method::GET, "/rustfs/admin/v3/info", "")).await;
assert_eq!(
admin_status,
StatusCode::SERVICE_UNAVAILABLE,
"pre-install admin info request must return 503 ServiceUnavailable instead of 500: {admin_body}"
);
}
+6 -8
View File
@@ -1304,7 +1304,6 @@ pub(crate) fn bucket_target_matches_peer(target: &BucketTarget, peer: &PeerInfo)
}
pub(crate) fn site_replication_target_arns_by_peer(
bucket: &str,
config: Option<&PersistedReplicationConfiguration>,
) -> HashMap<String, String> {
let mut arns_by_peer = HashMap::new();
@@ -1313,13 +1312,12 @@ pub(crate) fn site_replication_target_arns_by_peer(
};
let mut configured_arns = Vec::new();
let role_arn = config.role.trim();
if !role_arn.is_empty() && role_arn.parse::<ARN>().is_ok_and(|parsed| parsed.bucket == bucket) {
configured_arns.push(role_arn.to_string());
if !config.role.trim().is_empty() {
configured_arns.push(config.role.clone());
}
for rule in config.rules.iter().filter(|rule| is_derived_site_replication_rule(rule)) {
for rule in &config.rules {
let arn = rule.destination.bucket.trim();
if !arn.is_empty() && arn.parse::<ARN>().is_ok_and(|parsed| parsed.bucket == bucket) {
if !arn.is_empty() {
configured_arns.push(arn.to_string());
}
}
@@ -1401,7 +1399,7 @@ pub(crate) fn reconcile_site_replication_bucket_targets(
return Ok(existing);
}
let configured_arns = site_replication_target_arns_by_peer(bucket, config);
let configured_arns = site_replication_target_arns_by_peer(config);
let mut targets = existing.targets;
for peer in state.peers.values() {
@@ -1664,7 +1662,7 @@ pub(crate) fn build_site_replication_config(
// Reuse the ARN already recorded for a peer so the rule keeps pointing at the same
// bucket target `reconcile_site_replication_bucket_targets` keys off (a MinIO-era
// `arn:minio:...` target would otherwise be orphaned by a freshly minted ARN).
let configured_arns = site_replication_target_arns_by_peer(bucket, existing);
let configured_arns = site_replication_target_arns_by_peer(existing);
let mut rules = Vec::new();
for peer in state.peers.values() {
if peer.deployment_id == local_peer.deployment_id || same_identity_endpoint(&peer.endpoint, &local_peer.endpoint) {
-30
View File
@@ -2139,36 +2139,6 @@ fn test_reconcile_site_replication_bucket_targets_keeps_operator_target_to_peer(
reconciled_again.targets[1].bandwidth_limit, 9,
"operator tuning of the site target carries over"
);
// An operator replication rule targeting a distinct bucket on the same peer
// deployment (`arn:minio:replication:us-east-1:remote:photos-dst`) must never
// be adopted as the site-replication target ARN, which would duplicate the
// operator target ARN in `BucketTargets` and disable both target clients.
let operator_peer_arn = "arn:minio:replication:us-east-1:remote:photos-dst".to_string();
let mut operator_on_peer = operator_target.clone();
operator_on_peer.arn = operator_peer_arn.clone();
let operator_config = PersistedReplicationConfiguration {
role: String::new(),
rules: vec![build_site_replication_rule(&operator_peer_arn, 1, "operator-bucket-repl")],
};
let reconciled_with_cfg = reconcile_site_replication_bucket_targets(
BucketTargets {
targets: vec![operator_on_peer.clone(), site_target.clone()],
},
"photos",
&state,
&local,
Some(&operator_config),
"secret",
)
.expect("reconcile targets with operator replication rule");
assert_eq!(reconciled_with_cfg.targets.len(), 2);
assert_eq!(reconciled_with_cfg.targets[0].arn, operator_peer_arn);
assert_eq!(reconciled_with_cfg.targets[1].arn, "arn:minio:replication::remote:photos");
assert_ne!(
reconciled_with_cfg.targets[0].arn, reconciled_with_cfg.targets[1].arn,
"site target must keep its own same-name bucket ARN"
);
}
#[test]
+1 -1
View File
@@ -794,7 +794,7 @@ pub fn parse_etag(object_etag: &str) -> Result<HeaderValue, S3Error> {
let etag_quoted = format!("\"{}\"", etag_trimmed);
HeaderValue::from_str(&etag_quoted).map_err(|e| {
HeaderValue::from_bytes(etag_quoted.as_bytes()).map_err(|e| {
warn!(
"Failed to convert ETag to HeaderValue (ETag: {}): {}. The ETag header will be omitted from the response.",
etag_quoted, e
@@ -807,6 +807,17 @@ fn gateway_post_archive_encoding_uses_form_content_fields() {
.request("GET", &format!("/{BUCKET}/quoted-utf8"), b"", &[], Some(0))
.await;
assert_eq!(read.headers.get("content-type").map(String::as_str), Some("text/plain; name=\"café\""));
let overridden = root
.request(
"GET",
&format!("/{BUCKET}/quoted-utf8?response-content-type=text%2Fplain"),
b"",
&[],
Some(0),
)
.await;
assert_eq!(overridden.status, 200, "{}", overridden.body);
assert_eq!(overridden.headers.get("content-type").map(String::as_str), Some("text/plain"));
server.shutdown().await;
},
);
+19 -3
View File
@@ -24,6 +24,16 @@ CORE_TESTS = {
"head_object_consistency_test::head_object_consistency_after_write_and_multipart_and_presigned_head",
"storage_class_capability_test::tests::historical_label_only_metadata_is_standard_without_hiding_a_real_transition_tier",
}
DST_SUITE = "rustfs-ecstore::dst_production_ecstore"
DST_TESTS = {
"dst_prod_test1_quorum_put_get_delete_offline_and_enospc",
"dst_prod_test2_physical_bitrot_highwayhash_detect_reconstruct_and_heal",
"dst_prod_test3_alice_power_loss_crash_consistency_old_or_new_never_mixed",
"metadata_write_crash_preserves_published_metadata",
"dst_prod_test4_deterministic_multiseed_concurrent_chaos_and_replay_equivalence",
"dst_prod_test5_multipart_commit_crash_cutpoints_before_rename_and_before_cleanup",
"multipart_replay_rejects_missing_or_other_disk_anchor",
}
def output(*args):
@@ -151,12 +161,16 @@ def selected_tests(listing):
return selected
def verify_execution(listing, junit, core=False):
def verify_execution(listing, junit, core=False, dst=False):
inventory = json.loads(Path(listing).read_text())
expected = selected_tests(inventory)
known = {(binary, name) for binary, suite in inventory["rust-suites"].items() for name in suite["testcases"]}
if core and (len(expected) != len(CORE_TESTS) or {name for _, name in expected} != CORE_TESTS):
raise ValueError("core contract must select exactly the write/read, denial and restart proofs")
if dst:
missing = {(DST_SUITE, name) for name in DST_TESTS} - expected
if missing:
raise ValueError(f"missing production DST tests: {sorted(missing)}")
report = ET.parse(junit).getroot()
if report.tag != "testsuites" or report.get("failures") != "0" or report.get("errors") != "0":
raise ValueError("test report must be a successful nextest run")
@@ -201,7 +215,9 @@ def main():
child = sub.add_parser("evidence")
child.add_argument("listing", type=Path)
child.add_argument("junit", type=Path)
child.add_argument("--core", action="store_true")
required = child.add_mutually_exclusive_group()
required.add_argument("--core", action="store_true")
required.add_argument("--dst", action="store_true")
args = parser.parse_args()
try:
if args.command == "build":
@@ -221,7 +237,7 @@ def main():
"doc": [*selection, "--doc"], "warm": ["--no-run", *selection]}[args.operation]
subprocess.run(command, cwd=ROOT, check=True)
else:
print(f"Verified {verify_execution(args.listing, args.junit, args.core)} test executions")
print(f"Verified {verify_execution(args.listing, args.junit, args.core, args.dst)} test executions")
except (OSError, ValueError, KeyError, TypeError, ET.ParseError, subprocess.CalledProcessError) as error:
print(f"verification artifact: {error}", file=sys.stderr)
return 1
+13 -2
View File
@@ -244,10 +244,10 @@ class ExecutionEvidenceTests(unittest.TestCase):
self.listing = listing([("crate-a", "one", False), ("crate-b", "two", False), ("crate-b", "ignored", True)])
self.report = junit([("crate-a", "one", None), ("crate-b", "two", None)])
def verify(self, listing_value=None, report=None, *, core=False):
def verify(self, listing_value=None, report=None, *, core=False, dst=False):
self.listing_file.write_text(json.dumps(self.listing if listing_value is None else listing_value))
ET.ElementTree(self.report if report is None else report).write(self.junit_file)
return artifact.verify_execution(self.listing_file, self.junit_file, core=core)
return artifact.verify_execution(self.listing_file, self.junit_file, core=core, dst=dst)
def test_exact_selected_set_and_known_ignored_cases(self):
self.assertEqual(self.verify(), 2)
@@ -321,6 +321,17 @@ class ExecutionEvidenceTests(unittest.TestCase):
with self.subTest(attribute=attribute), self.assertRaises(ValueError):
self.verify(report=report)
def test_dst_rejects_a_green_report_with_a_missing_required_test(self):
cases = [(artifact.DST_SUITE, name) for name in sorted(artifact.DST_TESTS)]
for selected in [cases, cases[:-1]]:
inventory = listing([(suite, name, False) for suite, name in selected])
report = junit([(suite, name, None) for suite, name in selected])
if selected == cases:
self.assertEqual(self.verify(inventory, report, dst=True), len(cases))
else:
with self.assertRaisesRegex(ValueError, "missing production DST tests"):
self.verify(inventory, report, dst=True)
def test_core_requires_exactly_three_selected_proofs(self):
names = sorted(artifact.CORE_TESTS)
core_listing = listing([("e2e", name, False) for name in names])
+56 -2
View File
@@ -286,18 +286,48 @@ marker="$GUARD_DIR/$host"
case "${QUEUE_FIXTURE:-quiet}" in
missing) exit 2 ;;
hung) exec sleep 60 ;;
diskstats-*)
QUEUE_SAMPLE_DIR="$(mktemp -d "$GUARD_DIR/diskstats.XXXXXXXX")"
export QUEUE_SAMPLE_DIR
trap 'rm -rf -- "$QUEUE_SAMPLE_DIR"' EXIT
printf '10.00 0.00\n' >"$QUEUE_SAMPLE_DIR/uptime"
cat >"$QUEUE_SAMPLE_DIR/diskstats" <<'STATS'
259 0 nvme0n1 0 0 0 0 20 0 80 40 0 0 100
259 1 nvme1n1 0 0 0 0 30 0 80 60 0 0 100
STATS
cp "$QUEUE_SAMPLE_DIR/diskstats" "$QUEUE_SAMPLE_DIR/after"
if [[ "$QUEUE_FIXTURE" != diskstats-idle ]]; then
writes=24
write_ms=48
case "$QUEUE_FIXTURE" in
diskstats-reset-count) writes=19 ;;
diskstats-reset-time) write_ms=39 ;;
esac
printf '259 0 nvme0n1 0 0 0 0 %s 0 96 %s 0 0 250\n' "$writes" "$write_ms" >"$QUEUE_SAMPLE_DIR/after"
printf '259 1 nvme1n1 0 0 0 0 46 0 128 76 0 0 150\n' >>"$QUEUE_SAMPLE_DIR/after"
fi
advance_diskstats() {
printf '15.00 0.00\n' >"$QUEUE_SAMPLE_DIR/uptime"
cp "$QUEUE_SAMPLE_DIR/after" "$QUEUE_SAMPLE_DIR/diskstats"
}
export -f advance_diskstats
command=$(printf '%s\n' "$command" | sed \
's@/proc/uptime@"$QUEUE_SAMPLE_DIR/uptime"@g; s@/proc/diskstats@"$QUEUE_SAMPLE_DIR/diskstats"@g; s@^sleep 5$@advance_diskstats@')
bash -c "$command"
exit
;;
reset)
n=0
[[ ! -f "$marker" ]] || read -r n < "$marker"
n=$((n+1))
printf '%s\n' "$n" > "$marker"
if [[ "$host" == host-b && "$n" == 2 ]]; then
echo '0.050000 0.800000'
echo '0.050000 0.800000 0 NA NA'
exit 0
fi
;;
esac
echo '0.050000 0.070000'
echo '0.050000 0.070000 0 NA NA'
SSH
cat > "$GUARD_BIN/curl" <<'CURL'
#!/usr/bin/env bash
@@ -369,4 +399,28 @@ if PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE=hung "$SCRIPT_DIR/wait_cluster_disk_que
fi
rg -q 'failed or timed out' "$TMP_DIR/queue-timeout.log"
queue_cmd=("$SCRIPT_DIR/wait_cluster_disk_queue.sh"
--target a=host-a --devices a=nvme0n1+nvme1n1 --timeout-secs 11)
for fixture in diskstats-write diskstats-idle; do
PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE="$fixture" "${queue_cmd[@]}" >"$TMP_DIR/$fixture.tsv"
printf 'sample\tnode\tmean_queue\tpeak_queue\tcompleted_writes\twrite_ms_per_op\tpeak_write_ms_per_op\n' >"$TMP_DIR/expected.tsv"
for sample in 1 2; do
if [[ "$fixture" == diskstats-write ]]; then
printf '%s\ta\t0.020000\t0.030000\t20\t1.200000\t2.000000\n' "$sample"
else
printf '%s\ta\t0.000000\t0.000000\t0\tNA\tNA\n' "$sample"
fi
done >>"$TMP_DIR/expected.tsv"
diff -u "$TMP_DIR/expected.tsv" "$TMP_DIR/$fixture.tsv"
done
for fixture in diskstats-reset-count diskstats-reset-time; do
if PATH="$GUARD_BIN:$PATH" QUEUE_FIXTURE="$fixture" "${queue_cmd[@]}" >"$TMP_DIR/$fixture.log" 2>&1; then
echo "expected $fixture to fail an otherwise quiet sample" >&2
exit 1
fi
rg -q 'disk queue sample failed or timed out' "$TMP_DIR/$fixture.log"
done
echo "object batch benchmark enhanced tests passed"
+37 -9
View File
@@ -73,6 +73,7 @@ trap 'exit 143' TERM
# Only validated device names are placed in the SSH command. The sampler uses
# monotonic uptime and the weighted I/O milliseconds from /proc/diskstats.
# Write completions and write milliseconds describe the same sampling window.
sample=$(cat <<'REMOTE'
set -eu
export LC_ALL=C
@@ -81,8 +82,8 @@ snapshot() {
BEGIN { n=split(devices,d," "); for(i=1;i<=n;i++) want[d[i]]=1 }
FNR==NR { t=$1; next }
$3 in want {
if (NF<14 || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14
if (NF<14 || $8 !~ /^[0-9]+$/ || $11 !~ /^[0-9]+$/ || $14 !~ /^[0-9]+$/) exit 2
print $3,t,$14,$8,$11
got++
}
END { if (got!=n) exit 2 }
@@ -93,10 +94,36 @@ sleep 5
after=$(snapshot)
printf '%s\n--\n%s\n' "$before" "$after" | awk '
$0=="--" { second=1; next }
!second { if ($1 in t) bad=1; t[$1]=$2; w[$1]=$3; count++; next }
{ if (!($1 in t) || seen[$1]++ || $2<=t[$1] || $3<w[$1]) { bad=1; next }
q=($3-w[$1])/(1000*($2-t[$1])); sum+=q; if(q>peak)peak=q; got++ }
END { if (bad||!count||got!=count) exit 2; printf "%.6f %.6f\n",sum/count,peak }
!second {
if ($1 in t) bad=1
t[$1]=$2; w[$1]=$3; writes[$1]=$4; write_ms[$1]=$5
count++
next
}
{
if (!($1 in t) || seen[$1]++ || $2<=t[$1] || $3<w[$1] || $4<writes[$1] || $5<write_ms[$1]) {
bad=1
next
}
q=($3-w[$1])/(1000*($2-t[$1]))
sum+=q
if (q>peak) peak=q
completed=$4-writes[$1]
if (completed>0) {
elapsed_ms=$5-write_ms[$1]
total_completed+=completed
total_write_ms+=elapsed_ms
await_ms=elapsed_ms/completed
if (await_ms>peak_write_ms) peak_write_ms=await_ms
}
got++
}
END {
if (bad||!count||got!=count) exit 2
printf "%.6f %.6f %.0f",sum/count,peak,total_completed
if (total_completed>0) printf " %.6f %.6f\n",total_write_ms/total_completed,peak_write_ms
else printf " NA NA\n"
}
'
REMOTE
)
@@ -104,7 +131,7 @@ REMOTE
end=$((SECONDS+budget))
streak=0
sample_number=0
printf 'sample\tnode\tmean_queue\tpeak_queue\n'
printf 'sample\tnode\tmean_queue\tpeak_queue\tcompleted_writes\twrite_ms_per_op\tpeak_write_ms_per_op\n'
while ((end-SECONDS >= 5)); do
sample_number=$((sample_number+1))
remaining=$((end-SECONDS))
@@ -125,12 +152,13 @@ while ((end-SECONDS >= 5)); do
quiet=true
for i in "${!targets[@]}"; do
result=$(cat "$artifacts/$i")
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([0-9]+\.[0-9]+)$ ]]; then
if [[ ! "$result" =~ ^([0-9]+\.[0-9]+)\ ([0-9]+\.[0-9]+)\ ([0-9]+)\ (NA|[0-9]+\.[0-9]+)\ (NA|[0-9]+\.[0-9]+)$ ]]; then
echo "invalid disk queue sample from ${targets[i]%%=*}" >&2; exit 1
fi
mean="${BASH_REMATCH[1]}"
peak="${BASH_REMATCH[2]}"
printf '%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak"
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$sample_number" "${targets[i]%%=*}" "$mean" "$peak" \
"${BASH_REMATCH[3]}" "${BASH_REMATCH[4]}" "${BASH_REMATCH[5]}"
if ! awk -v mean="$mean" -v peak="$peak" 'BEGIN {exit !(mean<=0.25 && peak<=0.75)}'; then quiet=false; fi
done
if [[ "$quiet" == true ]]; then