Compare commits

...

9 Commits

Author SHA1 Message Date
Hauser Zhi c85677b69c test: fix SSE-C lint and native multipart copy-heal setup
Count warning matches directly and bind native multipart staging to the real bucket incarnation while preserving the historical version fixture.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 16:12:31 +08:00
Hauser Zhi 2ec19eac97 Merge remote-tracking branch 'origin/houseme/fix/rolling-put-stall' into houseme/fix/rolling-put-stall 2026-11-26 14:17:09 +08:00
Hauser Zhi 759a83af53 Merge origin/main into the rolling PUT fix
Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 14:10:02 +08:00
Hauser Zhi d6ddd91853 perf(ecstore): bound PUT rename preparation after quorum
Apply a single pre-dispatch deadline to remote routing and permit admission. Encode the request once those resources are available and keep existing ownership for dispatched mutations.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 14:10:02 +08:00
Hauser Zhi 576252fe17 Merge branch 'main' into houseme/fix/rolling-put-stall 2026-11-26 14:04:56 +08:00
Hauser Zhi 42393840a6 Merge remote-tracking branch 'origin/main' into houseme/fix/rolling-put-stall 2026-11-26 13:57:02 +08:00
Hauser Zhi 4406577d30 perf(ecstore): simplify quorum probes and rename fanout
Keep presence-only probes typed as unit results and share their cross-set error reduction with bucket-info queries. Reuse one path owner across disk rename tasks and allocate a connect deadline only when there is a spare.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 11:55:20 +08:00
Hauser Zhi a826b62904 perf(ecstore): bound PUT rename dialing after write quorum
Share a post-quorum connection deadline across remote rename producers. Unresolved connections can be skipped before dispatch while active mutations drain under the normal namespace owner.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 11:29:50 +08:00
Hauser Zhi 111f74e35e fix(ecstore): stop bucket presence checks at read quorum
A metadata-only bucket probe can finish after the existing read quorum has confirmed the volume. Preserve full error reduction when quorum has not been reached and keep ordered bucket info and mutation callers on their existing path.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
2026-11-26 11:09:04 +08:00
13 changed files with 545 additions and 217 deletions
+8 -16
View File
@@ -3203,12 +3203,11 @@ impl BucketMetadataSys {
Box::pin(async {
let store = self.object_store();
let options = crate::storage_api_contracts::bucket::BucketOptions::default();
let info = if require_write_quorum {
store.get_bucket_info_from_sets(bucket, &options).await
if require_write_quorum {
store.get_bucket_info_from_sets(bucket, &options).await.map(|_| ())
} else {
store.get_bucket_info_from_sets_at_read_quorum(bucket, &options).await
};
info.map(|_| ())
store.check_bucket_presence_at_read_quorum(bucket).await
}
}),
)
.await?;
@@ -3771,19 +3770,12 @@ impl BucketMetadataSys {
#[cfg(test)]
self.authority_disk_loads.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (bucket_info_res, metadata_res) = tokio::join!(
let (bucket_presence_res, metadata_res) = tokio::join!(
Box::pin(await_bucket_namespace_operation(
Some(guard),
bucket,
"bucket metadata snapshot existence check",
async {
store
.get_bucket_info_from_sets_at_read_quorum(
bucket,
&crate::storage_api_contracts::bucket::BucketOptions::default(),
)
.await
},
store.check_bucket_presence_at_read_quorum(bucket),
)),
Box::pin(await_bucket_namespace_operation(
Some(guard),
@@ -3792,8 +3784,8 @@ impl BucketMetadataSys {
load_bucket_metadata_parse_with_presence(Arc::clone(&store), bucket, false),
)),
);
match bucket_info_res {
Ok(_) => {}
match bucket_presence_res {
Ok(()) => {}
Err(Error::VolumeNotFound) => return Ok(BucketMetadataAuthority::MissingBucket),
Err(err) => return Err(err),
}
+240 -48
View File
@@ -32,8 +32,8 @@ use crate::disk::{
DeleteRecoveryInspection, DeleteRecoveryPage, DeleteRecoveryRpcOperation, DeleteRecoveryRpcReply, DiskAPI, DiskInfo,
DiskInfoOptions, DiskLocation, DiskOption, FileInfoVersions, FileReader, FileWriter, GuardedDeleteVersionsPayload,
GuardedFileInfoVersions, PartTransactionAction, PoolMetaNativeRecoveryRequest, PoolMetaNativeRecoveryResponse,
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp, SnapshotLeaseToken, UpdateMetadataOpts, VolumeInfo,
WalkDirOptions, batch_read_version_one_by_one,
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataGuards, RenameDataObservation, RenameDataResp,
RenameDispatchDeadline, SnapshotLeaseToken, UpdateMetadataOpts, VolumeInfo, WalkDirOptions, batch_read_version_one_by_one,
disk_store::{
DEFAULT_RUSTFS_DRIVE_ACTIVE_MONITORING, ENV_RUSTFS_DRIVE_ACTIVE_MONITORING, SKIP_IF_SUCCESS_BEFORE,
get_drive_active_check_interval, get_drive_active_check_timeout, get_drive_disk_info_timeout, get_drive_list_dir_timeout,
@@ -3313,6 +3313,25 @@ fn validate_decoded_file_info(file_info: &FileInfo) -> Result<()> {
file_info.validate_for_metadata_read().map_err(Into::into)
}
// Dropping preparation is safe only before the mutation enters the transport.
async fn before_rename_dispatch<T>(mut deadline: Option<RenameDispatchDeadline>, prepare: impl Future<Output = T>) -> Option<T> {
let Some(deadline) = deadline.as_mut() else {
return Some(prepare.await);
};
tokio::select! {
biased;
result = prepare => Some(result),
() = async {
let at = deadline.wait_for(Option::is_some).await.ok().and_then(|deadline| *deadline);
if let Some(at) = at {
time::sleep_until(at).await;
} else {
std::future::pending::<()>().await;
}
} => None,
}
}
impl RemoteDisk {
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_borrowed(
@@ -3335,6 +3354,7 @@ impl RemoteDisk {
dst_volume: &str,
dst_path: &str,
items: Vec<RenameBatchClientItem<'_>>,
dispatch_deadline: Option<RenameDispatchDeadline>,
) -> std::result::Result<RemoteRenameBatchStream, RenameBatchStartError> {
if self.rename_admission.is_none() || items.is_empty() || items.len() > 16 {
return Err(RenameBatchStartError::NotDispatched(DiskError::UnsupportedDisk));
@@ -3354,20 +3374,35 @@ impl RemoteDisk {
if let Some(error) = self.offline_bypass_error() {
return Err(RenameBatchStartError::NotDispatched(error));
}
let routing = super::client::node_service_rename_batch_client(
&self.addr,
TonicInterceptor::Signature(gen_tonic_signature_interceptor()),
);
let mut client = match tokio::time::timeout_at(deadline, routing).await {
Ok(Ok(Some(client))) => client,
Ok(Ok(None)) => return Err(RenameBatchStartError::UnsupportedBeforeStream),
Ok(Err(error)) => {
return Err(RenameBatchStartError::NotDispatched(DiskError::RemoteClientUnavailable(
error.to_string(),
)));
}
Err(_) => return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout)),
};
let prepared = before_rename_dispatch(dispatch_deadline, async {
let routing = super::client::node_service_rename_batch_client(
&self.addr,
TonicInterceptor::Signature(gen_tonic_signature_interceptor()),
);
let client = match tokio::time::timeout_at(deadline, routing).await {
Ok(Ok(Some(client))) => client,
Ok(Ok(None)) => return Err(RenameBatchStartError::UnsupportedBeforeStream),
Ok(Err(error)) => {
return Err(RenameBatchStartError::NotDispatched(DiskError::RemoteClientUnavailable(
error.to_string(),
)));
}
Err(_) => return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout)),
};
let admission = self
.acquire_rename_admission_until(items.len(), deadline)
.await
.map_err(RenameBatchStartError::NotDispatched)?;
let guard = RenameBatchCallGuard {
admission,
deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
Ok((client, guard))
})
.await
.ok_or(RenameBatchStartError::NotDispatched(DiskError::DiskNotFound))?;
let (mut client, mut guard) = prepared?;
let mut request_items = Vec::with_capacity(items.len());
for item in items {
let item_index = u32::try_from(item.slot)
@@ -3393,21 +3428,11 @@ impl RemoteDisk {
crate::cluster::rpc::set_tonic_canonical_body_digest(&mut request, &canonical_body)
.map_err(Error::other)
.map_err(RenameBatchStartError::NotDispatched)?;
let admission = self
.acquire_rename_admission_until(request.get_ref().items.len(), deadline)
.await
.map_err(RenameBatchStartError::NotDispatched)?;
let guard = RenameBatchCallGuard {
admission,
deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
let call_timeout = deadline.saturating_duration_since(tokio::time::Instant::now());
if call_timeout == Duration::ZERO {
guard.release_without_quarantine();
return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout));
}
let mut guard = guard;
guard.mark_dispatched();
let response = match self
.execute_peer_batch_with_timeout(
@@ -3433,7 +3458,6 @@ impl RemoteDisk {
Ok(guard.into_stream(response.into_inner(), expected_mask))
}
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_borrowed_with_fence(
&self,
src_volume: &str,
@@ -3443,6 +3467,36 @@ impl RemoteDisk {
dst_path: &str,
scanner_publication_lease_token: Option<Uuid>,
) -> Result<RenameDataResp> {
self.rename_data_observed(
src_volume,
src_path,
fi,
dst_volume,
dst_path,
RenameDataGuards {
scanner_publication_lease_token,
..Default::default()
},
)
.await
.result
}
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn rename_data_observed(
&self,
src_volume: &str,
src_path: &str,
fi: &FileInfo,
dst_volume: &str,
dst_path: &str,
guards: RenameDataGuards,
) -> RenameDataObservation {
let RenameDataGuards {
scanner_publication_lease_token,
dispatch_deadline,
..
} = guards;
let multipart_rename = src_volume == crate::disk::RUSTFS_META_MULTIPART_BUCKET;
let pool_meta_cas = rustfs_utils::http::metadata_compat::contains_key_str(
&fi.metadata,
@@ -3453,7 +3507,7 @@ impl RemoteDisk {
|| dst_path != "pool.bin"
|| scanner_publication_lease_token.is_some())
{
return Err(DiskError::UnsupportedDisk);
return RenameDataObservation::unknown(Err(DiskError::UnsupportedDisk));
}
trace!(
event = EVENT_REMOTE_DISK_RPC,
@@ -3469,11 +3523,36 @@ impl RemoteDisk {
"Remote disk RPC started"
);
self.execute_with_timeout_for_op(
let mut dispatch_expired = false;
let result = Self::execute_with_timeout_for_op(
self,
"rename_data",
|| async {
let prepare_started = rustfs_io_metrics::put_stage_timer();
let collect_prepare_timing = prepare_started.is_some();
let prepared = before_rename_dispatch(dispatch_deadline, async {
let get_client_started = collect_prepare_timing.then(Instant::now);
let client = self.get_client_with_msgpack_policy().await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_REMOTE_CLIENT_GET_CLIENT,
get_client_started,
);
let (client, policy) = client?;
let rename_deadline = tokio::time::Instant::now() + get_max_timeout_duration();
let rename_admission = self.acquire_rename_admission_until(1, rename_deadline).await?;
let rename_admission_guard = RenameBatchCallGuard {
admission: rename_admission,
deadline: rename_deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
Ok::<_, DiskError>((client, policy, rename_admission_guard))
})
.await;
let Some(prepared) = prepared else {
dispatch_expired = true;
return Err(DiskError::DiskNotFound);
};
let (mut client, mut policy, mut rename_admission_guard) = prepared?;
let msgpack_encode_started = collect_prepare_timing.then(Instant::now);
let file_info_bin = Bytes::from(encode_file_info_msgpack(fi)?);
rustfs_io_metrics::record_put_object_stage_duration_from(
@@ -3486,13 +3565,6 @@ impl RemoteDisk {
file_info_bin.len(),
);
}
let get_client_started = collect_prepare_timing.then(Instant::now);
let client = self.get_client_with_msgpack_policy().await;
rustfs_io_metrics::record_put_object_stage_duration_from(
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_REMOTE_CLIENT_GET_CLIENT,
get_client_started,
);
let (mut client, mut policy) = client?;
let bucket_incarnation_id = crate::store::bucket_heal_scope_for_object(dst_volume, dst_path)
.map(|scope| Bytes::copy_from_slice(scope.incarnation.as_bytes()))
.unwrap_or_default();
@@ -3504,13 +3576,6 @@ impl RemoteDisk {
let scanner_publication_lease = scanner_publication_lease_token
.map(|token| Bytes::copy_from_slice(token.as_bytes()))
.unwrap_or_default();
let rename_deadline = tokio::time::Instant::now() + get_max_timeout_duration();
let rename_admission = self.acquire_rename_admission_until(1, rename_deadline).await?;
let mut rename_admission_guard = RenameBatchCallGuard {
admission: rename_admission,
deadline: rename_deadline,
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
};
let rpc_kind = if multipart_rename {
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_MULTIPART
} else if pool_meta_cas {
@@ -3673,7 +3738,11 @@ impl RemoteDisk {
},
get_max_timeout_duration(),
)
.await
.await;
RenameDataObservation {
result,
rejected_before_publication: dispatch_expired,
}
}
/// Delete a path while binding the target-side operation to a scanner
@@ -6484,6 +6553,66 @@ mod tests {
}
}
#[tokio::test(start_paused = true)]
async fn rename_dispatch_budget_only_starts_after_the_quorum_signal() {
use futures::FutureExt as _;
let (tx, rx) = tokio::sync::watch::channel(None);
let mut dial = std::pin::pin!(before_rename_dispatch(Some(rx), std::future::pending::<()>()));
assert!(dial.as_mut().now_or_never().is_none());
time::advance(Duration::from_secs(2)).await;
assert!(dial.as_mut().now_or_never().is_none(), "quorum has not been reached");
tx.send_replace(Some(time::Instant::now() + Duration::from_secs(1)));
assert!(dial.as_mut().now_or_never().is_none(), "quorum grants a connection grace period");
time::advance(Duration::from_secs(1)).await;
assert_eq!(dial.await, None, "only the unresolved connection expires");
assert_eq!(before_rename_dispatch(Some(tx.subscribe()), std::future::ready(8)).await, Some(8));
}
#[tokio::test]
async fn rename_dispatch_budget_does_not_cancel_a_dispatched_rpc() {
use futures::FutureExt as _;
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind rename peer");
peer.peer.serve_rename_data();
let gate = Arc::new(TestFormatReadGate::default());
*peer.peer.rename_data_reply_gate.lock().expect("rename reply gate") = Some(gate.clone());
let disk = remote_disk_for_addr(&peer.addr).await;
let (tx, rx) = tokio::sync::watch::channel(None);
let file_info = sample_rename_data_file_info();
let mut rename = std::pin::pin!(disk.rename_data_observed(
"tmp",
"source",
&file_info,
"bucket",
"object",
RenameDataGuards {
dispatch_deadline: Some(rx),
..Default::default()
},
));
time::timeout(Duration::from_secs(5), async {
tokio::select! {
() = gate.entered.notified() => {},
_ = rename.as_mut() => panic!("rename completed before the peer received it"),
}
})
.await
.expect("peer should receive the authenticated mutation");
tx.send_replace(Some(time::Instant::now()));
assert!(rename.as_mut().now_or_never().is_none(), "the dispatched mutation must continue to drain");
gate.release.cancel();
let observed = rename.await;
assert!(!observed.rejected_before_publication());
observed.result.expect("remote rename should return success");
peer.stop().await;
}
#[tokio::test]
async fn multipart_rename_old_peer_rejects_without_legacy_fallback() {
runtime_sources::ensure_test_rpc_secret();
@@ -6540,7 +6669,7 @@ mod tests {
for (object, calls) in [("object", 1), ("other-object", 2)] {
let result = remote
.start_rename_data_batch("tmp", "source", "bucket", object, rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", object, rename_batch_client_items(&file_infos), None)
.await;
assert!(matches!(result, Err(RenameBatchStartError::UnsupportedBeforeStream)));
assert_eq!(
@@ -6577,7 +6706,7 @@ mod tests {
for width in [2_usize, 4] {
let file_infos = (0..width).map(|_| sample_rename_data_file_info()).collect::<Vec<_>>();
let mut stream = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos), None)
.await
.unwrap_or_else(|_| panic!("{width}-item real batch must start"));
assert_eq!(
@@ -6615,6 +6744,62 @@ mod tests {
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_dispatch_budget_releases_waiting_batch_admission_without_dispatch() {
use std::task::Poll;
runtime_sources::ensure_test_rpc_secret();
let peer = TestGrpcPeer::spawn(Bytes::new(), Bytes::new())
.await
.expect("bind rename batch peer");
peer.peer.serve_rename_batch_results(usize::MAX);
temp_env::async_with_vars([(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, Some("true"))], async {
let remote = remote_disk_for_addr(&peer.addr).await;
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
let capacity = rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT;
let held = Arc::clone(&gate)
.acquire_many_owned(u32::try_from(capacity - 1).expect("valid permit count"))
.await
.expect("reserve all but one permit");
let file_infos = [sample_rename_data_file_info(), sample_rename_data_file_info()];
let (tx, rx) = tokio::sync::watch::channel(None);
let mut rename = std::pin::pin!(remote.start_rename_data_batch(
"tmp",
"source",
"bucket",
"object",
rename_batch_client_items(&file_infos),
Some(rx),
));
time::timeout(
Duration::from_secs(5),
std::future::poll_fn(|cx| {
assert!(rename.as_mut().poll(cx).is_pending(), "batch must wait for two permits");
if gate.available_permits() == 0 {
Poll::Ready(())
} else {
Poll::Pending
}
}),
)
.await
.expect("the queued batch must reserve the spare permit");
tx.send_replace(Some(time::Instant::now()));
let result = time::timeout(Duration::from_secs(5), rename)
.await
.expect("elapsed dispatch budget must release the batch waiter");
assert!(matches!(result, Err(RenameBatchStartError::NotDispatched(DiskError::DiskNotFound))));
assert_eq!(peer.peer.rename_batch_calls(), 0, "expiry must not send a mutation to the peer");
assert_eq!(gate.available_permits(), 1, "the cancelled acquire must release its reservation");
drop(held);
assert_eq!(gate.available_permits(), capacity);
})
.await;
peer.stop().await;
}
#[tokio::test]
#[serial]
async fn rename_batch_real_partial_eof_quarantines_only_missing_items() {
@@ -6633,7 +6818,7 @@ mod tests {
let gate = Arc::clone(remote.rename_admission.as_ref().expect("rename admission enabled"));
let file_infos = (0..4).map(|_| sample_rename_data_file_info()).collect::<Vec<_>>();
let mut stream = remote
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos))
.start_rename_data_batch("tmp", "source", "bucket", "object", rename_batch_client_items(&file_infos), None)
.await
.unwrap_or_else(|_| panic!("real partial batch must start"));
@@ -7200,7 +7385,7 @@ mod tests {
fn msgpack_eligible_requests_bind_one_policy_and_bounded_local_retry() {
let source = rustfs_protos::compat_manifest::production_source(include_str!("remote_disk.rs"), "remote_disk.rs");
for function in [
"rename_data_borrowed_with_fence",
"rename_data_observed",
"write_metadata",
"update_metadata",
"read_version",
@@ -7550,6 +7735,7 @@ mod tests {
rename_batch_result_limit: Arc<StdMutex<Option<usize>>>,
serve_rename_data: Arc<AtomicBool>,
rename_data_disks: Arc<StdMutex<Vec<String>>>,
rename_data_reply_gate: Arc<StdMutex<Option<Arc<TestFormatReadGate>>>>,
object_read_all_disks: Arc<StdMutex<Vec<String>>>,
format_data: Bytes,
read_all_data: Bytes,
@@ -7584,6 +7770,7 @@ mod tests {
rename_batch_result_limit: Arc::default(),
serve_rename_data: Arc::default(),
rename_data_disks: Arc::default(),
rename_data_reply_gate: Arc::default(),
object_read_all_disks: Arc::default(),
format_data,
read_all_data,
@@ -7711,6 +7898,11 @@ mod tests {
.lock()
.expect("rename data disks lock poisoned")
.push(request.disk);
let gate = peer.rename_data_reply_gate.lock().expect("rename reply gate lock").take();
if let Some(gate) = gate {
gate.entered.notify_one();
gate.release.cancelled().await;
}
let payload = serde_json::to_string(&RenameDataResp {
sign: Some(vec![1]),
..Default::default()
+3 -3
View File
@@ -645,7 +645,7 @@ impl LocalDiskWrapper {
get_max_timeout_duration()
};
let observed = run_owned_mutation(external_guard, move || async move {
let mut preflight_rejection = None;
let mut rejected_before_publication = false;
let result = operation
.track_disk_health_mutation(
"rename_data",
@@ -661,7 +661,7 @@ impl LocalDiskWrapper {
namespace_owner,
))
.await;
preflight_rejection = observed.preflight_rejection;
rejected_before_publication = observed.rejected_before_publication();
observed.result
},
timeout_duration,
@@ -670,7 +670,7 @@ impl LocalDiskWrapper {
// Health tracking must observe the real disk error, not an Ok tuple.
Ok(super::RenameDataObservation {
result,
preflight_rejection,
rejected_before_publication,
})
})
.await;
-1
View File
@@ -12,7 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
pub(in crate::disk) use self::commit::LocalRenamePreflightRejection;
#[cfg(test)]
#[path = "local/read_path_tests.rs"]
mod read_path_tests;
+2 -2
View File
@@ -540,7 +540,7 @@ async fn prepare_rename_commit_and_destination_metadata(
/// Proof produced only when the local rename returns at an existing access
/// preflight, before metadata, backups, or object data can be published.
#[derive(Debug)]
pub(in crate::disk) struct LocalRenamePreflightRejection(());
struct LocalRenamePreflightRejection(());
#[derive(Default)]
pub(super) struct RenameDataState {
@@ -2939,7 +2939,7 @@ impl LocalDisk {
.await;
super::super::RenameDataObservation {
result,
preflight_rejection: state.preflight_rejection,
rejected_before_publication: state.preflight_rejection.is_some(),
}
}
}
+13 -16
View File
@@ -130,24 +130,28 @@ pub(crate) struct RenameDataGuards {
pub(crate) scanner_publication_lease_token: Option<Uuid>,
pub(crate) external_guard: Option<Arc<dyn Send + Sync>>,
pub(crate) namespace_owner: Option<Arc<dyn Send + Sync>>,
pub(crate) dispatch_deadline: Option<RenameDispatchDeadline>,
}
/// Local preflight evidence stays outside DiskAPI and the RPC response format.
/// The fanout publishes this deadline once enough disks have committed.
pub(crate) type RenameDispatchDeadline = tokio::sync::watch::Receiver<Option<tokio::time::Instant>>;
/// Pre-dispatch evidence stays outside DiskAPI and the RPC response format.
pub(crate) struct RenameDataObservation {
pub(crate) result: Result<RenameDataResp>,
preflight_rejection: Option<local::LocalRenamePreflightRejection>,
pub(crate) rejected_before_publication: bool,
}
impl RenameDataObservation {
fn unknown(result: Result<RenameDataResp>) -> Self {
pub(crate) fn unknown(result: Result<RenameDataResp>) -> Self {
Self {
result,
preflight_rejection: None,
rejected_before_publication: false,
}
}
pub(crate) fn rejected_before_publication(&self) -> bool {
self.result.is_err() && self.preflight_rejection.is_some()
self.result.is_err() && self.rejected_before_publication
}
}
@@ -1388,18 +1392,11 @@ impl Disk {
.rename_data_observed_with_guards(src_volume, src_path, fi, dst_volume, dst_path, guards)
.await
}
Disk::Remote(remote_disk) => RenameDataObservation::unknown(
Disk::Remote(remote_disk) => {
remote_disk
.rename_data_borrowed_with_fence(
src_volume,
src_path,
fi,
dst_volume,
dst_path,
guards.scanner_publication_lease_token,
)
.await,
),
.rename_data_observed(src_volume, src_path, fi, dst_volume, dst_path, guards)
.await
}
}
}
+145 -65
View File
@@ -149,7 +149,7 @@ use std::{
time::{Duration, Instant},
};
use tokio::io::{AsyncRead, ReadBuf};
use tokio::sync::{RwLock, mpsc, oneshot};
use tokio::sync::{RwLock, mpsc, oneshot, watch};
use tokio::task::JoinSet;
pub(in crate::set_disk) const EVENT_SET_DISK_READ: &str = "set_disk_read";
@@ -3279,6 +3279,7 @@ fn rename_tail_cleanup_queue() -> &'static RenameTailCleanupQueue {
}
const EVENT_SET_DISK_RENAME_ROLLBACK: &str = "set_disk_rename_rollback";
const PUT_RENAME_POST_QUORUM_DISPATCH_GRACE: Duration = Duration::from_secs(1);
#[derive(Clone, Copy)]
enum RenameDispatchState {
@@ -3305,12 +3306,22 @@ struct RenameBatchGroup {
slots: Vec<usize>,
}
#[derive(Clone)]
struct RenameSlotPaths {
src_bucket: Arc<String>,
src_object: Arc<String>,
dst_bucket: Arc<String>,
dst_object: Arc<String>,
src_bucket: String,
src_object: String,
dst_bucket: String,
dst_object: String,
}
impl RenameSlotPaths {
fn new(src_bucket: &str, src_object: &str, dst_bucket: &str, dst_object: &str) -> Self {
Self {
src_bucket: src_bucket.to_owned(),
src_object: src_object.to_owned(),
dst_bucket: dst_bucket.to_owned(),
dst_object: dst_object.to_owned(),
}
}
}
struct RenameSlotContext {
@@ -3320,20 +3331,22 @@ struct RenameSlotContext {
scanner_token: Option<Uuid>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
publication_scope: Option<crate::object_api::ScannerPublicationCommitScope>,
paths: RenameSlotPaths,
paths: Arc<RenameSlotPaths>,
successful_completion_rank: Option<Arc<AtomicUsize>>,
write_quorum: usize,
dispatch_deadline: Option<disk::RenameDispatchDeadline>,
}
struct RenameOutcomeProducerArgs {
disks: Arc<Vec<Option<DiskStore>>>,
file_infos: Arc<Vec<FileInfo>>,
fence_tokens: Arc<Vec<Option<Uuid>>>,
paths: RenameSlotPaths,
paths: Arc<RenameSlotPaths>,
namespace_owner: Option<Arc<dyn Send + Sync>>,
publication_scope: Option<crate::object_api::ScannerPublicationCommitScope>,
write_quorum: usize,
allow_batch: bool,
dispatch_deadline: Option<disk::RenameDispatchDeadline>,
}
struct RenameOutcomeProducers {
@@ -3827,6 +3840,7 @@ pub(in crate::set_disk) struct RenameDataFenceOptions<'a> {
rollback_receipt: Option<RenameRollbackReceipt>,
multipart_proof_authority: Option<crate::disk::multipart_source::ProofVerificationContext>,
multipart_commit_owner: Option<Arc<MultipartLogicalGuards>>,
bound_dispatch_after_quorum: bool,
}
impl<'a> RenameDataFenceOptions<'a> {
@@ -3842,9 +3856,15 @@ impl<'a> RenameDataFenceOptions<'a> {
rollback_receipt: None,
multipart_proof_authority: None,
multipart_commit_owner: None,
bound_dispatch_after_quorum: false,
}
}
pub(in crate::set_disk) fn with_quorum_bounded_dispatch(mut self, enabled: bool) -> Self {
self.bound_dispatch_after_quorum = enabled;
self
}
pub(in crate::set_disk) fn with_multipart_commit_owner(mut self, owner: Arc<MultipartLogicalGuards>) -> Self {
self.multipart_commit_owner = Some(owner);
self
@@ -4426,6 +4446,7 @@ impl SetDisks {
disk::RenameDataGuards {
scanner_publication_lease_token: context.scanner_token,
namespace_owner: context.namespace_owner.clone(),
dispatch_deadline: context.dispatch_deadline.clone(),
..Default::default()
},
)
@@ -4602,6 +4623,7 @@ impl SetDisks {
publication_scope,
write_quorum,
allow_batch,
dispatch_deadline,
} = args;
debug_assert!(!allow_batch || publication_scope.is_none());
let disk_count = disks.len();
@@ -4626,6 +4648,10 @@ impl SetDisks {
continue;
}
let outcome_tx = outcome_tx.clone();
let dispatch_deadline = dispatch_deadline
.as_ref()
.filter(|_| disk.as_ref().is_some_and(|disk| !disk.is_local()))
.cloned();
let context = RenameSlotContext {
slot,
disk,
@@ -4636,6 +4662,7 @@ impl SetDisks {
paths: paths.clone(),
successful_completion_rank: successful_completion_rank.clone(),
write_quorum,
dispatch_deadline,
};
let resource_unit = resource_unit.clone();
let producer = crate::disk::with_optional_resource_unit(resource_unit, async move {
@@ -4653,6 +4680,7 @@ impl SetDisks {
let group_disks = disks.clone();
let group_tokens = fence_tokens.clone();
let resource_unit = resource_unit.clone();
let dispatch_deadline = dispatch_deadline.clone();
let producer = crate::disk::with_optional_resource_unit(resource_unit, async move {
let prepared = join_all(group.slots.into_iter().map(|slot| {
let context = RenameSlotContext {
@@ -4665,6 +4693,7 @@ impl SetDisks {
paths: paths.clone(),
successful_completion_rank: successful_completion_rank.clone(),
write_quorum,
dispatch_deadline: dispatch_deadline.clone(),
};
async move { (slot, Self::prepare_and_admit_rename_slot(context).await) }
}))
@@ -4736,6 +4765,7 @@ impl SetDisks {
&paths.dst_bucket,
&paths.dst_object,
items,
dispatch_deadline,
)
.await
}
@@ -4844,6 +4874,7 @@ impl SetDisks {
rollback_receipt,
multipart_proof_authority: _,
multipart_commit_owner: _,
bound_dispatch_after_quorum: _,
} = fence_options;
if let Some(file_info) = disks
.iter()
@@ -4864,19 +4895,13 @@ impl SetDisks {
Arc::new(Self::scanner_publication_lease_tokens_for_disks(disks, scanner_publication_lease_tokens)?);
Self::record_rename_batch_candidates(disks, &file_infos, &fanout_fence_tokens, src_bucket, dst_bucket, dst_object);
let coordinator_disks = fanout_disks.clone();
let src_bucket = Arc::new(src_bucket.to_string());
let src_object = Arc::new(src_object.to_string());
let dst_bucket = Arc::new(dst_bucket.to_string());
let dst_object = Arc::new(dst_object.to_string());
let paths = Arc::new(RenameSlotPaths::new(src_bucket, src_object, dst_bucket, dst_object));
let (commit_tx, commit_rx) = oneshot::channel();
let coordinator_failure_receipt = rollback_receipt.clone();
let early_ack_spawn_to_quorum_wait_started = rustfs_io_metrics::put_stage_timer();
let tail_drain = tokio::spawn(crate::disk::with_detached_disk_io_context({
let fanout_src_bucket = src_bucket.clone();
let fanout_src_object = src_object.clone();
let fanout_dst_bucket = dst_bucket.clone();
let fanout_dst_object = dst_object.clone();
let paths = paths.clone();
async move {
let allow_batch = scanner_publication_commit_scope.is_none();
let RenameOutcomeProducers {
@@ -4886,16 +4911,12 @@ impl SetDisks {
disks: fanout_disks.clone(),
file_infos: file_infos.clone(),
fence_tokens: fanout_fence_tokens.clone(),
paths: RenameSlotPaths {
src_bucket: fanout_src_bucket.clone(),
src_object: fanout_src_object.clone(),
dst_bucket: fanout_dst_bucket.clone(),
dst_object: fanout_dst_object.clone(),
},
paths: paths.clone(),
namespace_owner: namespace_commit_guard.clone().map(|owner| owner as Arc<dyn Send + Sync>),
publication_scope: scanner_publication_commit_scope,
write_quorum,
allow_batch,
dispatch_deadline: None,
});
let mut commit_tx = Some(commit_tx);
@@ -4980,7 +5001,7 @@ impl SetDisks {
}
if let Some(commit_tx) = commit_tx.take() {
#[cfg(test)]
rename_fanout_barrier::wait_for_armed_rename_before_early_ack(&fanout_dst_object).await;
rename_fanout_barrier::wait_for_armed_rename_before_early_ack(&paths.dst_object).await;
let _ = commit_tx.send(snapshot_commit);
}
sent_commit = true;
@@ -4998,7 +5019,7 @@ impl SetDisks {
);
#[cfg(test)]
rollback_fault_injection::after_fanout(&fanout_dst_object);
rollback_fault_injection::after_fanout(&paths.dst_object);
if rustfs_io_metrics::put_stage_metrics_enabled() {
let fanout_success = errs.iter().filter(|err| err.is_none()).count();
let fanout_error = errs.len().saturating_sub(fanout_success + fanout_panic);
@@ -5021,7 +5042,7 @@ impl SetDisks {
&errs,
&dispatch_states,
&data_dirs,
(&fanout_dst_bucket, &fanout_dst_object),
(&paths.dst_bucket, &paths.dst_object),
RenameRollbackOwnership {
receipt: rollback_receipt,
namespace_commit_guard,
@@ -5068,11 +5089,10 @@ impl SetDisks {
let Some(disk) = disk.clone() else {
continue;
};
let dst_bucket = fanout_dst_bucket.clone();
let dst_object = fanout_dst_object.clone();
let paths = paths.clone();
backup_reclaims.push(tokio::spawn(async move {
let backup_path = format!("{dst_object}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
disk.delete(&dst_bucket, &backup_path, DeleteOptions::default()).await
let backup_path = format!("{}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}", paths.dst_object);
disk.delete(&paths.dst_bucket, &backup_path, DeleteOptions::default()).await
}));
}
for result in join_all(backup_reclaims).await {
@@ -5081,16 +5101,16 @@ impl SetDisks {
Ok(Err(DiskError::FileNotFound | DiskError::VolumeNotFound)) => {}
Ok(Err(err)) => {
warn!(
dst_bucket = %fanout_dst_bucket,
dst_object = %fanout_dst_object,
dst_bucket = %paths.dst_bucket,
dst_object = %paths.dst_object,
error = %err,
"rollback backup reclamation failed after committed rename"
);
}
Err(join_err) => {
warn!(
dst_bucket = %fanout_dst_bucket,
dst_object = %fanout_dst_object,
dst_bucket = %paths.dst_bucket,
dst_object = %paths.dst_object,
error = %join_err,
"rollback backup reclamation task failed after committed rename"
);
@@ -5136,7 +5156,7 @@ impl SetDisks {
let commit = match commit_rx.await {
Ok(commit) => commit,
Err(_) => {
record_indeterminate_rename(disks, (&dst_bucket, &dst_object), coordinator_failure_receipt).await;
record_indeterminate_rename(disks, (dst_bucket, dst_object), coordinator_failure_receipt).await;
return Err(DiskError::Unexpected);
}
};
@@ -5216,6 +5236,7 @@ impl SetDisks {
rollback_receipt,
multipart_proof_authority,
multipart_commit_owner,
bound_dispatch_after_quorum,
} = fence_options;
if let Some(file_info) = disks
.iter()
@@ -5239,28 +5260,15 @@ impl SetDisks {
};
let mut errs = vec![Some(DiskError::Unexpected); disks.len()];
let src_bucket = Arc::new(src_bucket.to_string());
let src_object = Arc::new(src_object.to_string());
let dst_bucket = Arc::new(dst_bucket.to_string());
let dst_object = Arc::new(dst_object.to_string());
let paths = Arc::new(RenameSlotPaths::new(src_bucket, src_object, dst_bucket, dst_object));
let disk_count = disks.len();
let fanout_disks = Arc::new(disks.to_vec());
let fanout_file_infos = Arc::new(file_infos);
let fanout_fence_tokens =
Arc::new(Self::scanner_publication_lease_tokens_for_disks(disks, scanner_publication_lease_tokens)?);
Self::record_rename_batch_candidates(
disks,
&fanout_file_infos,
&fanout_fence_tokens,
src_bucket.as_str(),
dst_bucket.as_str(),
dst_object.as_str(),
);
let fanout_src_bucket = src_bucket.clone();
let fanout_src_object = src_object.clone();
let fanout_dst_bucket = dst_bucket.clone();
let fanout_dst_object = dst_object.clone();
Self::record_rename_batch_candidates(disks, &fanout_file_infos, &fanout_fence_tokens, src_bucket, dst_bucket, dst_object);
let fanout_paths = paths.clone();
let fanout_publication_scope = scanner_publication_commit_scope.clone();
let logical_guards = multipart_commit_owner;
let multipart_commit_owner = logical_guards
@@ -5278,13 +5286,16 @@ impl SetDisks {
// fan-out owner, even if the caller future is cancelled.
let _fanout_publication_scope = fanout_publication_scope;
let _namespace_commit_guard = fanout_namespace_commit_guard.clone();
let paths = RenameSlotPaths {
src_bucket: fanout_src_bucket,
src_object: fanout_src_object,
dst_bucket: fanout_dst_bucket,
dst_object: fanout_dst_object.clone(),
};
let allow_batch = !protected_multipart && scanner_publication_commit_scope.is_none();
let (dispatch_deadline_tx, dispatch_deadline) = if bound_dispatch_after_quorum
&& fanout_disks.iter().flatten().count() > write_quorum
&& fanout_disks.iter().flatten().any(|disk| !disk.is_local())
{
let (tx, rx) = watch::channel(None);
(Some(tx), Some(rx))
} else {
(None, None)
};
let RenameOutcomeProducers {
outcomes: mut outcome_rx,
mut tasks,
@@ -5292,19 +5303,29 @@ impl SetDisks {
disks: fanout_disks,
file_infos: fanout_file_infos.clone(),
fence_tokens: fanout_fence_tokens,
paths,
paths: fanout_paths.clone(),
namespace_owner: fanout_namespace_owner,
publication_scope: scanner_publication_commit_scope,
write_quorum,
allow_batch,
dispatch_deadline,
});
let mut results = Vec::with_capacity(disk_count);
let mut successful = 0;
while let Some(outcome) = outcome_rx.recv().await {
if let Some(tx) = dispatch_deadline_tx.as_ref()
&& matches!(&outcome.completion, Ok(Ok(_)))
{
successful += 1;
if successful == write_quorum {
tx.send_replace(Some(tokio::time::Instant::now() + PUT_RENAME_POST_QUORUM_DISPATCH_GRACE));
}
}
results.push(outcome);
}
while tasks.join_next().await.is_some() {}
#[cfg(test)]
rollback_fault_injection::after_fanout(&fanout_dst_object);
rollback_fault_injection::after_fanout(&fanout_paths.dst_object);
(results, fanout_file_infos)
};
let fanout_future = crate::disk::with_detached_disk_io_context(fanout_future);
@@ -5338,7 +5359,7 @@ impl SetDisks {
let (results, file_infos) = match fanout_result {
Ok(result) => result,
Err(_) => {
record_indeterminate_rename(disks, (&dst_bucket, &dst_object), rollback_receipt).await;
record_indeterminate_rename(disks, (dst_bucket, dst_object), rollback_receipt).await;
return Err(DiskError::Unexpected);
}
};
@@ -5471,7 +5492,7 @@ impl SetDisks {
// Destination-only Undo cannot restore a consumed MPU head.
// Only this failed owner can spend the original native caps.
owner
.failed_owned(disks, &file_infos, &src_object, (&dst_bucket, &dst_object), namespace_commit_guard)
.failed_owned(disks, &file_infos, src_object, (dst_bucket, dst_object), namespace_commit_guard)
.await;
} else {
rollback_failed_rename(
@@ -5480,7 +5501,7 @@ impl SetDisks {
&errs,
&dispatch_states,
&data_dirs,
(&dst_bucket, &dst_object),
(dst_bucket, dst_object),
RenameRollbackOwnership {
receipt: rollback_receipt,
namespace_commit_guard,
@@ -5526,11 +5547,10 @@ impl SetDisks {
let Some(disk) = disk.clone() else {
continue;
};
let dst_bucket = dst_bucket.clone();
let dst_object = dst_object.clone();
let paths = paths.clone();
backup_reclaims.push(tokio::spawn(async move {
let backup_path = format!("{dst_object}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}");
disk.delete(&dst_bucket, &backup_path, DeleteOptions::default()).await
let backup_path = format!("{}/{rollback_dir}/{STORAGE_FORMAT_FILE_BACKUP}", paths.dst_object);
disk.delete(&paths.dst_bucket, &backup_path, DeleteOptions::default()).await
}));
}
for result in join_all(backup_reclaims).await {
@@ -12818,6 +12838,66 @@ mod tests {
}
}
#[tokio::test]
#[serial_test::serial(capacity_dirty_scope)]
async fn rename_data_bounds_cold_connect_after_durable_quorum() {
const DISKS: usize = 4;
let bucket = "rename-connect-tail-bucket";
let object = "rename-connect-tail-object";
let (dirs, mut disks) = call_counter_local_disks(bucket, DISKS).await;
prepare_rename_source_dirs(&dirs, &disks, "source").await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind cold peer");
// The TCP socket remains open, but there is no TLS server to finish the dial.
let endpoint = crate::disk::endpoint::Endpoint {
url: url::Url::parse(&format!("https://{}/data/rustfs0", listener.local_addr().expect("cold peer address")))
.expect("cold peer URL"),
is_local: false,
pool_idx: 0,
set_idx: 0,
disk_idx: 3,
};
disks[DISKS - 1] = Some(
crate::disk::new_disk(
&endpoint,
&crate::disk::DiskOption {
cleanup: false,
health_check: false,
},
)
.await
.expect("construct remote disk"),
);
let file_infos = rename_commit_fileinfos(object, DISKS, "bounded-connect-etag");
let commit = temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CONNECT_TIMEOUT_SECS, Some("15"))], async {
tokio::time::timeout(
Duration::from_secs(5),
SetDisks::rename_data_owned_with_fence(
&disks,
(RUSTFS_META_TMP_BUCKET, "source"),
file_infos,
(bucket, object),
false,
RenameDataFenceOptions::new(3, None).with_quorum_bounded_dispatch(true),
),
)
.await
.expect("durable quorum must finish before the silent peer's dial deadline")
.expect("three durable renames must satisfy write quorum")
})
.await;
assert_eq!(commit.convergence, RenameConvergence::PartialCommit);
assert!(commit.needs_immediate_heal());
assert!(commit.tail_drain.is_none());
for dir in dirs.iter().take(3) {
let reopened = reopen_local_disk(dir).await;
let stored = reopened
.read_version("", bucket, object, "", &ReadOptions::default())
.await
.expect("quorum metadata survives reopening");
assert_eq!(stored.metadata.get("etag").map(String::as_str), Some("bounded-connect-etag"));
}
}
#[tokio::test]
#[serial_test::serial(capacity_dirty_scope)]
async fn rename_data_without_tail_handoff_waits_after_write_quorum() {
+98 -26
View File
@@ -25,7 +25,8 @@ use super::super::{
reduce_write_quorum_errs,
};
use crate::api::bucket::metadata_sys;
use crate::disk::DiskAPI;
use crate::disk::{DiskAPI, DiskStore, VolumeInfo};
use futures::{Stream, StreamExt, stream::FuturesUnordered};
#[derive(Clone, Copy)]
pub(crate) enum BucketInfoQuorum {
@@ -34,6 +35,39 @@ pub(crate) enum BucketInfoQuorum {
HealCandidates,
}
async fn stat_bucket_volume(disk: Option<DiskStore>, bucket: &str) -> crate::disk::error::Result<VolumeInfo> {
match disk {
Some(disk) => disk.stat_volume(bucket).await,
None => Err(DiskError::DiskNotFound),
}
}
async fn collect_bucket_presence(
mut probes: impl Stream<Item = crate::disk::error::Result<()>> + Unpin,
disk_count: usize,
) -> Result<()> {
let required = disk_count.div_ceil(2).max(1);
let mut successes = 0;
let mut errors = Vec::new();
while let Some(result) = probes.next().await {
match result {
Ok(()) => {
successes += 1;
// The reducer favors success on ties, so the remaining disks
// cannot change this decision. Presence doesn't use timestamps.
if successes == required {
return Ok(());
}
}
Err(err) => errors.push(Some(err)),
}
}
errors.resize_with(errors.len() + successes, || None);
Err(reduce_read_quorum_errs(&errors, BUCKET_OP_IGNORED_ERRS, required)
.unwrap_or(DiskError::ErasureReadQuorum)
.into())
}
impl SetDisks {
/// Require proof from every configured disk before retiring a bucket
/// generation whose visible volume was removed outside the storage API.
@@ -43,12 +77,9 @@ impl SetDisks {
return Err(Error::ErasureReadQuorum);
}
let futures = disks.into_iter().map(|disk| async move {
match disk {
Some(disk) => disk.stat_volume(bucket).await.map(|_| ()),
None => Err(DiskError::DiskNotFound),
}
});
let futures = disks
.into_iter()
.map(|disk| async move { stat_bucket_volume(disk, bucket).await.map(|_| ()) });
let results = join_all(futures).await;
let mut volume_present = false;
let mut first_unknown = None;
@@ -70,31 +101,32 @@ impl SetDisks {
Ok(())
}
pub(crate) async fn check_bucket_presence_at_read_quorum(&self, bucket: &str) -> Result<()> {
let disks = self.disk_inventory().await;
let disk_count = disks.len();
let probes = disks
.into_iter()
.map(|disk| async move { stat_bucket_volume(disk, bucket).await.map(|_| ()) })
.collect::<FuturesUnordered<_>>();
collect_bucket_presence(probes, disk_count).await
}
pub(crate) async fn stat_bucket_with_quorum(&self, bucket: &str, quorum: BucketInfoQuorum) -> Result<BucketInfo> {
let disks = self.disk_inventory().await;
let disk_count = disks.len();
let mut futures = Vec::with_capacity(disk_count);
for disk in disks {
let bucket = bucket.to_string();
futures.push(async move {
match disk {
Some(disk) => disk.stat_volume(&bucket).await,
None => Err(DiskError::DiskNotFound),
}
});
}
let results = join_all(futures).await;
let mut infos = Vec::with_capacity(results.len());
let probes = disks.into_iter().map(|disk| stat_bucket_volume(disk, bucket));
let results = join_all(probes).await;
let mut first_info = None;
let mut errs = Vec::with_capacity(results.len());
for result in results {
match result {
Ok(info) => {
infos.push(Some(info));
if first_info.is_none() {
first_info = Some(info);
}
errs.push(None);
}
Err(err) => {
infos.push(None);
errs.push(Some(err));
}
}
@@ -113,10 +145,7 @@ impl SetDisks {
return Err(err.into());
}
infos
.into_iter()
.flatten()
.next()
first_info
.map(|info| BucketInfo {
name: info.name,
created: info.created,
@@ -341,3 +370,46 @@ impl BucketOperations for SetDisks {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::{FutureExt, stream};
#[test]
fn bucket_presence_returns_with_a_silent_peer() {
let probes = stream::iter([Err(DiskError::VolumeNotFound), Ok(()), Ok(())]).chain(stream::pending());
collect_bucket_presence(probes, 4)
.now_or_never()
.expect("read quorum must return before the fourth probe replies")
.expect("two successes win even if both other disks report a missing volume");
}
#[tokio::test]
async fn bucket_presence_preserves_absence_and_read_quorum_errors() {
let probes = stream::iter([Ok(()), Err(DiskError::VolumeNotFound), Err(DiskError::DiskNotFound)]);
assert!(
collect_bucket_presence(probes.chain(stream::pending()), 4)
.now_or_never()
.is_none(),
"the last disk can still prove either presence or absence"
);
let missing = stream::iter([
Ok(()),
Err(DiskError::VolumeNotFound),
Err(DiskError::DiskNotFound),
Err(DiskError::VolumeNotFound),
]);
assert!(matches!(collect_bucket_presence(missing, 4).await, Err(Error::VolumeNotFound)));
let unavailable = stream::iter([
Ok(()),
Err(DiskError::VolumeNotFound),
Err(DiskError::DiskNotFound),
Err(DiskError::DiskNotFound),
]);
assert!(matches!(collect_bucket_presence(unavailable, 4).await, Err(Error::ErasureReadQuorum)));
}
}
@@ -5926,6 +5926,14 @@ impl SetDisks {
|| commit_decommission_object_lock_guard.is_some()
|| commit_publication_guard.is_some();
let commit_write_completion = opts.write_completion;
let bound_rename_dispatch = commit_write_completion == crate::object_api::WriteCompletion::TailDrained
&& commit_object_lock_guard.is_some()
&& !is_meta_bucketname(bucket)
&& !opts.data_movement
&& !opts.replication_request
&& !quota_mutation_fence
&& commit_scanner_publication_scope.is_none()
&& scanner_publication_lease_tokens.is_none();
let commit_allows_early_ack = write_context.allows_early_ack(commit_write_completion)
&& !(opts.data_movement && opts.has_decommission_capacity_reservation())
&& commit_owns_namespace_guard
@@ -6253,6 +6261,7 @@ impl SetDisks {
commit_scanner_publication_lease_tokens.as_ref(),
)
.with_publication_scope(commit_scanner_publication_scope.clone())
.with_quorum_bounded_dispatch(bound_rename_dispatch)
.with_rollback_receipt(commit_rollback_receipt.clone())
.with_namespace_commit_guard(
(!is_meta_bucketname(&commit_bucket))
+15 -33
View File
@@ -24,7 +24,7 @@ use crate::disk::{
};
use crate::error::is_err_bucket_not_found;
use crate::runtime::sources as runtime_sources;
use crate::set_disk::{BucketInfoQuorum, get_lock_acquire_timeout};
use crate::set_disk::{BucketInfoQuorum, SetDisks, get_lock_acquire_timeout};
use crate::storage_api_contracts::admin::DiskSetSelector;
use crate::storage_api_contracts::bucket::{BUCKET_LIFECYCLE_LOCK_OBJECT, SRBucketDeleteOp};
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
@@ -1702,65 +1702,47 @@ impl ECStore {
#[instrument(skip(self))]
pub(crate) async fn get_bucket_info_from_sets(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
self.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Write)
self.probe_bucket_sets(|set| async move { set.get_bucket_info(bucket, opts).await })
.await
}
pub(crate) async fn get_bucket_info_from_sets_at_read_quorum(
&self,
bucket: &str,
opts: &BucketOptions,
) -> Result<BucketInfo> {
self.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Read)
pub(crate) async fn check_bucket_presence_at_read_quorum(&self, bucket: &str) -> Result<()> {
self.probe_bucket_sets(|set| async move { set.check_bucket_presence_at_read_quorum(bucket).await })
.await
}
async fn get_bucket_info_from_sets_with_quorum(
&self,
bucket: &str,
opts: &BucketOptions,
quorum: BucketInfoQuorum,
) -> Result<BucketInfo> {
async fn probe_bucket_sets<T, F: Future<Output = Result<T>>>(&self, probe: impl Fn(Arc<SetDisks>) -> F) -> Result<T> {
// One host may participate in several pools after expansion. Resolve the
// namespace against each erasure set so disks from different pools can
// never be combined into one bucket quorum.
// Bucket validation is request-path IO. Keep the previous peer fanout's
// latency shape by probing every set concurrently; scanner listings use
// a separate bounded path below because they run continuously.
let mut scoped_results = futures::future::join_all(self.bucket_sets().map(|(pool_index, set_index, set)| async move {
let result = match quorum {
BucketInfoQuorum::Read => set.stat_bucket_with_quorum(bucket, quorum).await,
BucketInfoQuorum::Write | BucketInfoQuorum::HealCandidates => set.get_bucket_info(bucket, opts).await,
};
(pool_index, set_index, result)
let mut scoped_results = futures::future::join_all(self.bucket_sets().map(|(pool_index, set_index, set)| {
let result = probe(set);
async move { (pool_index, set_index, result.await) }
}))
.await;
scoped_results.sort_unstable_by_key(|(pool_index, set_index, _)| (*pool_index, *set_index));
let mut first_info = None;
let mut first_error = None;
let mut first_success = None;
for (_, _, result) in scoped_results {
match result {
Ok(info) if first_info.is_none() => first_info = Some(info),
Ok(value) if first_success.is_none() => first_success = Some(value),
Ok(_) => {}
Err(err) if is_err_strict_volume_not_found(&err) => {}
Err(err) if first_error.is_none() => first_error = Some(err),
Err(_) => {}
Err(err) => return Err(err),
}
}
if let Some(err) = first_error {
return Err(err);
}
first_info.ok_or(Error::VolumeNotFound)
first_success.ok_or(Error::VolumeNotFound)
}
#[instrument(skip(self))]
pub(super) async fn handle_get_bucket_info(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
let mut info = match self.get_bucket_info_from_sets(bucket, opts).await {
Ok(info) => info,
Err(Error::ErasureWriteQuorum) => return self.get_bucket_info_at_read_quorum(bucket, opts).await,
Err(Error::ErasureWriteQuorum) => return self.get_bucket_info_at_read_quorum(bucket).await,
Err(err) => return Err(err),
};
@@ -1775,14 +1757,14 @@ impl ECStore {
Ok(info)
}
async fn get_bucket_info_at_read_quorum(&self, bucket: &str, opts: &BucketOptions) -> Result<BucketInfo> {
async fn get_bucket_info_at_read_quorum(&self, bucket: &str) -> Result<BucketInfo> {
// Lock order: bucket lifecycle -> internal metadata object read locks.
// Keep create/delete from changing the namespace while a read quorum
// confirms both physical presence and persisted bucket metadata.
let guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
await_bucket_namespace_operation(Some(&guard), bucket, "bucket read quorum validation", async {
let mut info = self
.get_bucket_info_from_sets_with_quorum(bucket, opts, BucketInfoQuorum::Read)
.probe_bucket_sets(|set| async move { set.stat_bucket_with_quorum(bucket, BucketInfoQuorum::Read).await })
.await?;
let (metadata, persisted) = metadata_sys::get_config_from_disk_with_presence_in(&self.ctx, bucket).await?;
if !persisted {
@@ -98,12 +98,19 @@ mod multipart_copy_heal_tests {
seed as u8
})
.collect::<Vec<_>>();
let options = ObjectOptions {
// C's historical timestamp predates this bucket, so bind the upload to its generation.
let (bucket_guard, incarnation) = store
.acquire_bucket_incarnation_fence_for_options(&bucket, None, None)
.await
.expect("hold the source bucket generation through native completion");
let mut options = ObjectOptions {
versioned: true,
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixed native C timestamp")),
expected_bucket_incarnation_id: Some(incarnation),
write_completion: WriteCompletion::TailDrained,
..Default::default()
};
bucket_guard.attach_to_object_options(&mut options);
let upload = store.pools[0]
.new_multipart_upload(&bucket, &object, &options)
.await
@@ -141,6 +148,7 @@ mod multipart_copy_heal_tests {
})
.await
.expect("native completion physical tails drain");
drop(bucket_guard);
let version = completed.version_id.expect("actual native C version");
let original_options = ObjectOptions {
versioned: true,
+1 -1
View File
@@ -288,7 +288,7 @@ impl ECStore {
RenameDataGuards {
scanner_publication_lease_token: scanner_token,
external_guard,
namespace_owner: None,
..Default::default()
},
);
if scanner_token.is_some() {
+2 -5
View File
@@ -389,11 +389,8 @@ mod tests {
"every plaintext POST Object SSE-C form upload must increment the counter"
);
let logs = String::from_utf8(buffer.0.lock().expect("log buffer").clone()).expect("UTF-8 logs");
let warning_lines: Vec<_> = logs
.lines()
.filter(|line| line.contains("ssec_request_without_tls"))
.collect();
assert_eq!(warning_lines.len(), 1, "the plaintext SSE-C warning must fire once per process");
let warning_count = logs.lines().filter(|line| line.contains("ssec_request_without_tls")).count();
assert_eq!(warning_count, 1, "the plaintext SSE-C warning must fire once per process");
}
#[test]