Compare commits

..

4 Commits

Author SHA1 Message Date
唐小鸭 29a0eb91b9 Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-12-02 00:27:11 +08:00
唐小鸭 5a5acedbee Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-12-01 12:17:18 +08:00
唐小鸭 51bd41a30b Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-11-30 11:10:12 +08:00
唐小鸭 49f01af16d fix(replication): replay deletes deferred by a held source lock
A live delete replication that cannot take the source object lock was dropped: the worker discarded the outcome, and the two lock skips before the target call were only logged at debug. A bulk delete keeps its key locks until the whole batch commits and keeps running after its client disconnects, so a retried bulk delete of the same keys made earlier markers lose the five second lock wait and never reach the target, or reach it without the result being recorded on the source.

Report how an attempt ended. When a source-side lock or read kept it from running, or from persisting its result, the worker journals the delete so the periodic MRF replay drives it again. Target failures stay with the persisted state and the scanner as before, so an unreachable target does not fill the journal. The three source-deferred skips now log at warn.
2026-11-29 22:59:11 +08:00
53 changed files with 377 additions and 2526 deletions
-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"
);
}
}
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
};
use super::replication_resyncer::{
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
replicate_object_with_outcome, update_resync_status_cas,
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
};
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::{
@@ -1329,12 +1329,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let storage = self.storage.clone();
let stats = self.stats.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1389,12 +1391,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1434,6 +1438,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
let handle = tokio::spawn(async move {
@@ -1453,7 +1458,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let Some(operation) = operation else { break };
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
self.task_handles.lock().await.push(handle);
@@ -1677,27 +1683,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 +1700,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")
@@ -1951,7 +1941,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -1969,7 +1966,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
.await;
}
}
@@ -1986,7 +1984,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -2433,28 +2438,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 +2456,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 +2470,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 +2480,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);
}
}
@@ -2608,6 +2560,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
stats: Arc<ReplicationStats>,
storage: Arc<S>,
in_flight: Arc<ReplicationInFlight>,
mrf_save_tx: &Sender<MrfReplicateEntry>,
) {
match operation {
ReplicationOperation::Object(obj_info) => {
@@ -2617,8 +2570,14 @@ 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;
// The delete request already succeeded, so a source lock that is
// still held (a bulk delete keeps its key locks until the whole
// batch commits) must not cost the replication: journal it for
// the next MRF replay.
let retry_entry = del_info.to_mrf_entry();
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
}
}
}
}
@@ -4234,38 +4193,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;
@@ -4608,6 +4535,102 @@ mod tests {
}
}
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
async fn delete_worker_journal(
delete: DeletedObjectReplicationInfo,
writeback_error: EcstoreError,
) -> Vec<MrfReplicateEntry> {
let shared = empty_resync_shared_state();
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
process_replication_operation(
ReplicationOperation::Delete(Box::new(delete)),
Arc::new(ReplicationStats::new()),
storage,
Arc::new(ReplicationInFlight::default()),
&mrf_save_tx,
)
.await;
drop(mrf_save_tx);
let mut journaled = Vec::new();
while let Some(entry) = mrf_save_rx.recv().await {
journaled.push(entry);
}
journaled
}
fn purged_on_target_delete(
arn: &str,
version_id: Uuid,
target_status: VersionPurgeStatusType,
) -> DeletedObjectReplicationInfo {
DeletedObjectReplicationInfo {
bucket: "source".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "purged".to_string(),
version_id: Some(version_id),
replication_state: Some(ReplicationState {
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
..Default::default()
}),
..Default::default()
},
op_type: ReplicationType::Delete,
..Default::default()
}
}
#[tokio::test]
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
let arn = "arn:test";
let version_id = Uuid::new_v4();
// A bulk delete of the same key still holds the object lock.
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
));
let journaled =
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
assert_eq!(
journaled.len(),
1,
"a delete whose result never reached the source must be kept for replay"
);
let entry = &journaled[0];
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
assert_eq!(entry.version_id, Some(version_id));
assert_eq!(entry.op, MrfOpKind::Delete);
assert_eq!(entry.target_arns, vec![arn.to_string()]);
}
#[tokio::test]
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
let arn = "arn:test";
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
let completed = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
source_gone(),
)
.await;
assert!(completed.is_empty(), "a completed delete must not be replayed");
let target_pending = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
source_gone(),
)
.await;
assert!(
target_pending.is_empty(),
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
);
}
#[tokio::test]
async fn delete_worker_preserves_persisted_admission_without_live_config() {
let arn = "arn:test";
@@ -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);
}
}
@@ -2422,12 +2422,40 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
let _ = replicate_delete_with_outcome(dobj, storage).await;
}
/// How one delete replication attempt ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeleteReplicationAttempt {
/// Every admitted target finished and the source state was persisted.
Completed,
/// The attempt did not finish for a reason another path already owns: a
/// target failure is recorded in the persisted state for the scanner, and
/// a force delete or delete-marker purge journals its own intent.
Unfinished,
/// A source-side lock or read kept the attempt from running, or from
/// persisting its result. Nothing durable records that, so the caller must
/// keep the delete for a later attempt.
SourceDeferred,
}
impl DeleteReplicationAttempt {
fn from_finished(finished: bool) -> Self {
if finished { Self::Completed } else { Self::Unfinished }
}
}
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> bool {
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
}
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> DeleteReplicationAttempt {
if dobj.delete_object.force_delete {
return replicate_force_delete_to_targets(&dobj, storage).await;
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
}
let bucket = dobj.bucket.clone();
@@ -2472,7 +2500,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::Unfinished;
}
};
let target_arns = dobj.admitted_target_arns();
@@ -2480,7 +2508,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// Batch expiry can return an empty state after removing the source.
// It owes no remote work or local writeback. Persisted target admission
// must still be honored even when the live configuration is gone.
return true;
return DeleteReplicationAttempt::Completed;
}
if dobj.delete_object.delete_marker
@@ -2502,7 +2530,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
reason = "source_not_delete_marker",
"Skipping stale delete-marker replication"
);
return true;
return DeleteReplicationAttempt::Completed;
}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
debug!(
@@ -2520,7 +2548,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// purge-intent replay landing here on purpose). Purge instead
// of just skipping; the result decides whether an MRF replay
// may acknowledge the entry.
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
}
Err(err) => {
// A transient source error (lock timeout, IO error) must not
@@ -2529,7 +2557,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// target mint one more delete marker (rustfs#6823). Fail the
// entry without touching the target; the MRF replay / heal
// scanner retries once the source is readable again.
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2554,7 +2582,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
}
}
@@ -2565,7 +2593,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
{
Ok(ns_lock) => ns_lock,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2589,14 +2617,14 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
Ok(lock_guard) => lock_guard,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2620,7 +2648,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
@@ -2686,25 +2714,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
@@ -2876,7 +2886,12 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
}
};
replicate_delete_outcome(
if !state_persisted {
// The targets were driven, but the result never reached the source
// metadata, so a scanner pass would still see the pre-attempt state.
return DeleteReplicationAttempt::SourceDeferred;
}
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
expected_targets,
rinfos.targets.len(),
state_persisted,
@@ -2884,7 +2899,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// error returns early above instead of replicating unverified.
true,
&replication_status,
)
))
}
/// Reads the source version addressed by `delete_marker_version_id` so a
@@ -4346,28 +4361,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;
@@ -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);
}
+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,
+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;
}
+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;
+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
}
@@ -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(
+17 -66
View File
@@ -123,7 +123,7 @@ fn tagging_directive_is_access(headers: &http::HeaderMap) -> bool {
.is_some_and(|value| value.as_bytes().eq_ignore_ascii_case(b"ACCESS"))
}
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
+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]