mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-26 18:32:42 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 0ef63577e8 | |||
| 2e9e206d02 | |||
| 4eb6f3d624 | |||
| 9f536da60d | |||
| a66c7c986f | |||
| dbb9ca60fc | |||
| 873f728e55 | |||
| 94f8ec5706 | |||
| 9a65ac95f7 |
@@ -43,6 +43,7 @@ script-tests: ## Run shell script tests
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/test_internode_msgpack_peer_canary.py
|
||||
./scripts/test_internode_msgpack_peer_canary_runner.sh
|
||||
./scripts/test_object_batch_bench_enhanced.sh
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/test_warp_raw_quality.py
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/test_inline_docker_lab.py
|
||||
./scripts/test_package_service_scripts.sh
|
||||
./scripts/test_hotpath_warp_ab_gate.sh
|
||||
|
||||
@@ -416,18 +416,6 @@ threads-required = "num-test-threads"
|
||||
filter = 'package(rustfs-ecstore) & test(/^store::object::tests::(canceled_create_retains_usage_cleanup_namespace_owner|batch_delete_excludes_recovery_on_nonzero_pool|delete_excludes_recovery_with_(disjoint|identical|overlapping)_pool_lock_clients)$/)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# Isolate the physical Apply barrier and same-name multipart lock probes from
|
||||
# competing disk fixtures. Keep their deadlines and internal concurrency.
|
||||
[[profile.ci.overrides]]
|
||||
filter = """
|
||||
package(rustfs-ecstore) & (
|
||||
test(=core::pools::native_recovery::integration_tests::pool_meta_native_physical_runtime_fork_after_apply_latches_original_gate)
|
||||
| test(=set_disk::ops::multipart::same_name_object_namespace_lock_tests::same_name_key_writes_succeed_on_unversioned_versioned_and_hard_quota_buckets)
|
||||
| test(=set_disk::ops::multipart::same_name_object_namespace_lock_tests::same_name_object_write_lock_does_not_block_other_keys_on_versioned_bucket)
|
||||
)
|
||||
"""
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# These eight-disk decommission fixtures exercise concurrent retries,
|
||||
# free-version cleanup, and real capacity probes under production lock deadlines.
|
||||
# Reserve the run's capacity so unrelated IO cannot exhaust those budgets.
|
||||
|
||||
@@ -106,6 +106,8 @@ when restoring `/rustfs/console` for a custom OEM build.
|
||||
## Distributed endpoint locality
|
||||
|
||||
- `RUSTFS_LOCAL_ENDPOINT_HOST` identifies this server's host in a distributed `RUSTFS_VOLUMES` topology without resolving every peer during startup. Set it to exactly one host, without a scheme, port, or path. It is accepted only for orchestrated URL topologies and must match at least one endpoint on the RustFS server port; invalid or unmatched values fail startup. Leave it unset to retain DNS-based locality discovery.
|
||||
- DNS-based discovery resolves each configured hostname once successfully per startup and reuses the result across drives and pools. If discovery finds no local endpoint, startup exits before opening the service listener. Check that this member's advertised hostname resolves to an address on a local interface and that its endpoint port matches `RUSTFS_ADDRESS`. The next start resolves the hosts again.
|
||||
- A finite, positive `RUSTFS_STARTUP_TOPOLOGY_WAIT_TIMEOUT` bounds how long endpoint discovery waits for DNS, including lookups and retry delays. If it expires during startup, the CLI reports the error and exits without waiting for an already-running system resolver call.
|
||||
|
||||
## Scanner environment aliases
|
||||
|
||||
|
||||
@@ -680,13 +680,11 @@ async fn test_copy_object_does_not_inherit_source_legal_hold() {
|
||||
.key("implicit-copy")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
.expect_err("copy should not inherit the source hold");
|
||||
assert_eq!(implicit_legal_hold.raw_response().map(|response| response.status().as_u16()), Some(404));
|
||||
assert_eq!(
|
||||
implicit_legal_hold
|
||||
.legal_hold()
|
||||
.and_then(|value| value.status())
|
||||
.map(|value| value.as_str()),
|
||||
Some("OFF")
|
||||
implicit_legal_hold.as_service_error().and_then(ProvideErrorMetadata::code),
|
||||
Some("NoSuchObjectLockConfiguration")
|
||||
);
|
||||
|
||||
client
|
||||
@@ -2028,12 +2026,12 @@ async fn test_copy_object_retention_uses_destination_policy() {
|
||||
.key("no-default-copy")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let no_default_retention = no_default_retention
|
||||
.retention()
|
||||
.expect("retention response should be present");
|
||||
assert!(no_default_retention.mode().is_none());
|
||||
assert!(no_default_retention.retain_until_date().is_none());
|
||||
.expect_err("copy should have no retention without a destination default");
|
||||
assert_eq!(no_default_retention.raw_response().map(|response| response.status().as_u16()), Some(404));
|
||||
assert_eq!(
|
||||
no_default_retention.as_service_error().and_then(ProvideErrorMetadata::code),
|
||||
Some("NoSuchObjectLockConfiguration")
|
||||
);
|
||||
|
||||
let retained_version_id = put_object_with_retention(
|
||||
&client,
|
||||
|
||||
@@ -230,10 +230,10 @@ pub mod bucket {
|
||||
ObjectLockConfigState, ScannerBucketIncarnationReadGuard, acquire_bucket_metadata_transaction_lock,
|
||||
acquire_bucket_metadata_transaction_lock_for_incarnation, acquire_scanner_bucket_incarnation_fence,
|
||||
acquire_scanner_bucket_incarnation_read_fence, capture_bucket_metadata_incarnation, delete, delete_if_incarnation,
|
||||
delete_if_incarnation_at, delete_under_transaction_lock, get, get_accelerate_config, get_bucket_policy,
|
||||
get_bucket_policy_raw, get_bucket_targets_config, get_config_from_disk, get_cors_config, get_durability_config,
|
||||
get_etag_config, get_global_bucket_metadata_sys, get_lifecycle_config, get_logging_config, get_notification_config,
|
||||
get_object_lock_config, get_object_lock_config_state, get_on_demand_migration_config,
|
||||
delete_if_incarnation_at, delete_under_transaction_lock, find_object_lock_config_state, get, get_accelerate_config,
|
||||
get_bucket_policy, get_bucket_policy_raw, get_bucket_targets_config, get_config_from_disk, get_cors_config,
|
||||
get_durability_config, get_etag_config, get_global_bucket_metadata_sys, get_lifecycle_config, get_logging_config,
|
||||
get_notification_config, get_object_lock_config, get_object_lock_config_state, get_on_demand_migration_config,
|
||||
get_on_demand_migration_config_in, get_public_access_block_config, get_quota_config, get_replication_config,
|
||||
get_request_payment_config, get_s3_tagging_config, get_sse_config, get_tagging_config, get_versioning_config,
|
||||
get_website_config, init_bucket_metadata_sys, list_bucket_targets, reload_bucket_metadata, remove_bucket_metadata,
|
||||
@@ -452,15 +452,13 @@ pub mod data_usage {
|
||||
#[cfg(feature = "test-util")]
|
||||
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
|
||||
pub use crate::data_usage::{
|
||||
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
|
||||
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
|
||||
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations,
|
||||
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
|
||||
load_bucket_scan_progress_for_admin, load_bucket_usage_certification_from_backend_cached,
|
||||
load_bucket_usage_from_backend_cached, load_compression_total_from_memory, load_data_usage_from_backend,
|
||||
load_data_usage_from_backend_cached, quota_object_size, record_bucket_delete_marker_memory,
|
||||
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
|
||||
record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
|
||||
DATA_USAGE_CACHE_NAME, apply_bucket_usage_memory_overlay, compute_bucket_usage,
|
||||
init_compression_total_memory_from_backend, invalidate_admin_data_usage_snapshot_cache,
|
||||
invalidate_data_usage_snapshot_cache, live_bucket_usage_computations, load_admin_data_usage_from_backend_cached,
|
||||
load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin, load_bucket_usage_from_backend_cached,
|
||||
load_compression_total_from_memory, load_data_usage_from_backend, load_data_usage_from_backend_cached, quota_object_size,
|
||||
record_bucket_delete_marker_memory, record_bucket_object_delete_memory, record_bucket_object_version_write_memory,
|
||||
record_bucket_object_write_memory, record_bucket_object_write_unknown_previous_memory, record_compression_total_memory,
|
||||
refresh_bucket_usage_from_object_layer, refresh_versioned_bucket_usage_from_object_layer,
|
||||
remove_bucket_usage_from_backend, replace_bucket_usage_memory_from_info, store_compression_total_in_backend,
|
||||
store_data_usage_in_backend, verified_account_bucket_usage,
|
||||
|
||||
@@ -212,17 +212,18 @@ pub fn get_global_transition_state() -> Arc<TransitionState> {
|
||||
crate::runtime::global::current_ctx().transition_state()
|
||||
}
|
||||
|
||||
fn resolve_transition_worker_count() -> (i64, i64, i64) {
|
||||
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
|
||||
fn resolve_transition_worker_count(parallelism: std::num::NonZeroUsize) -> (i64, i64, i64) {
|
||||
let configured = env::var(ENV_TRANSITION_WORKERS)
|
||||
.ok()
|
||||
.and_then(|value| value.parse::<i64>().ok())
|
||||
.filter(|value| *value > 0)
|
||||
.unwrap_or(fallback);
|
||||
let mut effective = configured;
|
||||
.unwrap_or_else(|| {
|
||||
i64::try_from(parallelism.get())
|
||||
.unwrap_or(i64::MAX)
|
||||
.min(DEFAULT_TRANSITION_WORKERS_CAP)
|
||||
});
|
||||
let absolute_max = resolve_transition_workers_absolute_max();
|
||||
effective = std::cmp::min(effective, absolute_max);
|
||||
(configured, absolute_max, effective)
|
||||
(configured, absolute_max, configured.min(absolute_max))
|
||||
}
|
||||
|
||||
fn resolve_transition_workers_absolute_max() -> i64 {
|
||||
@@ -2085,7 +2086,7 @@ impl TransitionState {
|
||||
}
|
||||
|
||||
pub async fn init(api: Arc<ECStore>) {
|
||||
let (configured, absolute_max, n) = resolve_transition_worker_count();
|
||||
let (configured, absolute_max, n) = resolve_transition_worker_count(api.ctx.worker_parallelism());
|
||||
let transition_state = runtime_sources::transition_state_handle();
|
||||
debug!(
|
||||
event = EVENT_LIFECYCLE_WORKER_STATE,
|
||||
@@ -2100,8 +2101,7 @@ impl TransitionState {
|
||||
"Lifecycle worker configuration resolved"
|
||||
);
|
||||
|
||||
//self.objAPI = objAPI
|
||||
Self::update_workers(api, n).await;
|
||||
Self::resize_workers_to(api, n, n, absolute_max);
|
||||
}
|
||||
|
||||
pub fn pending_tasks(&self) -> usize {
|
||||
@@ -2270,18 +2270,15 @@ impl TransitionState {
|
||||
Self::update_workers_inner(api, n).await;
|
||||
}
|
||||
|
||||
pub async fn update_workers_inner(api: Arc<ECStore>, n: i64) {
|
||||
let mut n = n;
|
||||
let requested = n;
|
||||
if n == 0 {
|
||||
let (_, _, effective) = resolve_transition_worker_count();
|
||||
n = effective;
|
||||
}
|
||||
// Allow environment override of maximum workers
|
||||
let absolute_max = resolve_transition_workers_absolute_max();
|
||||
n = n.clamp(0, absolute_max);
|
||||
|
||||
Self::resize_workers_to(api, n, requested, absolute_max);
|
||||
pub async fn update_workers_inner(api: Arc<ECStore>, requested: i64) {
|
||||
let (effective, absolute_max) = if requested == 0 {
|
||||
let (_, absolute_max, effective) = resolve_transition_worker_count(api.ctx.worker_parallelism());
|
||||
(effective, absolute_max)
|
||||
} else {
|
||||
let absolute_max = resolve_transition_workers_absolute_max();
|
||||
(requested.clamp(0, absolute_max), absolute_max)
|
||||
};
|
||||
Self::resize_workers_to(api, effective, requested, absolute_max);
|
||||
}
|
||||
|
||||
fn resize_workers_to(api: Arc<ECStore>, n: i64, requested: i64, absolute_max: i64) {
|
||||
@@ -2477,19 +2474,16 @@ fn is_lifecycle_expiry_already_gone(err: &Error) -> bool {
|
||||
/// `_RUSTFS_ILM_EXPIRATION_WORKERS` silent override and the
|
||||
/// `RUSTFS_DEFAULT_EXPIRY_WORKERS` zero-fallback were undocumented, unset in
|
||||
/// every known deployment, and are removed (backlog#1832).
|
||||
fn expiry_worker_count() -> usize {
|
||||
let default = std::cmp::min(num_cpus::get(), 16);
|
||||
match env::var(ENV_MAX_EXPIRY_WORKERS) {
|
||||
Ok(value) => match value.parse::<usize>() {
|
||||
Ok(workers) if workers > 0 => workers,
|
||||
_ => default,
|
||||
},
|
||||
Err(_) => default,
|
||||
}
|
||||
fn expiry_worker_count(parallelism: std::num::NonZeroUsize) -> usize {
|
||||
env::var(ENV_MAX_EXPIRY_WORKERS)
|
||||
.ok()
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|workers| *workers > 0)
|
||||
.unwrap_or(parallelism.get().min(16))
|
||||
}
|
||||
|
||||
pub async fn init_background_expiry(api: Arc<ECStore>) {
|
||||
let workers = expiry_worker_count();
|
||||
let workers = expiry_worker_count(api.ctx.worker_parallelism());
|
||||
|
||||
ExpiryState::resize_workers(workers, api.clone()).await;
|
||||
let _ = spawn_tier_free_version_recovery_once(api.clone(), &TIER_FREE_VERSION_RECOVERY_STARTED);
|
||||
@@ -9740,19 +9734,24 @@ mod tests {
|
||||
#[test]
|
||||
#[serial]
|
||||
fn expiry_worker_count_resolves_all_env_states() {
|
||||
let default = std::cmp::min(num_cpus::get(), 16);
|
||||
let default = std::thread::available_parallelism().map_or(1, usize::from).min(16);
|
||||
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
|
||||
|
||||
with_expiry_worker_env(None, || {
|
||||
assert_eq!(expiry_worker_count(), default, "unset env must fall back to min(cpus, 16)");
|
||||
assert_eq!(expiry_worker_count(parallelism), default, "unset env must fall back to min(cpus, 16)");
|
||||
});
|
||||
with_expiry_worker_env(Some("0"), || {
|
||||
assert_eq!(expiry_worker_count(), default, "zero must fall back instead of spawning zero workers");
|
||||
assert_eq!(
|
||||
expiry_worker_count(parallelism),
|
||||
default,
|
||||
"zero must fall back instead of spawning zero workers"
|
||||
);
|
||||
});
|
||||
with_expiry_worker_env(Some("4"), || {
|
||||
assert_eq!(expiry_worker_count(), 4, "a valid positive value must win");
|
||||
with_expiry_worker_env(Some("32"), || {
|
||||
assert_eq!(expiry_worker_count(parallelism), 32, "an explicit count may exceed the default cap");
|
||||
});
|
||||
with_expiry_worker_env(Some("not-a-number"), || {
|
||||
assert_eq!(expiry_worker_count(), default, "garbage must fall back to the default");
|
||||
assert_eq!(expiry_worker_count(parallelism), default, "garbage must fall back to the default");
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9948,9 +9947,13 @@ mod tests {
|
||||
#[serial]
|
||||
fn resolve_transition_worker_count_uses_fallback_when_env_missing() {
|
||||
with_transition_worker_env(None, None, || {
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count();
|
||||
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count(parallelism);
|
||||
|
||||
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
|
||||
let cpus = std::thread::available_parallelism().map_or(1, usize::from);
|
||||
let fallback = i64::try_from(cpus)
|
||||
.expect("available parallelism fits in i64")
|
||||
.min(DEFAULT_TRANSITION_WORKERS_CAP);
|
||||
assert_eq!(configured, fallback);
|
||||
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
|
||||
assert_eq!(effective, fallback);
|
||||
@@ -9961,7 +9964,7 @@ mod tests {
|
||||
#[serial]
|
||||
fn resolve_transition_worker_count_honors_positive_env_value() {
|
||||
with_transition_worker_env(Some("4"), Some("32"), || {
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count();
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
|
||||
|
||||
assert_eq!(configured, 4);
|
||||
assert_eq!(absolute_max, 32);
|
||||
@@ -9973,7 +9976,7 @@ mod tests {
|
||||
#[serial]
|
||||
fn resolve_transition_worker_count_clamps_to_absolute_max() {
|
||||
with_transition_worker_env(Some("64"), Some("16"), || {
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count();
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
|
||||
|
||||
assert_eq!(configured, 64);
|
||||
assert_eq!(absolute_max, 16);
|
||||
@@ -9985,7 +9988,7 @@ mod tests {
|
||||
#[serial]
|
||||
fn resolve_transition_worker_count_ignores_non_positive_absolute_max() {
|
||||
with_transition_worker_env(Some("4"), Some("0"), || {
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count();
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
|
||||
|
||||
assert_eq!(configured, 4);
|
||||
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
|
||||
@@ -9993,7 +9996,7 @@ mod tests {
|
||||
});
|
||||
|
||||
with_transition_worker_env(Some("4"), Some("-1"), || {
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count();
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count(std::num::NonZeroUsize::MIN);
|
||||
|
||||
assert_eq!(configured, 4);
|
||||
assert_eq!(absolute_max, DEFAULT_TRANSITION_WORKERS_ABSOLUTE_MAX);
|
||||
@@ -10005,9 +10008,13 @@ mod tests {
|
||||
#[serial]
|
||||
fn resolve_transition_worker_count_falls_back_for_zero_value() {
|
||||
with_transition_worker_env(Some("0"), Some("32"), || {
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count();
|
||||
let parallelism = crate::runtime::instance::InstanceContext::new().worker_parallelism();
|
||||
let (configured, absolute_max, effective) = resolve_transition_worker_count(parallelism);
|
||||
|
||||
let fallback = std::cmp::min(num_cpus::get() as i64, DEFAULT_TRANSITION_WORKERS_CAP);
|
||||
let cpus = std::thread::available_parallelism().map_or(1, usize::from);
|
||||
let fallback = i64::try_from(cpus)
|
||||
.expect("available parallelism fits in i64")
|
||||
.min(DEFAULT_TRANSITION_WORKERS_CAP);
|
||||
assert_eq!(configured, fallback);
|
||||
assert_eq!(absolute_max, 32);
|
||||
assert_eq!(effective, fallback);
|
||||
|
||||
@@ -151,6 +151,15 @@ pub enum ObjectLockConfigState {
|
||||
Fabricated,
|
||||
}
|
||||
|
||||
// Only namespace probes can name the requested bucket. Internal metadata
|
||||
// storage errors must not be mistaken for absence of that bucket.
|
||||
fn bucket_namespace_error(bucket: &str, error: Error) -> Error {
|
||||
match error {
|
||||
Error::VolumeNotFound => Error::BucketNotFound(bucket.to_owned()),
|
||||
error => error,
|
||||
}
|
||||
}
|
||||
|
||||
enum BucketMetadataAuthority {
|
||||
Authoritative(Arc<BucketMetadata>),
|
||||
Fabricated,
|
||||
@@ -1695,6 +1704,24 @@ pub async fn get_object_lock_config_state(bucket: &str) -> Result<ObjectLockConf
|
||||
bucket_meta_sys.get_object_lock_config_state(bucket).await
|
||||
}
|
||||
|
||||
/// Read Object Lock state from authoritative bucket metadata.
|
||||
///
|
||||
/// `Ok(None)` means the bucket is confirmed missing. An existing bucket with
|
||||
/// no Object Lock configuration returns `Some(ConfirmedAbsent)`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns storage, migration, or validation errors when the state cannot be read.
|
||||
pub async fn find_object_lock_config_state(bucket: &str) -> Result<Option<ObjectLockConfigState>> {
|
||||
let bucket_meta_sys_lock = get_bucket_metadata_sys()?;
|
||||
let bucket_meta_sys = bucket_meta_sys_lock.read().await.clone();
|
||||
|
||||
match bucket_meta_sys.find_object_lock_config_state(bucket).await {
|
||||
Err(Error::BucketNotFound(name)) if name == bucket => Ok(None),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn get_object_lock_config_state_in(
|
||||
ctx: &crate::runtime::instance::InstanceContext,
|
||||
bucket: &str,
|
||||
@@ -3209,7 +3236,8 @@ impl BucketMetadataSys {
|
||||
info.map(|_| ())
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|err| bucket_namespace_error(bucket, err))?;
|
||||
if guard.is_lock_lost() {
|
||||
return Err(Error::other(format!(
|
||||
"bucket namespace lock was lost before lazy bucket metadata publish: {bucket}"
|
||||
@@ -3369,14 +3397,18 @@ impl BucketMetadataSys {
|
||||
}
|
||||
|
||||
pub async fn get_object_lock_config_state(&self, bucket: &str) -> Result<ObjectLockConfigState> {
|
||||
match self.get_metadata_authority(bucket).await? {
|
||||
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm),
|
||||
BucketMetadataAuthority::Fabricated => match self.migrate_legacy_metadata(bucket).await? {
|
||||
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm),
|
||||
BucketMetadataAuthority::MissingBucket => Err(Error::ConfigNotFound),
|
||||
BucketMetadataAuthority::Fabricated => Ok(ObjectLockConfigState::Fabricated),
|
||||
},
|
||||
BucketMetadataAuthority::MissingBucket => Err(Error::ConfigNotFound),
|
||||
self.find_object_lock_config_state(bucket).await?.ok_or(Error::ConfigNotFound)
|
||||
}
|
||||
|
||||
async fn find_object_lock_config_state(&self, bucket: &str) -> Result<Option<ObjectLockConfigState>> {
|
||||
let authority = match self.get_metadata_authority(bucket).await? {
|
||||
BucketMetadataAuthority::Fabricated => self.migrate_legacy_metadata(bucket).await?,
|
||||
authority => authority,
|
||||
};
|
||||
match authority {
|
||||
BucketMetadataAuthority::Authoritative(bm) => object_lock_config_state_from_authoritative_metadata(&bm).map(Some),
|
||||
BucketMetadataAuthority::Fabricated => Ok(Some(ObjectLockConfigState::Fabricated)),
|
||||
BucketMetadataAuthority::MissingBucket => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3516,7 +3548,8 @@ impl BucketMetadataSys {
|
||||
self.object_store()
|
||||
.get_bucket_info_from_sets(bucket, &crate::storage_api_contracts::bucket::BucketOptions::default()),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.map_err(|err| bucket_namespace_error(bucket, err))?;
|
||||
|
||||
let (mut metadata, persisted) = await_bucket_namespace_operation(
|
||||
Some(&namespace_guard),
|
||||
@@ -4564,14 +4597,17 @@ mod tests {
|
||||
sys.get_bucket_policy("migration-write-failure").await,
|
||||
Err(Error::ConfigNotFound)
|
||||
));
|
||||
assert!(sys.get_object_lock_config_state("migration-write-failure").await.is_err());
|
||||
assert!(sys.find_object_lock_config_state("migration-write-failure").await.is_err());
|
||||
assert!(sys.get("migration-write-failure").await.is_err());
|
||||
sys.legacy_migration_write_error.store(false, Ordering::Relaxed);
|
||||
|
||||
let loads_before = sys.lazy_disk_loads.load(Ordering::Relaxed);
|
||||
assert!(sys.find_object_lock_config_state("missing-bucket").await.unwrap().is_none());
|
||||
assert!(matches!(
|
||||
sys.get_object_lock_config_state("missing-bucket").await,
|
||||
Err(Error::ConfigNotFound)
|
||||
));
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), loads_before + 1);
|
||||
assert!(matches!(sys.get_bucket_policy("missing-bucket").await, Err(Error::ConfigNotFound)));
|
||||
assert!(matches!(sys.get_bucket_policy_raw("missing-bucket").await, Err(Error::ConfigNotFound)));
|
||||
|
||||
@@ -5290,14 +5326,14 @@ mod tests {
|
||||
// be lazily republished as a live bucket generation.
|
||||
let mut deleted_lazy = BucketMetadata::new("deleted-lazy-bucket");
|
||||
deleted_lazy.policy_config_json = b"stale-generation".to_vec();
|
||||
sys.persist_and_set(deleted_lazy)
|
||||
sys.persist_new_and_set(deleted_lazy)
|
||||
.await
|
||||
.expect("stale metadata should persist");
|
||||
.expect("stale committed metadata should persist");
|
||||
sys.metadata_map.write().await.remove("deleted-lazy-bucket");
|
||||
assert!(
|
||||
sys.get_config("deleted-lazy-bucket").await.is_err(),
|
||||
"lazy load must fail when the physical bucket no longer exists"
|
||||
);
|
||||
assert!(matches!(
|
||||
sys.get_config("deleted-lazy-bucket").await,
|
||||
Err(Error::BucketNotFound(name)) if name == "deleted-lazy-bucket"
|
||||
));
|
||||
assert!(sys.get("deleted-lazy-bucket").await.is_err());
|
||||
|
||||
// (d) The namespace generation fence must be acquired before lazy
|
||||
|
||||
@@ -44,7 +44,7 @@ use crate::{
|
||||
};
|
||||
use futures::{
|
||||
future::join_all,
|
||||
stream::{FuturesUnordered, StreamExt},
|
||||
stream::{self, StreamExt},
|
||||
};
|
||||
use http::HeaderMap;
|
||||
use rustfs_filemeta::FileInfo;
|
||||
@@ -540,39 +540,39 @@ impl Sets {
|
||||
// pub default_parity_count: usize,
|
||||
// }
|
||||
|
||||
struct DelObj {
|
||||
// set_idx: usize,
|
||||
orig_idx: usize,
|
||||
obj: ObjectToDelete,
|
||||
#[derive(Default)]
|
||||
struct SetDeleteBatch {
|
||||
indices: Vec<usize>,
|
||||
objects: Vec<ObjectToDelete>,
|
||||
}
|
||||
|
||||
fn apply_delete_objects_results(
|
||||
del_objects: &mut [DeletedObject],
|
||||
del_errs: &mut [Option<Error>],
|
||||
set_objects: &[DelObj],
|
||||
dobjects: &[DeletedObject],
|
||||
indices: &[usize],
|
||||
deleted: Vec<DeletedObject>,
|
||||
errs: Vec<Option<Error>>,
|
||||
) {
|
||||
let mut deleted = deleted.into_iter();
|
||||
for (i, err) in errs.into_iter().enumerate() {
|
||||
let obj = set_objects
|
||||
let index = *indices
|
||||
.get(i)
|
||||
.expect("delete_objects should return errors aligned with input objects");
|
||||
|
||||
del_errs[obj.orig_idx] = err;
|
||||
del_objects[obj.orig_idx] = dobjects
|
||||
.get(i)
|
||||
.expect("delete_objects should return objects aligned with input objects")
|
||||
.clone();
|
||||
del_errs[index] = err;
|
||||
del_objects[index] = deleted
|
||||
.next()
|
||||
.expect("delete_objects should return objects aligned with input objects");
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_delete_accounting_results(
|
||||
accounting: &mut [Option<DeleteAccounting>],
|
||||
set_objects: &[DelObj],
|
||||
set_accounting: &[Option<DeleteAccounting>],
|
||||
indices: &[usize],
|
||||
set_accounting: Vec<Option<DeleteAccounting>>,
|
||||
) {
|
||||
for (obj, value) in set_objects.iter().zip(set_accounting.iter()) {
|
||||
accounting[obj.orig_idx] = value.clone();
|
||||
for (&index, value) in indices.iter().zip(set_accounting) {
|
||||
accounting[index] = value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -583,43 +583,60 @@ impl Sets {
|
||||
objects: Vec<ObjectToDelete>,
|
||||
opts: ObjectOptions,
|
||||
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
|
||||
let [first, rest @ ..] = objects.as_slice() else {
|
||||
return (Vec::new(), Vec::new(), Vec::new());
|
||||
};
|
||||
if let [set] = self.disk_set.as_slice() {
|
||||
return set.delete_objects_with_accounting(bucket, objects, opts).await;
|
||||
}
|
||||
|
||||
let first_set = self.get_hashed_set_index(&first.object_name);
|
||||
let Some(prefix_len) = rest
|
||||
.iter()
|
||||
.position(|object| self.get_hashed_set_index(&object.object_name) != first_set)
|
||||
.map(|offset| offset + 1)
|
||||
else {
|
||||
return self.disk_set[first_set]
|
||||
.delete_objects_with_accounting(bucket, objects, opts)
|
||||
.await;
|
||||
};
|
||||
|
||||
let mut del_objects = vec![DeletedObject::default(); objects.len()];
|
||||
let mut del_errs = vec![None; objects.len()];
|
||||
let mut accounting = vec![None; objects.len()];
|
||||
let mut set_obj_map = HashMap::new();
|
||||
|
||||
for (i, obj) in objects.iter().enumerate() {
|
||||
let idx = self.get_hashed_set_index(obj.object_name.as_str());
|
||||
set_obj_map.entry(idx).or_insert_with(Vec::new).push(DelObj {
|
||||
orig_idx: i,
|
||||
obj: obj.clone(),
|
||||
});
|
||||
let mut objects = objects.into_iter().enumerate();
|
||||
let (indices, first_objects) = objects.by_ref().take(prefix_len).unzip();
|
||||
let mut batches = HashMap::new();
|
||||
batches.insert(
|
||||
first_set,
|
||||
SetDeleteBatch {
|
||||
indices,
|
||||
objects: first_objects,
|
||||
},
|
||||
);
|
||||
|
||||
for (index, object) in objects {
|
||||
let set_index = self.get_hashed_set_index(&object.object_name);
|
||||
let batch = batches.entry(set_index).or_default();
|
||||
batch.indices.push(index);
|
||||
batch.objects.push(object);
|
||||
}
|
||||
|
||||
let max_concurrent = set_obj_map.len().min(num_cpus::get()).max(1);
|
||||
let semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
|
||||
let mut futures = FuturesUnordered::new();
|
||||
let bucket = bucket.to_owned();
|
||||
let mut pending = stream::iter(batches)
|
||||
.map(|(set_index, batch)| {
|
||||
let disks = self.get_disks(set_index);
|
||||
let opts = opts.clone();
|
||||
async move {
|
||||
let (deleted, errors, accounting) = disks.delete_objects_with_accounting(bucket, batch.objects, opts).await;
|
||||
(batch.indices, deleted, errors, accounting)
|
||||
}
|
||||
})
|
||||
.buffer_unordered(self.ctx.worker_parallelism().get());
|
||||
|
||||
for (set_index, set_objects) in set_obj_map {
|
||||
let disks = self.get_disks(set_index);
|
||||
let objects = set_objects.iter().map(|entry| entry.obj.clone()).collect::<Vec<_>>();
|
||||
let bucket = bucket.clone();
|
||||
let opts = opts.clone();
|
||||
let semaphore = semaphore.clone();
|
||||
futures.push(async move {
|
||||
let _permit = semaphore
|
||||
.acquire_owned()
|
||||
.await
|
||||
.expect("delete_objects semaphore should remain open");
|
||||
let (deleted, errors, accounting) = disks.delete_objects_with_accounting(&bucket, objects, opts).await;
|
||||
(set_objects, deleted, errors, accounting)
|
||||
});
|
||||
}
|
||||
|
||||
while let Some((set_objects, deleted, errors, set_accounting)) = futures.next().await {
|
||||
apply_delete_objects_results(&mut del_objects, &mut del_errs, &set_objects, &deleted, errors);
|
||||
apply_delete_accounting_results(&mut accounting, &set_objects, &set_accounting);
|
||||
while let Some((indices, deleted, errors, set_accounting)) = pending.next().await {
|
||||
apply_delete_objects_results(&mut del_objects, &mut del_errs, &indices, deleted, errors);
|
||||
apply_delete_accounting_results(&mut accounting, &indices, set_accounting);
|
||||
}
|
||||
|
||||
(del_objects, del_errs, accounting)
|
||||
@@ -1569,35 +1586,14 @@ mod tests {
|
||||
let mut del_objects = vec![DeletedObject::default(); 3];
|
||||
let mut del_errs = vec![None, None, None];
|
||||
|
||||
let early_batch = vec![DelObj {
|
||||
orig_idx: 1,
|
||||
obj: ObjectToDelete {
|
||||
object_name: "second".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
}];
|
||||
let early_indices = [1];
|
||||
let early_objects = vec![DeletedObject {
|
||||
object_name: "second".to_string(),
|
||||
found: true,
|
||||
..Default::default()
|
||||
}];
|
||||
|
||||
let late_batch = vec![
|
||||
DelObj {
|
||||
orig_idx: 2,
|
||||
obj: ObjectToDelete {
|
||||
object_name: "third".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
DelObj {
|
||||
orig_idx: 0,
|
||||
obj: ObjectToDelete {
|
||||
object_name: "first".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
];
|
||||
let late_indices = [2, 0];
|
||||
let late_objects = vec![
|
||||
DeletedObject {
|
||||
object_name: "third".to_string(),
|
||||
@@ -1611,12 +1607,12 @@ mod tests {
|
||||
},
|
||||
];
|
||||
|
||||
apply_delete_objects_results(&mut del_objects, &mut del_errs, &early_batch, &early_objects, vec![None]);
|
||||
apply_delete_objects_results(&mut del_objects, &mut del_errs, &early_indices, early_objects, vec![None]);
|
||||
apply_delete_objects_results(
|
||||
&mut del_objects,
|
||||
&mut del_errs,
|
||||
&late_batch,
|
||||
&late_objects,
|
||||
&late_indices,
|
||||
late_objects,
|
||||
vec![Some(Error::other("third failed")), None],
|
||||
);
|
||||
|
||||
|
||||
@@ -230,126 +230,50 @@ pub async fn lookup_degraded_bucket_usage_baseline(store: Arc<ECStore>, bucket:
|
||||
.and_then(|cached| cached.degraded_baseline.get(bucket).copied())
|
||||
}
|
||||
|
||||
/// Whether a cached usage snapshot can certify the current bucket's byte count.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BucketUsageStatus {
|
||||
Certified(u64),
|
||||
Pending(BucketUsagePendingReason),
|
||||
Unavailable(BucketUsageUnavailableReason),
|
||||
}
|
||||
|
||||
/// Why otherwise readable usage cannot yet certify this bucket.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BucketUsagePendingReason {
|
||||
SnapshotNotReady,
|
||||
BucketPending,
|
||||
MissingBucketProof,
|
||||
PreviousIncarnation,
|
||||
}
|
||||
|
||||
/// Which part of a purported certification was invalid.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BucketUsageUnavailableReason {
|
||||
InvalidSnapshotProof,
|
||||
InvalidBucketIncarnation,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum SnapshotCertification {
|
||||
Ready,
|
||||
Pending,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
/// An immutable sample with its bucket certification metadata checked once.
|
||||
#[derive(Debug, Clone)]
|
||||
struct UsageSnapshot {
|
||||
info: DataUsageInfo,
|
||||
certification: SnapshotCertification,
|
||||
can_certify_buckets: bool,
|
||||
}
|
||||
|
||||
impl UsageSnapshot {
|
||||
fn new(info: DataUsageInfo, invalid_certification_claim: bool) -> Self {
|
||||
let certification = if invalid_certification_claim
|
||||
|| info.usage_snapshot_admin_projection
|
||||
|| (info.usage_snapshot_complete && (info.usage_snapshot_partial || info.usage_snapshot_bootstrap_pending))
|
||||
{
|
||||
SnapshotCertification::Invalid
|
||||
} else if info.usage_snapshot_bootstrap_pending || info.usage_snapshot_observational || !info.usage_snapshot_complete {
|
||||
SnapshotCertification::Pending
|
||||
} else if !info.is_complete_bucket_usage_snapshot() {
|
||||
SnapshotCertification::Invalid
|
||||
} else {
|
||||
let pending = &info.usage_snapshot_pending_buckets;
|
||||
if u64::try_from(pending.len()).ok() != Some(info.usage_snapshot_pending_bucket_count) {
|
||||
SnapshotCertification::Invalid
|
||||
} else {
|
||||
match info.usage_snapshot_converged {
|
||||
Some(true) if pending.is_empty() => SnapshotCertification::Ready,
|
||||
Some(false) if !pending.is_empty() && pending.windows(2).all(|pair| pair[0] < pair[1]) => {
|
||||
SnapshotCertification::Ready
|
||||
}
|
||||
None if pending.is_empty() => SnapshotCertification::Pending,
|
||||
_ => SnapshotCertification::Invalid,
|
||||
}
|
||||
}
|
||||
};
|
||||
let certification = match certification {
|
||||
SnapshotCertification::Ready if info.scanner_cycle.is_none() || info.scanner_epoch.is_none() => {
|
||||
SnapshotCertification::Pending
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
Self { info, certification }
|
||||
fn new(info: DataUsageInfo) -> Self {
|
||||
let pending = &info.usage_snapshot_pending_buckets;
|
||||
let can_certify_buckets = info.is_complete_bucket_usage_snapshot()
|
||||
&& !info.usage_snapshot_observational
|
||||
&& info.scanner_cycle.is_some()
|
||||
&& info.scanner_epoch.is_some()
|
||||
&& u64::try_from(pending.len()).ok() == Some(info.usage_snapshot_pending_bucket_count)
|
||||
&& match info.usage_snapshot_converged {
|
||||
Some(true) => pending.is_empty(),
|
||||
Some(false) => !pending.is_empty() && pending.windows(2).all(|pair| pair[0] < pair[1]),
|
||||
None => false,
|
||||
};
|
||||
Self {
|
||||
info,
|
||||
can_certify_buckets,
|
||||
}
|
||||
}
|
||||
|
||||
fn clone_info(&self) -> DataUsageInfo {
|
||||
self.info.clone()
|
||||
}
|
||||
|
||||
fn bucket_usage_certification(&self, bucket: &str, incarnation: uuid::Uuid) -> BucketUsageStatus {
|
||||
use BucketUsagePendingReason::{BucketPending, MissingBucketProof, PreviousIncarnation, SnapshotNotReady};
|
||||
use BucketUsageStatus::{Certified, Pending, Unavailable};
|
||||
use BucketUsageUnavailableReason::{InvalidBucketIncarnation, InvalidSnapshotProof};
|
||||
|
||||
if incarnation.is_nil() {
|
||||
return Unavailable(InvalidBucketIncarnation);
|
||||
}
|
||||
match self.certification {
|
||||
SnapshotCertification::Invalid => return Unavailable(InvalidSnapshotProof),
|
||||
SnapshotCertification::Pending => return Pending(SnapshotNotReady),
|
||||
SnapshotCertification::Ready => {}
|
||||
}
|
||||
if self
|
||||
.info
|
||||
.usage_snapshot_pending_buckets
|
||||
.binary_search_by(|pending| pending.as_str().cmp(bucket))
|
||||
.is_ok()
|
||||
fn certified_bucket_usage(&self, bucket: &str, incarnation: uuid::Uuid) -> Option<u64> {
|
||||
if !self.can_certify_buckets
|
||||
|| incarnation.is_nil()
|
||||
|| self
|
||||
.info
|
||||
.usage_snapshot_pending_buckets
|
||||
.binary_search_by(|pending| pending.as_str().cmp(bucket))
|
||||
.is_ok()
|
||||
{
|
||||
return Pending(BucketPending);
|
||||
}
|
||||
let Some((usage, proof)) = self
|
||||
.info
|
||||
.buckets_usage
|
||||
.get(bucket)
|
||||
.and_then(|usage| usage.bucket_incarnation.as_deref().map(|proof| (usage, proof)))
|
||||
else {
|
||||
return Pending(MissingBucketProof);
|
||||
};
|
||||
match uuid::Uuid::parse_str(proof) {
|
||||
Ok(id) if id == incarnation => Certified(usage.size),
|
||||
Ok(id) if !id.is_nil() => Pending(PreviousIncarnation),
|
||||
_ => Unavailable(InvalidBucketIncarnation),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BucketUsageStatus {
|
||||
fn certified_bytes(self) -> Option<u64> {
|
||||
match self {
|
||||
Self::Certified(bytes) => Some(bytes),
|
||||
Self::Pending(_) | Self::Unavailable(_) => None,
|
||||
return None;
|
||||
}
|
||||
let usage = self.info.buckets_usage.get(bucket)?;
|
||||
let certified = uuid::Uuid::parse_str(usage.bucket_incarnation.as_deref()?).ok()?;
|
||||
(certified == incarnation).then_some(usage.size)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -406,7 +330,6 @@ fn cache_data_usage_snapshot_result<T>(
|
||||
Some(match result {
|
||||
Ok(LoadedUsageBaseline {
|
||||
info,
|
||||
invalid_certification_claim,
|
||||
mut degraded_baseline,
|
||||
observed_unavailable,
|
||||
}) => {
|
||||
@@ -429,7 +352,7 @@ fn cache_data_usage_snapshot_result<T>(
|
||||
degraded_baseline.entry(bucket.clone()).or_insert(*size);
|
||||
}
|
||||
}
|
||||
let snapshot = UsageSnapshot::new(info, invalid_certification_claim);
|
||||
let snapshot = UsageSnapshot::new(info);
|
||||
let projected = project(&snapshot);
|
||||
*cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(snapshot),
|
||||
@@ -1426,8 +1349,6 @@ pub async fn load_data_usage_from_backend(store: Arc<ECStore>) -> Result<DataUsa
|
||||
/// baseline derived from it.
|
||||
struct LoadedUsageBaseline {
|
||||
info: DataUsageInfo,
|
||||
/// Certification failures detected before normalization can demote the sample.
|
||||
invalid_certification_claim: bool,
|
||||
degraded_baseline: HashMap<String, u64>,
|
||||
/// True when the observed snapshot could not be read (a transport error,
|
||||
/// not absence): the cached loader then carries the previous refresh's
|
||||
@@ -1444,8 +1365,7 @@ async fn load_data_usage_from_backend_with_baseline(store: Arc<ECStore>) -> Resu
|
||||
// The observed-newness gate below compares against the snapshot as
|
||||
// persisted, before normalization demotes or discards anything.
|
||||
let authoritative_as_persisted = loaded_snapshot.snapshot_identity();
|
||||
let (info, mut degraded_baseline, invalid_certification_claim) =
|
||||
normalize_loaded_data_usage(loaded_snapshot, source.is_authoritative()).await;
|
||||
let (info, mut degraded_baseline) = normalize_loaded_data_usage(loaded_snapshot, source.is_authoritative()).await;
|
||||
|
||||
// A bucket without a converged scanner cycle behind it — a freshly joined
|
||||
// replica whose every cycle is superseded by the sustained replication
|
||||
@@ -1471,7 +1391,6 @@ async fn load_data_usage_from_backend_with_baseline(store: Arc<ECStore>) -> Resu
|
||||
|
||||
Ok(LoadedUsageBaseline {
|
||||
info,
|
||||
invalid_certification_claim,
|
||||
degraded_baseline,
|
||||
observed_unavailable,
|
||||
})
|
||||
@@ -1651,12 +1570,10 @@ fn discard_incomplete_bucket_usage(data_usage_info: &mut DataUsageInfo) {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_complete_usage_snapshot(data_usage_info: &mut DataUsageInfo) -> bool {
|
||||
let invalid_complete_claim = data_usage_info.usage_snapshot_complete && !data_usage_info.is_complete_bucket_usage_snapshot();
|
||||
if invalid_complete_claim {
|
||||
fn validate_complete_usage_snapshot(data_usage_info: &mut DataUsageInfo) {
|
||||
if data_usage_info.usage_snapshot_complete && !data_usage_info.is_complete_bucket_usage_snapshot() {
|
||||
data_usage_info.usage_snapshot_complete = false;
|
||||
}
|
||||
invalid_complete_claim
|
||||
}
|
||||
|
||||
fn populate_backward_compatible_usage_maps(data_usage_info: &mut DataUsageInfo) {
|
||||
@@ -1691,16 +1608,14 @@ fn populate_backward_compatible_usage_maps(data_usage_info: &mut DataUsageInfo)
|
||||
async fn normalize_loaded_data_usage(
|
||||
mut data_usage_info: DataUsageInfo,
|
||||
authoritative_format: bool,
|
||||
) -> (DataUsageInfo, HashMap<String, u64>, bool) {
|
||||
) -> (DataUsageInfo, HashMap<String, u64>) {
|
||||
info!("Loaded data usage info from backend with {} buckets", data_usage_info.buckets_count);
|
||||
|
||||
if !authoritative_format {
|
||||
data_usage_info.usage_snapshot_complete = false;
|
||||
}
|
||||
populate_backward_compatible_usage_maps(&mut data_usage_info);
|
||||
let invalid_complete_claim = validate_complete_usage_snapshot(&mut data_usage_info);
|
||||
let invalid_certification_claim =
|
||||
invalid_complete_claim || (authoritative_format && data_usage_info.usage_snapshot_observational);
|
||||
validate_complete_usage_snapshot(&mut data_usage_info);
|
||||
let degraded_baseline = data_usage_info.bucket_sizes.clone();
|
||||
discard_incomplete_bucket_usage(&mut data_usage_info);
|
||||
|
||||
@@ -1727,7 +1642,7 @@ async fn normalize_loaded_data_usage(
|
||||
}
|
||||
}
|
||||
|
||||
(data_usage_info, degraded_baseline, invalid_certification_claim)
|
||||
(data_usage_info, degraded_baseline)
|
||||
}
|
||||
|
||||
/// Load the persisted data usage snapshot through a small in-process cache.
|
||||
@@ -1748,21 +1663,7 @@ pub async fn load_bucket_usage_from_backend_cached(
|
||||
bucket: &str,
|
||||
incarnation: uuid::Uuid,
|
||||
) -> Result<Option<u64>, Error> {
|
||||
Ok(load_bucket_usage_certification_from_backend_cached(store, bucket, incarnation)
|
||||
.await?
|
||||
.certified_bytes())
|
||||
}
|
||||
|
||||
/// Inspect the certification for one bucket in the cached authoritative usage snapshot.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error when the snapshot cannot be read or decoded.
|
||||
pub async fn load_bucket_usage_certification_from_backend_cached(
|
||||
store: Arc<ECStore>,
|
||||
bucket: &str,
|
||||
incarnation: uuid::Uuid,
|
||||
) -> Result<BucketUsageStatus, Error> {
|
||||
project_data_usage_from_backend_cached(store, |snapshot| snapshot.bucket_usage_certification(bucket, incarnation)).await
|
||||
project_data_usage_from_backend_cached(store, |snapshot| snapshot.certified_bucket_usage(bucket, incarnation)).await
|
||||
}
|
||||
|
||||
// Project under the cache guard so scalar readers never copy the snapshot's
|
||||
@@ -1844,7 +1745,6 @@ async fn load_admin_data_usage_snapshot_cached(store: Arc<ECStore>) -> Result<Da
|
||||
.map(|info| LoadedUsageBaseline {
|
||||
info,
|
||||
degraded_baseline: HashMap::new(),
|
||||
invalid_certification_claim: false,
|
||||
observed_unavailable: false,
|
||||
});
|
||||
let loaded_at = tokio::time::Instant::now();
|
||||
@@ -4070,7 +3970,7 @@ mod tests {
|
||||
legacy.bucket_sizes.insert("large".to_string(), 0);
|
||||
legacy.buckets_count = 2;
|
||||
|
||||
let (normalized, degraded_baseline, _) = normalize_loaded_data_usage(legacy, false).await;
|
||||
let (normalized, degraded_baseline) = normalize_loaded_data_usage(legacy, false).await;
|
||||
|
||||
assert_eq!(normalized.buckets_count, 0);
|
||||
assert!(normalized.buckets_usage.is_empty());
|
||||
@@ -4117,7 +4017,7 @@ mod tests {
|
||||
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
|
||||
info.buckets_count = 2;
|
||||
|
||||
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
|
||||
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
|
||||
|
||||
assert_eq!(normalized.buckets_count, 2);
|
||||
assert!(normalized.usage_snapshot_complete);
|
||||
@@ -4152,7 +4052,7 @@ mod tests {
|
||||
info.bucket_sizes.insert("partial".to_string(), 196_870_144);
|
||||
info.buckets_count = 1;
|
||||
|
||||
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
|
||||
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
|
||||
|
||||
assert_eq!(normalized.buckets_count, 0);
|
||||
assert!(!normalized.buckets_usage.contains_key("control"));
|
||||
@@ -4167,7 +4067,7 @@ mod tests {
|
||||
info.buckets_count = 2;
|
||||
|
||||
assert!(!data_usage_contains_bucket(&info, "missing"));
|
||||
let (normalized, _, _) = normalize_loaded_data_usage(info, true).await;
|
||||
let (normalized, _) = normalize_loaded_data_usage(info, true).await;
|
||||
|
||||
assert!(!normalized.usage_snapshot_complete);
|
||||
assert!(normalized.buckets_usage.is_empty());
|
||||
@@ -4176,7 +4076,7 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn complete_empty_snapshot_remains_authoritative() {
|
||||
let (normalized, _, _) = normalize_loaded_data_usage(
|
||||
let (normalized, _) = normalize_loaded_data_usage(
|
||||
DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
usage_snapshot_complete: true,
|
||||
@@ -4441,7 +4341,7 @@ mod tests {
|
||||
async fn partial_admin_observation_does_not_promote_a_legacy_baseline() {
|
||||
let (legacy, observed) = usage_snapshots_with_missing_observed_set();
|
||||
let (selected, current_format) = select_admin_data_usage_snapshot(legacy, false, Some(observed));
|
||||
let (normalized, _, _) = normalize_loaded_data_usage(selected, current_format).await;
|
||||
let (normalized, _) = normalize_loaded_data_usage(selected, current_format).await;
|
||||
|
||||
assert!(normalized.is_valid_partial_snapshot());
|
||||
assert!(!normalized.is_complete_bucket_usage_snapshot());
|
||||
@@ -4563,7 +4463,7 @@ mod tests {
|
||||
async fn install_data_usage_snapshot_cache_for_test(info: DataUsageInfo, age: Duration) {
|
||||
let degraded_baseline = info.bucket_sizes.clone();
|
||||
*data_usage_snapshot_cache().write().await = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(info, false)),
|
||||
snapshot: Some(UsageSnapshot::new(info)),
|
||||
last_load_failed: false,
|
||||
loaded_at: tokio::time::Instant::now()
|
||||
.checked_sub(age)
|
||||
@@ -4599,7 +4499,6 @@ mod tests {
|
||||
LoadedUsageBaseline {
|
||||
degraded_baseline: info.bucket_sizes.clone(),
|
||||
info,
|
||||
invalid_certification_claim: false,
|
||||
observed_unavailable: false,
|
||||
}
|
||||
}
|
||||
@@ -5020,7 +4919,6 @@ mod tests {
|
||||
Ok(LoadedUsageBaseline {
|
||||
info: expected,
|
||||
degraded_baseline: HashMap::new(),
|
||||
invalid_certification_claim: false,
|
||||
observed_unavailable: false,
|
||||
}),
|
||||
loaded_at,
|
||||
@@ -5220,7 +5118,7 @@ mod tests {
|
||||
observed.usage_snapshot_converged = Some(false);
|
||||
observed.usage_snapshot_authoritative_baseline = Some(baseline.snapshot_identity());
|
||||
let mut cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(observed, false)),
|
||||
snapshot: Some(UsageSnapshot::new(observed)),
|
||||
last_load_failed: false,
|
||||
loaded_at,
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -5259,7 +5157,7 @@ mod tests {
|
||||
(loaded.scanner_epoch, loaded.scanner_cycle) = loaded_position;
|
||||
let expected = if accept { &loaded } else { &previous };
|
||||
let mut cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(previous.clone(), false)),
|
||||
snapshot: Some(UsageSnapshot::new(previous.clone())),
|
||||
last_load_failed: false,
|
||||
loaded_at,
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -5286,7 +5184,7 @@ mod tests {
|
||||
let loaded_at = tokio::time::Instant::now();
|
||||
let expected = data_usage_info_for_test("bucket", 3, 42, SystemTime::UNIX_EPOCH + Duration::from_secs(2));
|
||||
let mut cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(expected.clone(), false)),
|
||||
snapshot: Some(UsageSnapshot::new(expected.clone())),
|
||||
last_load_failed: false,
|
||||
loaded_at,
|
||||
degraded_baseline: HashMap::from([("bucket".to_string(), 42)]),
|
||||
@@ -5332,7 +5230,7 @@ mod tests {
|
||||
let now = SystemTime::now();
|
||||
let future = now + rustfs_data_usage::USAGE_LAST_UPDATE_FUTURE_TOLERANCE + Duration::from_secs(60);
|
||||
let mut cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 3, 42, future), false)),
|
||||
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 3, 42, future))),
|
||||
last_load_failed: false,
|
||||
loaded_at,
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -5431,10 +5329,7 @@ mod tests {
|
||||
let loaded_at = tokio::time::Instant::now();
|
||||
let refresh_generation = data_usage_snapshot_generation();
|
||||
let mut cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(
|
||||
data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH),
|
||||
false,
|
||||
)),
|
||||
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH))),
|
||||
last_load_failed: false,
|
||||
loaded_at,
|
||||
degraded_baseline: HashMap::from([("observed-only".to_string(), 7_u64), ("covered".to_string(), 1)]),
|
||||
@@ -5445,7 +5340,6 @@ mod tests {
|
||||
Ok(LoadedUsageBaseline {
|
||||
info: data_usage_info_for_test("bucket", 1, 42, SystemTime::UNIX_EPOCH),
|
||||
degraded_baseline: HashMap::from([("covered".to_string(), 2_u64)]),
|
||||
invalid_certification_claim: false,
|
||||
observed_unavailable: true,
|
||||
}),
|
||||
loaded_at,
|
||||
@@ -5469,10 +5363,7 @@ mod tests {
|
||||
let loaded_at = tokio::time::Instant::now();
|
||||
let refresh_generation = data_usage_snapshot_generation();
|
||||
let mut cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(
|
||||
data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH),
|
||||
false,
|
||||
)),
|
||||
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH))),
|
||||
last_load_failed: false,
|
||||
loaded_at,
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -5484,7 +5375,6 @@ mod tests {
|
||||
Ok(LoadedUsageBaseline {
|
||||
info: data_usage_info_for_test("stale", 1, 42, SystemTime::UNIX_EPOCH),
|
||||
degraded_baseline: HashMap::new(),
|
||||
invalid_certification_claim: false,
|
||||
observed_unavailable: false,
|
||||
}),
|
||||
loaded_at,
|
||||
@@ -6662,7 +6552,7 @@ mod tests {
|
||||
let successor = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
|
||||
let mut snapshot_cache = data_usage_snapshot_cache().write().await;
|
||||
*snapshot_cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(successor, false)),
|
||||
snapshot: Some(UsageSnapshot::new(successor)),
|
||||
last_load_failed: false,
|
||||
loaded_at: tokio::time::Instant::now(),
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -6734,7 +6624,7 @@ mod tests {
|
||||
let successor = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
|
||||
let mut snapshot_cache = data_usage_snapshot_cache().write().await;
|
||||
*snapshot_cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(successor, false)),
|
||||
snapshot: Some(UsageSnapshot::new(successor)),
|
||||
last_load_failed: false,
|
||||
loaded_at: tokio::time::Instant::now(),
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -6787,7 +6677,7 @@ mod tests {
|
||||
};
|
||||
let stale = data_usage_info_for_test(BUCKET, 7, 294, SystemTime::now());
|
||||
*data_usage_snapshot_cache().write().await = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(stale, false)),
|
||||
snapshot: Some(UsageSnapshot::new(stale)),
|
||||
last_load_failed: false,
|
||||
loaded_at: tokio::time::Instant::now(),
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -8237,7 +8127,7 @@ mod tests {
|
||||
// memory. Selecting that newer view must not erase local mutations.
|
||||
let (selected, current_format) = select_admin_data_usage_snapshot(baseline, true, Some(observed));
|
||||
assert_eq!(selected.scanner_cycle, Some(11));
|
||||
let (selected, _, _) = normalize_loaded_data_usage(selected, current_format).await;
|
||||
let (selected, _) = normalize_loaded_data_usage(selected, current_format).await;
|
||||
let mut distributed = selected.clone();
|
||||
apply_bucket_usage_memory_overlay_if_authoritative(&mut distributed, false).await;
|
||||
assert_eq!((distributed.objects_total_count, distributed.objects_total_size), (2, 20));
|
||||
|
||||
@@ -82,9 +82,10 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
|
||||
assert!(reject_admin_usage_projection(&snapshot).is_err());
|
||||
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
|
||||
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
|
||||
assert_eq!(
|
||||
UsageSnapshot::new(snapshot, false).bucket_usage_certification("bucket", incarnation),
|
||||
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
|
||||
assert!(
|
||||
UsageSnapshot::new(snapshot)
|
||||
.certified_bucket_usage("bucket", incarnation)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -380,9 +381,10 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
|
||||
assert!(second.usage_snapshot_admin_projection);
|
||||
assert!(reject_admin_usage_projection(&second).is_err());
|
||||
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
|
||||
assert_eq!(
|
||||
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
|
||||
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
|
||||
assert!(
|
||||
UsageSnapshot::new(second)
|
||||
.certified_bucket_usage(bucket, new_identity)
|
||||
.is_none()
|
||||
);
|
||||
let quota = load_data_usage_from_backend_cached(store.clone())
|
||||
.await
|
||||
|
||||
@@ -20,7 +20,7 @@ fn scalar_projection_borrows_snapshot_and_preserves_unknown_and_zero() {
|
||||
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
|
||||
info.buckets_usage.insert("empty".to_string(), BucketUsageInfo::default());
|
||||
let cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(info, false)),
|
||||
snapshot: Some(UsageSnapshot::new(info)),
|
||||
last_load_failed: false,
|
||||
loaded_at,
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -66,10 +66,7 @@ fn projection_is_skipped_for_missing_failed_expired_or_invalidated_snapshots() {
|
||||
);
|
||||
|
||||
cache = Some(CachedDataUsageSnapshot {
|
||||
snapshot: Some(UsageSnapshot::new(
|
||||
data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH),
|
||||
false,
|
||||
)),
|
||||
snapshot: Some(UsageSnapshot::new(data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH))),
|
||||
last_load_failed: false,
|
||||
loaded_at,
|
||||
degraded_baseline: HashMap::new(),
|
||||
@@ -81,7 +78,6 @@ fn projection_is_skipped_for_missing_failed_expired_or_invalidated_snapshots() {
|
||||
Ok(LoadedUsageBaseline {
|
||||
info: data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH),
|
||||
degraded_baseline: HashMap::new(),
|
||||
invalid_certification_claim: false,
|
||||
observed_unavailable: false,
|
||||
}),
|
||||
loaded_at,
|
||||
@@ -103,7 +99,6 @@ fn projected_publication_moves_bucket_maps_into_cache() {
|
||||
Ok(LoadedUsageBaseline {
|
||||
info,
|
||||
degraded_baseline: HashMap::new(),
|
||||
invalid_certification_claim: false,
|
||||
observed_unavailable: false,
|
||||
}),
|
||||
tokio::time::Instant::now(),
|
||||
@@ -172,106 +167,41 @@ fn projected_publication_moves_bucket_maps_into_cache() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bucket_usage_certification_distinguishes_pending_and_unavailable_proof() {
|
||||
use BucketUsagePendingReason::{BucketPending, MissingBucketProof, PreviousIncarnation, SnapshotNotReady};
|
||||
use BucketUsageStatus::{Certified, Pending, Unavailable};
|
||||
use BucketUsageUnavailableReason::{InvalidBucketIncarnation, InvalidSnapshotProof};
|
||||
|
||||
fn certified_bucket_usage_rejects_unproven_and_pending_data() {
|
||||
let id = uuid::Uuid::from_u128(7);
|
||||
let mut info = data_usage_info_for_test("known", 1, 42, SystemTime::UNIX_EPOCH);
|
||||
info.usage_snapshot_converged = Some(true);
|
||||
info.scanner_cycle = Some(1);
|
||||
info.scanner_epoch = Some(1);
|
||||
info.buckets_usage
|
||||
.get_mut("known")
|
||||
.expect("fixture bucket")
|
||||
.bucket_incarnation = Some(id.to_string());
|
||||
let certified = UsageSnapshot::new(info.clone(), false);
|
||||
assert_eq!(certified.bucket_usage_certification("known", id), Certified(42));
|
||||
assert_eq!(certified.bucket_usage_certification("missing", id), Pending(MissingBucketProof));
|
||||
assert_eq!(
|
||||
certified.bucket_usage_certification("known", uuid::Uuid::from_u128(8)),
|
||||
Pending(PreviousIncarnation)
|
||||
);
|
||||
assert_eq!(
|
||||
certified.bucket_usage_certification("known", uuid::Uuid::nil()),
|
||||
Unavailable(InvalidBucketIncarnation)
|
||||
);
|
||||
for (proof, expected) in [
|
||||
(None, Pending(MissingBucketProof)),
|
||||
(Some("corrupt".into()), Unavailable(InvalidBucketIncarnation)),
|
||||
(Some(uuid::Uuid::nil().to_string()), Unavailable(InvalidBucketIncarnation)),
|
||||
] {
|
||||
let mut sample = info.clone();
|
||||
sample
|
||||
.buckets_usage
|
||||
.get_mut("known")
|
||||
.expect("fixture bucket")
|
||||
.bucket_incarnation = proof;
|
||||
assert_eq!(UsageSnapshot::new(sample, false).bucket_usage_certification("known", id), expected);
|
||||
}
|
||||
|
||||
for (names, count, expected) in [
|
||||
(vec!["other"], 1, Certified(42)),
|
||||
(vec!["known"], 1, Pending(BucketPending)),
|
||||
(vec!["known"], 0, Unavailable(InvalidSnapshotProof)),
|
||||
(vec!["z", "a"], 2, Unavailable(InvalidSnapshotProof)),
|
||||
(vec!["other", "other"], 2, Unavailable(InvalidSnapshotProof)),
|
||||
(vec![], 0, Unavailable(InvalidSnapshotProof)),
|
||||
] {
|
||||
let mut sample = info.clone();
|
||||
sample.usage_snapshot_converged = Some(false);
|
||||
sample.usage_snapshot_pending_buckets = names.into_iter().map(str::to_owned).collect();
|
||||
sample.usage_snapshot_pending_bucket_count = count;
|
||||
assert_eq!(UsageSnapshot::new(sample, false).bucket_usage_certification("known", id), expected);
|
||||
}
|
||||
|
||||
for sample in [
|
||||
DataUsageInfo {
|
||||
usage_snapshot_partial: true,
|
||||
..info.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
scanner_epoch: None,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_pending_buckets: vec!["known".into()],
|
||||
..info.clone()
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
UsageSnapshot::new(sample, false).bucket_usage_certification("known", id),
|
||||
Unavailable(InvalidSnapshotProof)
|
||||
);
|
||||
}
|
||||
|
||||
let bootstrap = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
scanner_epoch: Some(1),
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
..Default::default()
|
||||
};
|
||||
for sample in [
|
||||
DataUsageInfo::default(),
|
||||
bootstrap,
|
||||
DataUsageInfo {
|
||||
usage_snapshot_observational: true,
|
||||
..info.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
scanner_epoch: None,
|
||||
..info.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_converged: None,
|
||||
..info
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
UsageSnapshot::new(sample, false).bucket_usage_certification("known", id),
|
||||
Pending(SnapshotNotReady)
|
||||
);
|
||||
}
|
||||
info.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some(id.to_string());
|
||||
let certified = UsageSnapshot::new(info.clone());
|
||||
assert_eq!(certified.certified_bucket_usage("known", id), Some(42));
|
||||
assert_eq!(certified.certified_bucket_usage("known", uuid::Uuid::from_u128(8)), None);
|
||||
assert_eq!(certified.certified_bucket_usage("known", uuid::Uuid::nil()), None);
|
||||
let mut legacy = info.clone();
|
||||
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = None;
|
||||
assert_eq!(UsageSnapshot::new(legacy.clone()).certified_bucket_usage("known", id), None);
|
||||
legacy.buckets_usage.get_mut("known").unwrap().bucket_incarnation = Some("corrupt".into());
|
||||
assert_eq!(UsageSnapshot::new(legacy).certified_bucket_usage("known", id), None);
|
||||
let mut pending = info.clone();
|
||||
pending.usage_snapshot_converged = Some(false);
|
||||
pending.usage_snapshot_pending_buckets = vec!["other".into()];
|
||||
pending.usage_snapshot_pending_bucket_count = 1;
|
||||
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), Some(42));
|
||||
pending.usage_snapshot_pending_buckets = vec!["known".into()];
|
||||
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
|
||||
pending.usage_snapshot_pending_bucket_count = 0;
|
||||
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
|
||||
pending.usage_snapshot_pending_buckets = vec!["z".into(), "a".into()];
|
||||
pending.usage_snapshot_pending_bucket_count = 2;
|
||||
assert_eq!(UsageSnapshot::new(pending.clone()).certified_bucket_usage("known", id), None);
|
||||
pending.usage_snapshot_pending_buckets = vec!["other".into(), "other".into()];
|
||||
assert_eq!(UsageSnapshot::new(pending).certified_bucket_usage("known", id), None);
|
||||
let mut observational = info.clone();
|
||||
observational.usage_snapshot_observational = true;
|
||||
assert_eq!(UsageSnapshot::new(observational).certified_bucket_usage("known", id), None);
|
||||
info.usage_snapshot_converged = None;
|
||||
assert_eq!(UsageSnapshot::new(info).certified_bucket_usage("known", id), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -366,55 +296,12 @@ async fn persisted_scalar_projection_shares_cache_refresh_and_invalidation() {
|
||||
.expect("persist malformed certification evidence");
|
||||
invalidate_data_usage_snapshot_cache().await;
|
||||
assert_eq!(
|
||||
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
|
||||
load_bucket_usage_from_backend_cached(store.clone(), "known", incarnation)
|
||||
.await
|
||||
.expect("read snapshot without accepting malformed certification"),
|
||||
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
|
||||
None
|
||||
);
|
||||
assert_eq!(persisted_bucket_usage(store.clone(), "known").await, Some(84));
|
||||
|
||||
info.scanner_cycle = Some(3);
|
||||
info.usage_snapshot_converged = Some(true);
|
||||
info.usage_snapshot_pending_bucket_count = 0;
|
||||
info.usage_snapshot_pending_buckets.clear();
|
||||
info.buckets_count += 1;
|
||||
save_config(
|
||||
store.clone(),
|
||||
DATA_USAGE_OBJ_NAME_PATH.as_str(),
|
||||
serde_json::to_vec(&info).expect("encode invalid bucket count"),
|
||||
)
|
||||
.await
|
||||
.expect("persist malformed completeness claim");
|
||||
invalidate_data_usage_snapshot_cache().await;
|
||||
assert_eq!(
|
||||
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
|
||||
.await
|
||||
.expect("classify demoted completeness claim"),
|
||||
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
|
||||
);
|
||||
let raw = load_data_usage_from_backend_cached(store.clone())
|
||||
.await
|
||||
.expect("read normalized usage");
|
||||
assert!(!raw.usage_snapshot_complete);
|
||||
assert!(raw.buckets_usage.is_empty());
|
||||
|
||||
info.scanner_cycle = Some(4);
|
||||
info.buckets_count -= 1;
|
||||
info.usage_snapshot_observational = true;
|
||||
save_config(
|
||||
store.clone(),
|
||||
DATA_USAGE_OBJ_NAME_PATH.as_str(),
|
||||
serde_json::to_vec(&info).expect("encode observational sample in primary slot"),
|
||||
)
|
||||
.await
|
||||
.expect("persist wrong snapshot kind");
|
||||
invalidate_data_usage_snapshot_cache().await;
|
||||
assert_eq!(
|
||||
load_bucket_usage_certification_from_backend_cached(store.clone(), "known", incarnation)
|
||||
.await
|
||||
.expect("classify wrong snapshot kind"),
|
||||
BucketUsageStatus::Unavailable(BucketUsageUnavailableReason::InvalidSnapshotProof)
|
||||
);
|
||||
invalidate_data_usage_snapshot_cache().await;
|
||||
if let Some(cancel) = store.ctx.background_cancel_token() {
|
||||
cancel.cancel();
|
||||
|
||||
@@ -22915,6 +22915,22 @@ mod test {
|
||||
.expect("new tmp data should be written");
|
||||
let dst_meta_parent = dir.path().join(bucket).join(object);
|
||||
os::fsync_dir_recorder::set_grouped_failure(&dst_meta_parent, io::ErrorKind::PermissionDenied);
|
||||
let disk_permits = Arc::clone(&disk.file_sync_permits);
|
||||
let initial_permits = disk_permits.available_permits();
|
||||
let (permit_probe_tx, mut permit_probe_rx) = tokio::sync::oneshot::channel();
|
||||
let canonical_parent = dir
|
||||
.path()
|
||||
.canonicalize()
|
||||
.expect("canonical fixture directory")
|
||||
.join(bucket)
|
||||
.join(object);
|
||||
let _probe = os::prepared_publication_test_hooks::install_at(
|
||||
os::prepared_publication_test_hooks::Stage::DirFsync,
|
||||
&canonical_parent,
|
||||
move || {
|
||||
let _ = permit_probe_tx.send(disk_permits.available_permits());
|
||||
},
|
||||
);
|
||||
|
||||
let new_fi = test_file_info(object, version_id, Some(new_data_dir), None);
|
||||
let err = disk
|
||||
@@ -22923,6 +22939,8 @@ mod test {
|
||||
.expect_err("grouped dst dir fsync failure must fail the fresh PUT");
|
||||
|
||||
assert_eq!(err, DiskError::FileAccessDenied);
|
||||
assert_eq!(permit_probe_rx.try_recv().expect("observe the grouped syscall"), initial_permits - 1);
|
||||
assert_eq!(disk.file_sync_permits.available_permits(), initial_permits);
|
||||
assert!(
|
||||
!dst_meta_parent.join(STORAGE_FORMAT_FILE).exists(),
|
||||
"fresh PUT rollback must remove the committed xl.meta after grouped dst dir fsync failure"
|
||||
|
||||
@@ -2152,9 +2152,17 @@ impl LocalDisk {
|
||||
&& let Some(parent) = dst_file_path.parent()
|
||||
{
|
||||
let fsync_started = rustfs_io_metrics::put_stage_timer();
|
||||
if let Err(err) =
|
||||
os::fsync_commit_directory(parent, &commit.directory_guard, commit.mutation_lease.clone(), None).await
|
||||
{
|
||||
let fsync_result = async {
|
||||
let admission = if dst_dir_group_commit {
|
||||
Some(os::acquire_file_sync_admission(self.file_sync_permits.clone()).await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
os::fsync_commit_directory(parent, &commit.directory_guard, commit.mutation_lease.clone(), admission.as_ref())
|
||||
.await
|
||||
}
|
||||
.await;
|
||||
if let Err(err) = fsync_result {
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_DST_DIR_FSYNC,
|
||||
fsync_started,
|
||||
|
||||
+126
-42
@@ -1007,14 +1007,15 @@ impl OpenedDstDirFsyncGroup {
|
||||
}
|
||||
|
||||
struct DstDirFsyncWaiter {
|
||||
namespace_owner: Option<Arc<dyn Send + Sync>>,
|
||||
resource_unit: Option<super::io_admission::ResourceIoUnit>,
|
||||
owner: DstDirFsyncOwner,
|
||||
result_tx: oneshot::Sender<SharedDstDirFsyncResult>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DstDirFsyncOwner {
|
||||
_namespace: Option<Arc<dyn Send + Sync>>,
|
||||
_resource: Option<super::io_admission::ResourceIoUnit>,
|
||||
disk_permit: Option<Arc<OwnedSemaphorePermit>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -1073,6 +1074,7 @@ impl DstDirFsyncGroupCommit {
|
||||
&self,
|
||||
opened: OpenedDstDirFsyncGroup,
|
||||
namespace_owner: Option<Arc<dyn Send + Sync>>,
|
||||
admission: Option<&FileSyncAdmission>,
|
||||
) -> io::Result<(oneshot::Receiver<SharedDstDirFsyncResult>, Option<Arc<DstDirFsyncGroup>>)> {
|
||||
let (result_tx, result_rx) = oneshot::channel();
|
||||
let mut registry = self.inner.lock();
|
||||
@@ -1105,8 +1107,11 @@ impl DstDirFsyncGroupCommit {
|
||||
let mut group_state = group.inner.lock();
|
||||
group_state.pending.push_back(DstDirFsyncWaiter {
|
||||
result_tx,
|
||||
namespace_owner,
|
||||
resource_unit: super::io_admission::current_resource_unit(),
|
||||
owner: DstDirFsyncOwner {
|
||||
_namespace: namespace_owner,
|
||||
_resource: super::io_admission::current_resource_unit(),
|
||||
disk_permit: admission.map(|admission| Arc::clone(&admission.disk_permit)),
|
||||
},
|
||||
});
|
||||
let start_worker = !group_state.worker_running;
|
||||
if start_worker {
|
||||
@@ -1158,7 +1163,7 @@ impl DstDirFsyncGroupCommit {
|
||||
&self,
|
||||
dir: &Path,
|
||||
) -> io::Result<(oneshot::Receiver<SharedDstDirFsyncResult>, Option<Arc<DstDirFsyncGroup>>)> {
|
||||
self.enqueue_opened(OpenedDstDirFsyncGroup::open(dir)?, None)
|
||||
self.enqueue_opened(OpenedDstDirFsyncGroup::open(dir)?, None, None)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1224,7 +1229,10 @@ impl Drop for DstDirFsyncWorkerGuard {
|
||||
}
|
||||
}
|
||||
|
||||
fn run_dst_dir_fsync_group_worker(group: Arc<DstDirFsyncGroup>) -> impl std::future::Future<Output = ()> {
|
||||
fn run_dst_dir_fsync_group_worker(
|
||||
group: Arc<DstDirFsyncGroup>,
|
||||
global_permits: &Semaphore,
|
||||
) -> impl std::future::Future<Output = ()> + '_ {
|
||||
// Capture before spawning: shutdown may drop the future without polling it.
|
||||
let worker_guard = DstDirFsyncWorkerGuard {
|
||||
group: group.clone(),
|
||||
@@ -1253,20 +1261,25 @@ fn run_dst_dir_fsync_group_worker(group: Arc<DstDirFsyncGroup>) -> impl std::fut
|
||||
|
||||
#[cfg(test)]
|
||||
fsync_dir_recorder::record_grouped(&group.dir, batch.len());
|
||||
let namespace_owners = batch
|
||||
let owners: Vec<_> = batch
|
||||
.iter_mut()
|
||||
.filter_map(|waiter| {
|
||||
let namespace = waiter.namespace_owner.take();
|
||||
let resource = waiter.resource_unit.take();
|
||||
(namespace.is_some() || resource.is_some()).then_some(DstDirFsyncOwner {
|
||||
_namespace: namespace,
|
||||
_resource: resource,
|
||||
})
|
||||
let owner = std::mem::take(&mut waiter.owner);
|
||||
(owner._namespace.is_some() || owner._resource.is_some() || owner.disk_permit.is_some()).then_some(owner)
|
||||
})
|
||||
.collect();
|
||||
let result = fsync_open_dst_dir_group(&group, namespace_owners)
|
||||
.await
|
||||
.map_err(SharedDstDirFsyncError::from_error);
|
||||
let result = async {
|
||||
// The waiters already hold their disk admission. Reserve one global slot
|
||||
// per physical sync, keeping it with the worker so shutdown can release it.
|
||||
let _global_permit = if owners.iter().any(|owner| owner.disk_permit.is_some()) {
|
||||
Some(acquire_global_file_sync_permit(global_permits).await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
fsync_open_dst_dir_group(&group, owners).await
|
||||
}
|
||||
.await
|
||||
.map_err(SharedDstDirFsyncError::from_error);
|
||||
let batch_len = batch.len();
|
||||
DST_DIR_FSYNC_GROUP_COMMIT.complete_batch(batch_len);
|
||||
worker_guard.in_flight = 0;
|
||||
@@ -1300,7 +1313,7 @@ async fn fsync_dst_dir_group_commit_with_enabled(
|
||||
enabled: bool,
|
||||
namespace_owner: Option<Arc<dyn Send + Sync>>,
|
||||
) -> io::Result<()> {
|
||||
fsync_dst_dir_group_commit_opened(dir.as_ref(), enabled, namespace_owner, None).await
|
||||
fsync_dst_dir_group_commit_opened(dir.as_ref(), enabled, namespace_owner, None, None).await
|
||||
}
|
||||
|
||||
async fn fsync_dst_dir_group_commit_opened(
|
||||
@@ -1308,6 +1321,7 @@ async fn fsync_dst_dir_group_commit_opened(
|
||||
enabled: bool,
|
||||
namespace_owner: Option<Arc<dyn Send + Sync>>,
|
||||
opened: Option<Arc<std::fs::File>>,
|
||||
admission: Option<&FileSyncAdmission>,
|
||||
) -> io::Result<()> {
|
||||
if !enabled {
|
||||
if let Some(file) = opened {
|
||||
@@ -1333,9 +1347,9 @@ async fn fsync_dst_dir_group_commit_opened(
|
||||
})
|
||||
.await
|
||||
.map_err(|err| io::Error::other(format!("blocking dst dir group open failed: {err}")))??;
|
||||
let (result_rx, worker) = DST_DIR_FSYNC_GROUP_COMMIT.enqueue_opened(opened, namespace_owner)?;
|
||||
let (result_rx, worker) = DST_DIR_FSYNC_GROUP_COMMIT.enqueue_opened(opened, namespace_owner, admission)?;
|
||||
if let Some(group) = worker {
|
||||
tokio::spawn(run_dst_dir_fsync_group_worker(group));
|
||||
tokio::spawn(run_dst_dir_fsync_group_worker(group, &FILE_SYNC_PERMITS));
|
||||
}
|
||||
|
||||
match result_rx.await {
|
||||
@@ -1415,9 +1429,8 @@ pub(crate) async fn fsync_commit_directory(
|
||||
.ok_or_else(|| io::Error::other("commit directory was not published"))?
|
||||
.file
|
||||
.clone();
|
||||
if !dst_dir_fsync_group_commit_enabled()
|
||||
&& let Some(admission) = admission
|
||||
{
|
||||
let grouped = dst_dir_fsync_group_commit_enabled();
|
||||
if !grouped && let Some(admission) = admission {
|
||||
let dir = dir.to_path_buf();
|
||||
return run_blocking_namespace_file_sync_operation(lease, admission, move || {
|
||||
#[cfg(test)]
|
||||
@@ -1426,7 +1439,7 @@ pub(crate) async fn fsync_commit_directory(
|
||||
})
|
||||
.await;
|
||||
}
|
||||
fsync_dst_dir_group_commit_opened(dir, dst_dir_fsync_group_commit_enabled(), Some(lease), Some(file)).await
|
||||
fsync_dst_dir_group_commit_opened(dir, grouped, Some(lease), Some(file), admission).await
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
@@ -1453,7 +1466,7 @@ pub(crate) async fn fsync_dst_dir_group_commit_or_namespace_file_sync_limit(
|
||||
admission: &FileSyncAdmission,
|
||||
) -> io::Result<()> {
|
||||
if dst_dir_fsync_group_commit_enabled() {
|
||||
fsync_dst_dir_group_commit_with_enabled(dir, true, Some(lease)).await
|
||||
fsync_dst_dir_group_commit_opened(dir.as_ref(), true, Some(lease), None, Some(admission)).await
|
||||
} else {
|
||||
fsync_dir_with_namespace_file_sync_limit(dir, lease, admission).await
|
||||
}
|
||||
@@ -2328,9 +2341,10 @@ static FSYNC_RUNTIME: LazyLock<Option<tokio::runtime::Runtime>> = LazyLock::new(
|
||||
if threads <= 1 {
|
||||
return None;
|
||||
}
|
||||
let workers = crate::runtime::detect_worker_parallelism().get().min(8);
|
||||
let mut builder = tokio::runtime::Builder::new_multi_thread();
|
||||
builder
|
||||
.worker_threads(num_cpus::get().min(8))
|
||||
.worker_threads(workers)
|
||||
.max_blocking_threads(threads)
|
||||
.thread_name("rustfs-fsync")
|
||||
.thread_stack_size(512 * 1024)
|
||||
@@ -2666,7 +2680,7 @@ fn default_global_file_sync_limit(cpu_count: usize, max_blocking_threads: usize)
|
||||
fn global_file_sync_limit() -> usize {
|
||||
let max_blocking_threads =
|
||||
rustfs_utils::get_env_usize(rustfs_config::ENV_MAX_BLOCKING_THREADS, rustfs_config::DEFAULT_MAX_BLOCKING_THREADS);
|
||||
default_global_file_sync_limit(num_cpus::get(), max_blocking_threads)
|
||||
default_global_file_sync_limit(crate::runtime::detect_worker_parallelism().get(), max_blocking_threads)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -5845,15 +5859,7 @@ async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: S
|
||||
global_permits: &Semaphore,
|
||||
operation: impl FnOnce(&dyn Fn() -> bool) -> io::Result<T> + Send + 'static,
|
||||
) -> io::Result<T> {
|
||||
let wait_started = rustfs_io_metrics::put_stage_timer();
|
||||
let global_permit = global_permits
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| io::Error::other("global file sync concurrency limiter closed"))?;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_GLOBAL_FILE_SYNC_PERMIT_WAIT,
|
||||
wait_started,
|
||||
);
|
||||
let global_permit = acquire_global_file_sync_permit(global_permits).await?;
|
||||
let disk_permit = admission.disk_permit.clone();
|
||||
let queue = Arc::clone(&lease.blocking_queue);
|
||||
let result = queue
|
||||
@@ -5867,6 +5873,19 @@ async fn run_cancellable_blocking_namespace_file_sync_operation_with_global<T: S
|
||||
result
|
||||
}
|
||||
|
||||
async fn acquire_global_file_sync_permit(global_permits: &Semaphore) -> io::Result<SemaphorePermit<'_>> {
|
||||
let wait_started = rustfs_io_metrics::put_stage_timer();
|
||||
let permit = global_permits
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| io::Error::other("global file sync concurrency limiter closed"))?;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_GLOBAL_FILE_SYNC_PERMIT_WAIT,
|
||||
wait_started,
|
||||
);
|
||||
Ok(permit)
|
||||
}
|
||||
|
||||
pub(crate) async fn fsync_dir_with_namespace_file_sync_limit(
|
||||
dir: impl AsRef<Path>,
|
||||
lease: Arc<NamespaceMutationLease>,
|
||||
@@ -12306,11 +12325,20 @@ mod tests {
|
||||
let second_owner = second_ctx.begin_namespace_commit();
|
||||
let first_probe = Arc::downgrade(&first_owner);
|
||||
let second_probe = Arc::downgrade(&second_owner);
|
||||
let disk_permits = Arc::new(Semaphore::new(2));
|
||||
let first_admission = acquire_file_sync_admission(disk_permits.clone())
|
||||
.await
|
||||
.expect("first disk slot");
|
||||
let second_admission = acquire_file_sync_admission(disk_permits.clone())
|
||||
.await
|
||||
.expect("second disk slot");
|
||||
let global_permits = Arc::new(Semaphore::new(1));
|
||||
let (first_rx, group) = with_background_resource_unit(resources[0].acquire().await, async {
|
||||
DST_DIR_FSYNC_GROUP_COMMIT
|
||||
.enqueue_opened(
|
||||
OpenedDstDirFsyncGroup::open(&dir).expect("open first waiter directory"),
|
||||
Some(first_owner),
|
||||
Some(&first_admission),
|
||||
)
|
||||
.expect("queue first real waiter")
|
||||
})
|
||||
@@ -12321,6 +12349,7 @@ mod tests {
|
||||
.enqueue_opened(
|
||||
OpenedDstDirFsyncGroup::open(&dir).expect("open second waiter directory"),
|
||||
Some(second_owner),
|
||||
Some(&second_admission),
|
||||
)
|
||||
.expect("queue second real waiter")
|
||||
})
|
||||
@@ -12334,12 +12363,18 @@ mod tests {
|
||||
let _ = entered_tx.send(());
|
||||
let _ = release_rx.recv();
|
||||
});
|
||||
let worker = tokio::spawn(run_dst_dir_fsync_group_worker(group.clone()));
|
||||
drop((first_admission, second_admission));
|
||||
let worker = tokio::spawn({
|
||||
let group = group.clone();
|
||||
let global_permits = global_permits.clone();
|
||||
async move { run_dst_dir_fsync_group_worker(group, &global_permits).await }
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(5), entered_rx)
|
||||
.await
|
||||
.expect("batch must reach its physical fsync")
|
||||
.expect("physical fsync entry");
|
||||
assert_eq!(fsync_dir_recorder::grouped_batch_sizes(&dir), vec![2]);
|
||||
assert_eq!(global_permits.available_permits(), 0, "one physical sync must reserve the global slot");
|
||||
assert!(
|
||||
group.inner.lock().pending.is_empty(),
|
||||
"both waiters were transferred into the physical batch"
|
||||
@@ -12353,6 +12388,7 @@ mod tests {
|
||||
.enqueue_opened(
|
||||
OpenedDstDirFsyncGroup::open(&dir).expect("open queued waiter directory"),
|
||||
Some(queued_owner),
|
||||
None,
|
||||
)
|
||||
.expect("queue a waiter after the physical batch was frozen")
|
||||
})
|
||||
@@ -12372,6 +12408,8 @@ mod tests {
|
||||
let first_pending = first_ctx.namespace_commits_pending() && first_probe.upgrade().is_some();
|
||||
let second_pending = second_ctx.namespace_commits_pending() && second_probe.upgrade().is_some();
|
||||
let retained_resources = resources.each_ref().map(|gate| gate.snapshot().active);
|
||||
let retained_disk_permits = disk_permits.available_permits();
|
||||
let released_global_permits = global_permits.available_permits();
|
||||
let generations = (first_ctx.namespace_commit_generation(), second_ctx.namespace_commit_generation());
|
||||
drop(release_tx);
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
@@ -12401,6 +12439,38 @@ mod tests {
|
||||
assert!(!second_ctx.namespace_commits_pending());
|
||||
assert!(first_ctx.namespace_commit_generation() > generations.0);
|
||||
assert!(second_ctx.namespace_commit_generation() > generations.1);
|
||||
assert_eq!(retained_disk_permits, 0, "both disk slots must survive abort while the syscall runs");
|
||||
assert_eq!(released_global_permits, 1, "abort must restore capacity for other disks");
|
||||
assert_eq!(disk_permits.available_permits(), 2, "both disk slots return after fsync");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(dst_dir_fsync_group_commit)]
|
||||
async fn grouped_fsync_propagates_closed_global_limit_without_syncing() {
|
||||
let directory = tempdir().expect("fixture directory");
|
||||
let disk_permits = Arc::new(Semaphore::new(1));
|
||||
let admission = acquire_file_sync_admission(disk_permits.clone()).await.expect("disk slot");
|
||||
let (result, worker) = DST_DIR_FSYNC_GROUP_COMMIT
|
||||
.enqueue_opened(
|
||||
OpenedDstDirFsyncGroup::open(directory.path()).expect("open fixture"),
|
||||
None,
|
||||
Some(&admission),
|
||||
)
|
||||
.expect("enqueue waiter");
|
||||
drop(admission);
|
||||
let global_permits = Semaphore::new(0);
|
||||
global_permits.close();
|
||||
run_dst_dir_fsync_group_worker(worker.expect("first waiter starts worker"), &global_permits).await;
|
||||
|
||||
let error = result
|
||||
.await
|
||||
.expect("worker reports completion")
|
||||
.expect_err("closed limiter must reject fsync");
|
||||
assert_eq!(&*error.message, "global file sync concurrency limiter closed");
|
||||
assert!(!fsync_dir_recorder::was_fsynced(directory.path()));
|
||||
assert_eq!(disk_permits.available_permits(), 1);
|
||||
assert_eq!(DST_DIR_FSYNC_GROUP_COMMIT.counts_for_test(), (0, 0));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -12416,10 +12486,11 @@ mod tests {
|
||||
.enqueue_opened(
|
||||
OpenedDstDirFsyncGroup::open(temp_dir.path()).expect("open queued waiter directory"),
|
||||
Some(owner),
|
||||
None,
|
||||
)
|
||||
.expect("queue a real waiter");
|
||||
let group = group.expect("first waiter starts the group");
|
||||
let worker = run_dst_dir_fsync_group_worker(group.clone());
|
||||
let worker = run_dst_dir_fsync_group_worker(group.clone(), &FILE_SYNC_PERMITS);
|
||||
assert!(ctx.namespace_commits_pending());
|
||||
drop(worker);
|
||||
assert!(rx.await.is_err(), "shutdown before first poll must release the waiter");
|
||||
@@ -12496,9 +12567,12 @@ mod tests {
|
||||
.enqueue_for_test(temp_dir.path())
|
||||
.expect("enqueue old group");
|
||||
let old_group = old_worker.expect("old group starts a worker");
|
||||
tokio::time::timeout(Duration::from_secs(5), run_dst_dir_fsync_group_worker(old_group.clone()))
|
||||
.await
|
||||
.expect("old worker must finish its actual fsync");
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
run_dst_dir_fsync_group_worker(old_group.clone(), &FILE_SYNC_PERMITS),
|
||||
)
|
||||
.await
|
||||
.expect("old worker must finish its actual fsync");
|
||||
assert!(old_rx.await.expect("old worker reports completion").is_ok());
|
||||
assert!(fsync_dir_recorder::was_fsynced(temp_dir.path()));
|
||||
assert_eq!(fsync_dir_recorder::grouped_batch_sizes(temp_dir.path()), vec![1]);
|
||||
@@ -12512,11 +12586,12 @@ mod tests {
|
||||
.enqueue_opened(
|
||||
OpenedDstDirFsyncGroup::open(temp_dir.path()).expect("open successor directory"),
|
||||
Some(owner),
|
||||
None,
|
||||
)
|
||||
.expect("enqueue successor owner");
|
||||
let successor = successor_worker.expect("successor starts a new group");
|
||||
assert!(!Arc::ptr_eq(&old_group, &successor));
|
||||
let worker = run_dst_dir_fsync_group_worker(successor.clone());
|
||||
let worker = run_dst_dir_fsync_group_worker(successor.clone(), &FILE_SYNC_PERMITS);
|
||||
// The stale Arc represents W1 resuming after another worker removed G.
|
||||
DST_DIR_FSYNC_GROUP_COMMIT.remove_idle_group(&old_group);
|
||||
assert!(ctx.namespace_commits_pending());
|
||||
@@ -14665,8 +14740,17 @@ mod tests {
|
||||
q_fsync
|
||||
.run_fsync_cancellable(|is_cancelled| {
|
||||
assert!(!is_cancelled());
|
||||
if FSYNC_RUNTIME.is_some() {
|
||||
let blocking_threads = rustfs_utils::get_env_usize(
|
||||
rustfs_config::ENV_FSYNC_BLOCKING_THREADS,
|
||||
rustfs_config::DEFAULT_FSYNC_BLOCKING_THREADS,
|
||||
);
|
||||
if blocking_threads > 1 {
|
||||
let runtime = FSYNC_RUNTIME.as_ref().expect("configured dedicated fsync runtime");
|
||||
assert_eq!(std::thread::current().name(), Some("rustfs-fsync"));
|
||||
let expected = std::thread::available_parallelism().map_or(1, usize::from).min(8);
|
||||
assert_eq!(runtime.metrics().num_workers(), expected);
|
||||
} else {
|
||||
assert!(FSYNC_RUNTIME.is_none());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
|
||||
@@ -110,29 +110,24 @@ pub fn compression_index_storage_bytes(index: &Index) -> Bytes {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes one complete stored compression index for Range GET planning.
|
||||
pub fn decode_compression_index_bytes(bytes: &Bytes) -> Option<Index> {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
{
|
||||
if let Some(decoded) = decode_minio_index_bytes(bytes) {
|
||||
return Some(decoded);
|
||||
}
|
||||
}
|
||||
|
||||
// Check the legacy frame before attempting to restore a headerless S2
|
||||
// index. Metadata contains exactly one index, so reject partial parses.
|
||||
let mut decoded = Index::new();
|
||||
if decoded.load(bytes.as_ref()).is_ok() {
|
||||
if decoded.load(bytes.as_ref()).is_ok_and(|remaining| remaining.is_empty()) {
|
||||
return Some(decoded);
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
{
|
||||
let restored = restore_legacy_index_headers(bytes.as_ref());
|
||||
let mut decoded = Index::new();
|
||||
if decoded.load(&restored).is_ok() {
|
||||
return Some(decoded);
|
||||
}
|
||||
decode_minio_index_bytes(bytes)
|
||||
}
|
||||
|
||||
None
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compression_reader<R>(reader: R, algorithm: CompressionAlgorithm, encrypted: bool) -> CompressReader<R>
|
||||
@@ -298,30 +293,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
fn restore_legacy_index_headers(bytes: &[u8]) -> Vec<u8> {
|
||||
if bytes.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
const S2_INDEX_HEADER: &[u8] = b"s2idx\x00";
|
||||
const S2_INDEX_TRAILER: &[u8] = b"\x00xdi2s";
|
||||
let mut restored = Vec::with_capacity(4 + S2_INDEX_HEADER.len() + bytes.len() + 4 + S2_INDEX_TRAILER.len());
|
||||
restored.extend_from_slice(&[0x99, 0x2A, 0x4D, 0x18]);
|
||||
restored.extend_from_slice(S2_INDEX_HEADER);
|
||||
restored.extend_from_slice(bytes);
|
||||
|
||||
let total_size = (restored.len() + 4 + S2_INDEX_TRAILER.len()) as u32;
|
||||
restored.extend_from_slice(&total_size.to_le_bytes());
|
||||
restored.extend_from_slice(S2_INDEX_TRAILER);
|
||||
|
||||
let chunk_len = restored.len() - 4;
|
||||
restored[1] = chunk_len as u8;
|
||||
restored[2] = (chunk_len >> 8) as u8;
|
||||
restored[3] = (chunk_len >> 16) as u8;
|
||||
restored
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct WriteEncryption {
|
||||
key_bytes: [u8; 32],
|
||||
|
||||
@@ -73,6 +73,8 @@ impl TryFrom<&str> for Endpoint {
|
||||
|
||||
/// Performs the conversion.
|
||||
fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
|
||||
const INVALID_URL_PORT: &str = "invalid URL endpoint format: port number must be between 1 to 65535";
|
||||
|
||||
// check whether given path is not empty.
|
||||
if ["", "/", "\\"].iter().any(|&v| v.eq(value)) {
|
||||
return Err(Error::other("empty or root endpoint is not supported"));
|
||||
@@ -80,6 +82,7 @@ impl TryFrom<&str> for Endpoint {
|
||||
|
||||
let mut is_local = false;
|
||||
let url = match Url::parse(value) {
|
||||
Ok(url) if url.port() == Some(0) => return Err(Error::other(INVALID_URL_PORT)),
|
||||
#[allow(unused_mut)]
|
||||
Ok(mut url) if url.has_host() => {
|
||||
// URL style of endpoint.
|
||||
@@ -139,9 +142,7 @@ impl TryFrom<&str> for Endpoint {
|
||||
url_parse_from_file_path(value)?
|
||||
}
|
||||
Err(e) => match e {
|
||||
ParseError::InvalidPort => {
|
||||
return Err(Error::other("invalid URL endpoint format: port number must be between 1 to 65535"));
|
||||
}
|
||||
ParseError::InvalidPort => return Err(Error::other(INVALID_URL_PORT)),
|
||||
ParseError::EmptyHost => return Err(Error::other("invalid URL endpoint format: empty host name")),
|
||||
ParseError::RelativeUrlWithoutBase => {
|
||||
// like /foo
|
||||
@@ -450,6 +451,12 @@ mod test {
|
||||
expected_type: Some(EndpointType::Url),
|
||||
expected_err: None,
|
||||
},
|
||||
TestCase {
|
||||
arg: "http://127.0.0.1:0/path",
|
||||
expected_endpoint: None,
|
||||
expected_type: None,
|
||||
expected_err: Some(Error::other("invalid URL endpoint format: port number must be between 1 to 65535")),
|
||||
},
|
||||
TestCase {
|
||||
arg: "https://93.184.216.34:808080/path",
|
||||
expected_endpoint: None,
|
||||
|
||||
@@ -21,20 +21,25 @@ use rustfs_config::{
|
||||
ENV_KUBERNETES_SERVICE_HOST, ENV_LOCAL_ENDPOINT_HOST, ENV_MINIO_CI, ENV_STARTUP_TOPOLOGY_RETRY_MAX_DELAY,
|
||||
ENV_STARTUP_TOPOLOGY_WAIT_MODE, ENV_STARTUP_TOPOLOGY_WAIT_TIMEOUT, ENV_UNSAFE_BYPASS_DISK_CHECK,
|
||||
};
|
||||
use rustfs_utils::{XHost, check_local_server_addr, get_env_opt_str, get_host_ip, is_local_host};
|
||||
use rustfs_utils::{XHost, check_local_server_addr, get_env_opt_str, is_local_ip};
|
||||
#[cfg(test)]
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
collections::{BTreeMap, BTreeSet, HashMap, HashSet, hash_map::Entry},
|
||||
future::Future,
|
||||
io::{Error, ErrorKind, Result},
|
||||
net::IpAddr,
|
||||
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::time::sleep as async_sleep;
|
||||
use tokio::time::{Instant as TokioInstant, sleep as async_sleep, sleep_until};
|
||||
use tracing::{error, info, instrument, warn};
|
||||
use url::Host;
|
||||
|
||||
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
|
||||
const LOG_SUBSYSTEM_ENDPOINT_TOPOLOGY: &str = "endpoint_topology";
|
||||
const EVENT_STARTUP_ENDPOINT_DNS_FAILED: &str = "startup_endpoint_dns_failed";
|
||||
|
||||
/// enum for setup type.
|
||||
#[derive(PartialEq, Eq, Debug, Clone)]
|
||||
pub enum SetupType {
|
||||
@@ -196,18 +201,17 @@ struct PoolEndpointList {
|
||||
setup_type: SetupType,
|
||||
}
|
||||
|
||||
struct ResolvedStartupHost {
|
||||
addresses: HashSet<IpAddr>,
|
||||
is_local: bool,
|
||||
}
|
||||
|
||||
impl AsRef<Vec<Endpoints>> for PoolEndpointList {
|
||||
fn as_ref(&self) -> &Vec<Endpoints> {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl AsMut<Vec<Endpoints>> for PoolEndpointList {
|
||||
fn as_mut(&mut self) -> &mut Vec<Endpoints> {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl PoolEndpointList {
|
||||
/// Creates a list of endpoints per pool, resolves their relevant hostnames
|
||||
/// and discovers whether those are local or remote.
|
||||
@@ -322,76 +326,41 @@ impl PoolEndpointList {
|
||||
|
||||
let convergence_started = Instant::now();
|
||||
let dns_retry_deadline = DnsRetryDeadline::new(policy.wait_timeout, policy.retry_max_delay);
|
||||
if let Some(local_endpoint_host) = local_endpoint_host {
|
||||
let resolved_hosts = if let Some(local_endpoint_host) = local_endpoint_host {
|
||||
pool_endpoint_list.update_is_local_from_explicit_host(disks_layout, server_addr.port(), local_endpoint_host)?;
|
||||
HashMap::new()
|
||||
} else {
|
||||
pool_endpoint_list
|
||||
.update_is_local(server_addr.port(), &dns_retry_deadline)
|
||||
.await?;
|
||||
|
||||
// Collapse divergent local/remote verdicts for the same host:port that
|
||||
// orchestrated DNS churn can produce during startup, before any check
|
||||
// relies on the local flag.
|
||||
normalize_same_host_local_state(pool_endpoint_list.as_mut());
|
||||
}
|
||||
.resolve_startup_hosts(server_addr.port(), &dns_retry_deadline, lookup_startup_host_ips)
|
||||
.await?
|
||||
};
|
||||
|
||||
let mut total_endpoints = 0;
|
||||
let mut local_endpoints = 0;
|
||||
for endpoints in pool_endpoint_list.inner.iter_mut() {
|
||||
// Check whether same path is not used in endpoints of a host on different port.
|
||||
// This relies on resolving every host to its IP set, which can flap while a
|
||||
// Kubernetes headless service is still publishing records; defer it in
|
||||
// orchestrated mode and re-run the DNS-independent checks below.
|
||||
if !policy.is_orchestrated() {
|
||||
let mut path_ip_map: HashMap<String, HashSet<IpAddr>> = HashMap::new();
|
||||
let mut host_ip_cache: HashMap<Host<&str>, HashSet<IpAddr>> = HashMap::new();
|
||||
let mut path_ip_map: HashMap<String, Cow<'_, HashSet<IpAddr>>> = HashMap::new();
|
||||
for ep in endpoints.as_ref() {
|
||||
let Some(host) = ep.url.host() else {
|
||||
let Some(host) = ep.url.host_str().and_then(|host| resolved_hosts.get(host)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let host_ip_set = if let Some(set) = host_ip_cache.get(&host) {
|
||||
info!(
|
||||
target: "rustfs::ecstore::endpoints",
|
||||
host = %host,
|
||||
endpoint = %ep.to_string(),
|
||||
from = "cache",
|
||||
"Create pool endpoints host '{}' found in cache for endpoint '{}'", host, ep.to_string()
|
||||
);
|
||||
set.clone()
|
||||
} else {
|
||||
let ips = match resolve_host_ips_with_retry(host.clone(), &ep.to_string(), &dns_retry_deadline).await {
|
||||
Ok(ips) => ips,
|
||||
Err(e) => {
|
||||
error!("Create pool endpoints host {} not found, error:{}", host, e);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
info!(
|
||||
target: "rustfs::ecstore::endpoints",
|
||||
host = %host,
|
||||
endpoint = %ep.to_string(),
|
||||
from = "get_host_ip",
|
||||
"Create pool endpoints host '{}' resolved to ips {:?} for endpoint '{}'",
|
||||
host,
|
||||
ips,
|
||||
ep.to_string()
|
||||
);
|
||||
host_ip_cache.insert(host.clone(), ips.clone());
|
||||
ips
|
||||
};
|
||||
|
||||
let path = ep.get_file_path();
|
||||
match path_ip_map.entry(path) {
|
||||
Entry::Occupied(mut e) => {
|
||||
if e.get().intersection(&host_ip_set).count() > 0 {
|
||||
let path_key = e.key().clone();
|
||||
if !e.get().is_disjoint(&host.addresses) {
|
||||
return Err(Error::other(format!(
|
||||
"same path '{path_key}' can not be served by different port on same address"
|
||||
"same path '{}' can not be served by different port on same address",
|
||||
e.key()
|
||||
)));
|
||||
}
|
||||
e.get_mut().extend(host_ip_set.iter());
|
||||
e.get_mut().to_mut().extend(&host.addresses);
|
||||
}
|
||||
Entry::Vacant(e) => {
|
||||
e.insert(host_ip_set);
|
||||
e.insert(Cow::Borrowed(&host.addresses));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -414,13 +383,11 @@ impl PoolEndpointList {
|
||||
}
|
||||
|
||||
// Here all endpoints are URL style.
|
||||
let mut ep_path_set = HashSet::new();
|
||||
let mut local_server_host_set = HashSet::new();
|
||||
let mut local_port_set = HashSet::new();
|
||||
let mut local_endpoint_count = 0;
|
||||
|
||||
for ep in endpoints.as_ref() {
|
||||
ep_path_set.insert(ep.get_file_path());
|
||||
if ep.is_local && ep.url.has_host() {
|
||||
local_server_host_set.insert(ep.url.host());
|
||||
local_port_set.insert(ep.url.port());
|
||||
@@ -438,30 +405,20 @@ impl PoolEndpointList {
|
||||
}
|
||||
|
||||
// Add missing port in all endpoints.
|
||||
total_endpoints += endpoints.as_ref().len();
|
||||
for ep in endpoints.as_mut() {
|
||||
local_endpoints += usize::from(ep.is_local);
|
||||
if !ep.url.has_host() {
|
||||
unique_args.insert(format!("localhost:{}", server_addr.port()));
|
||||
continue;
|
||||
}
|
||||
match ep.url.port() {
|
||||
None => {
|
||||
if local_endpoint_host.is_none() {
|
||||
let _ = ep.url.set_port(Some(server_addr.port()));
|
||||
}
|
||||
}
|
||||
Some(port) => {
|
||||
// If endpoint is local, but port is different than serverAddrPort, then make it as remote.
|
||||
if ep.is_local && server_addr.port() != port {
|
||||
ep.is_local = false;
|
||||
}
|
||||
}
|
||||
if ep.url.port().is_none() && local_endpoint_host.is_none() {
|
||||
let _ = ep.url.set_port(Some(server_addr.port()));
|
||||
}
|
||||
unique_args.insert(ep.host_port());
|
||||
}
|
||||
}
|
||||
|
||||
validate_local_physical_disk_independence(pool_endpoint_list.as_ref())?;
|
||||
|
||||
let setup_type = match pool_endpoint_list.as_ref()[0].as_ref()[0].get_type() {
|
||||
EndpointType::Path => SetupType::Erasure,
|
||||
EndpointType::Url => match unique_args.len() {
|
||||
@@ -470,15 +427,25 @@ impl PoolEndpointList {
|
||||
},
|
||||
};
|
||||
|
||||
pool_endpoint_list.setup_type = setup_type;
|
||||
// A storage member can belong to just one pool, but it must own a slot somewhere in the topology.
|
||||
if local_endpoints == 0 {
|
||||
let local_port = server_addr.port();
|
||||
if local_endpoint_host.is_some() {
|
||||
return Err(Error::other(format!(
|
||||
"{ENV_LOCAL_ENDPOINT_HOST} does not match any distributed endpoint on the local server port {local_port}"
|
||||
)));
|
||||
}
|
||||
return Err(Error::new(
|
||||
ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"no local storage endpoints on the local server port {local_port}; \
|
||||
check that a host in RUSTFS_VOLUMES resolves to a local interface and uses the RUSTFS_ADDRESS port"
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let total_endpoints: usize = pool_endpoint_list.inner.iter().map(|eps| eps.as_ref().len()).sum();
|
||||
let local_endpoints = pool_endpoint_list
|
||||
.inner
|
||||
.iter()
|
||||
.flat_map(|eps| eps.as_ref())
|
||||
.filter(|ep| ep.is_local)
|
||||
.count();
|
||||
validate_local_physical_disk_independence(pool_endpoint_list.as_ref())?;
|
||||
pool_endpoint_list.setup_type = setup_type;
|
||||
info!(
|
||||
target: "rustfs::ecstore::endpoints",
|
||||
mode = ?policy.mode,
|
||||
@@ -492,34 +459,33 @@ impl PoolEndpointList {
|
||||
Ok(pool_endpoint_list)
|
||||
}
|
||||
|
||||
/// resolves all hosts and discovers which are local
|
||||
async fn update_is_local(&mut self, local_port: u16, dns_retry_deadline: &DnsRetryDeadline) -> Result<()> {
|
||||
self._update_is_local(local_port, dns_retry_deadline).await
|
||||
}
|
||||
|
||||
/// resolves all hosts and discovers which are local
|
||||
async fn _update_is_local(&mut self, local_port: u16, dns_retry_deadline: &DnsRetryDeadline) -> Result<()> {
|
||||
// Keep each successful answer for the whole startup so all drives and path checks agree.
|
||||
async fn resolve_startup_hosts(
|
||||
&mut self,
|
||||
local_port: u16,
|
||||
dns_retry_deadline: &DnsRetryDeadline,
|
||||
resolve: impl for<'a> AsyncFn(Host<&'a str>) -> Result<HashSet<IpAddr>>,
|
||||
) -> Result<HashMap<String, ResolvedStartupHost>> {
|
||||
let mut resolved_hosts: HashMap<String, ResolvedStartupHost> = HashMap::new();
|
||||
for endpoints in self.inner.iter_mut() {
|
||||
for ep in endpoints.as_mut() {
|
||||
match ep.url.host() {
|
||||
None => {
|
||||
ep.is_local = true;
|
||||
}
|
||||
Some(host) => {
|
||||
ep.is_local = resolve_local_host_with_retry(
|
||||
host,
|
||||
ep.url.port().unwrap_or_default(),
|
||||
local_port,
|
||||
&ep.to_string(),
|
||||
dns_retry_deadline,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
let (Some(host_name), Some(host)) = (ep.url.host_str(), ep.url.host()) else {
|
||||
ep.is_local = true;
|
||||
continue;
|
||||
};
|
||||
let is_local = if let Some(resolved) = resolved_hosts.get(host_name) {
|
||||
resolved.is_local
|
||||
} else {
|
||||
let addresses = resolve_startup_host_with_retry(host, &ep.to_string(), dns_retry_deadline, &resolve).await?;
|
||||
let is_local = addresses.iter().any(is_local_ip);
|
||||
resolved_hosts.insert(host_name.to_owned(), ResolvedStartupHost { addresses, is_local });
|
||||
is_local
|
||||
};
|
||||
ep.is_local = is_local && ep.url.port().is_none_or(|port| port == local_port);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Ok(resolved_hosts)
|
||||
}
|
||||
|
||||
fn update_is_local_from_explicit_host(
|
||||
@@ -529,7 +495,6 @@ impl PoolEndpointList {
|
||||
raw_local_host: &str,
|
||||
) -> Result<()> {
|
||||
let local_host = parse_explicit_local_endpoint_host(raw_local_host)?;
|
||||
let mut local_endpoint_found = false;
|
||||
let mut host_path_ports = HashMap::new();
|
||||
debug_assert_eq!(self.inner.len(), disks_layout.pools.len());
|
||||
|
||||
@@ -575,17 +540,9 @@ impl PoolEndpointList {
|
||||
entry.insert(endpoint_port);
|
||||
}
|
||||
}
|
||||
|
||||
local_endpoint_found |= endpoint.is_local;
|
||||
}
|
||||
}
|
||||
|
||||
if !local_endpoint_found {
|
||||
return Err(Error::other(format!(
|
||||
"{ENV_LOCAL_ENDPOINT_HOST} does not match any distributed endpoint on the local server port {local_port}"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -686,17 +643,21 @@ fn kernel_hostname_for_endpoint_identity() -> Result<String> {
|
||||
.map_err(|_| Error::new(ErrorKind::InvalidData, "kernel hostname is not valid UTF-8"))
|
||||
}
|
||||
|
||||
fn endpoint_is_local_host(host: Host<&str>, port: u16, local_port: u16) -> Result<bool> {
|
||||
async fn lookup_startup_host_ips(host: Host<&str>) -> Result<HashSet<IpAddr>> {
|
||||
#[cfg(test)]
|
||||
if local_host_resolution_timeout_forced(&host) {
|
||||
return Err(Error::new(ErrorKind::TimedOut, "resolver timeout"));
|
||||
}
|
||||
|
||||
is_local_host(host, port, local_port)
|
||||
match host {
|
||||
Host::Domain(domain) => Ok(tokio::net::lookup_host((domain, 0)).await?.map(|addr| addr.ip()).collect()),
|
||||
Host::Ipv4(ip) => Ok(HashSet::from([IpAddr::V4(ip)])),
|
||||
Host::Ipv6(ip) => Ok(HashSet::from([IpAddr::V6(ip)])),
|
||||
}
|
||||
}
|
||||
|
||||
struct DnsRetryDeadline {
|
||||
started: Instant,
|
||||
started: TokioInstant,
|
||||
timeout: Duration,
|
||||
max_delay: Duration,
|
||||
}
|
||||
@@ -704,7 +665,7 @@ struct DnsRetryDeadline {
|
||||
impl DnsRetryDeadline {
|
||||
fn new(timeout: Duration, max_delay: Duration) -> Self {
|
||||
Self {
|
||||
started: Instant::now(),
|
||||
started: TokioInstant::now(),
|
||||
timeout,
|
||||
max_delay,
|
||||
}
|
||||
@@ -718,6 +679,14 @@ impl DnsRetryDeadline {
|
||||
self.started.elapsed()
|
||||
}
|
||||
|
||||
fn expires_at(&self) -> Option<TokioInstant> {
|
||||
// Zero means one lookup with no retries. MAX is the unbounded orchestrated policy.
|
||||
if matches!(self.timeout, Duration::ZERO | Duration::MAX) {
|
||||
return None;
|
||||
}
|
||||
self.started.checked_add(self.timeout)
|
||||
}
|
||||
|
||||
fn bounded_delay(&self, delay: Duration) -> Option<Duration> {
|
||||
let remaining = self.timeout.saturating_sub(self.started.elapsed());
|
||||
if remaining.is_zero() {
|
||||
@@ -746,17 +715,16 @@ where
|
||||
RetryLog: FnMut(u32, Duration, Duration, &Error),
|
||||
{
|
||||
let mut attempts: u32 = 0;
|
||||
let mut last_warn: Option<Instant> = None;
|
||||
|
||||
loop {
|
||||
match resolve().await {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(err) => {
|
||||
if !is_retryable_dns_error(&err) {
|
||||
return Err(permanent_error(err));
|
||||
}
|
||||
|
||||
let result = {
|
||||
let retry = async {
|
||||
let mut last_warn: Option<Instant> = None;
|
||||
loop {
|
||||
attempts += 1;
|
||||
let err = match resolve().await {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(err) if is_retryable_dns_error(&err) => err,
|
||||
Err(err) => return Err(permanent_error(err)),
|
||||
};
|
||||
let Some(delay) = dns_retry_deadline.bounded_delay(dns_retry_delay(attempts, dns_retry_deadline.max_delay))
|
||||
else {
|
||||
return Err(timeout_error(attempts, dns_retry_deadline.timeout(), err));
|
||||
@@ -770,8 +738,25 @@ where
|
||||
}
|
||||
sleep(delay).await;
|
||||
}
|
||||
};
|
||||
|
||||
match dns_retry_deadline.expires_at() {
|
||||
Some(expires_at) if expires_at <= TokioInstant::now() => None,
|
||||
Some(expires_at) => tokio::select! {
|
||||
biased;
|
||||
() = sleep_until(expires_at) => None,
|
||||
result = retry => Some(result),
|
||||
},
|
||||
None => Some(retry.await),
|
||||
}
|
||||
}
|
||||
};
|
||||
result.unwrap_or_else(|| {
|
||||
Err(timeout_error(
|
||||
attempts,
|
||||
dns_retry_deadline.timeout(),
|
||||
Error::new(ErrorKind::TimedOut, "startup DNS deadline elapsed"),
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Action-oriented tail shared by topology convergence timeout errors so a
|
||||
@@ -781,26 +766,30 @@ const TOPOLOGY_TIMEOUT_HINT: &str = "check DNS and /etc/hosts resolution, the ht
|
||||
and that all peer nodes have started; on Kubernetes/orchestrated deployments set \
|
||||
RUSTFS_STARTUP_TOPOLOGY_WAIT_MODE=orchestrated to keep waiting instead of exiting";
|
||||
|
||||
async fn resolve_local_host_with_retry(
|
||||
async fn resolve_startup_host_with_retry(
|
||||
host: Host<&str>,
|
||||
port: u16,
|
||||
local_port: u16,
|
||||
context: &str,
|
||||
dns_retry_deadline: &DnsRetryDeadline,
|
||||
) -> Result<bool> {
|
||||
resolve: &impl for<'a> AsyncFn(Host<&'a str>) -> Result<HashSet<IpAddr>>,
|
||||
) -> Result<HashSet<IpAddr>> {
|
||||
retry_dns_operation(
|
||||
|| {
|
||||
let host = host.clone();
|
||||
async move { endpoint_is_local_host(host, port, local_port) }
|
||||
},
|
||||
|| resolve(host.clone()),
|
||||
async_sleep,
|
||||
dns_retry_deadline,
|
||||
|err| Error::other(format!("endpoint '{context}' local-host detection failed for host '{host}': {err}")),
|
||||
|attempts, timeout, err| {
|
||||
Error::other(format!(
|
||||
"endpoint '{context}' local-host detection did not converge for host '{host}' after {attempts} attempts \
|
||||
let kind = if timeout.is_zero() {
|
||||
ErrorKind::Other
|
||||
} else {
|
||||
ErrorKind::TimedOut
|
||||
};
|
||||
Error::new(
|
||||
kind,
|
||||
format!(
|
||||
"endpoint '{context}' local-host detection did not converge for host '{host}' after {attempts} attempts \
|
||||
over {timeout:?} (stage=local_host_detection): {err}. {TOPOLOGY_TIMEOUT_HINT}"
|
||||
))
|
||||
),
|
||||
)
|
||||
},
|
||||
|attempts, delay, elapsed, err| {
|
||||
warn!(
|
||||
@@ -817,42 +806,18 @@ over {timeout:?} (stage=local_host_detection): {err}. {TOPOLOGY_TIMEOUT_HINT}"
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn resolve_host_ips_with_retry(
|
||||
host: Host<&str>,
|
||||
context: &str,
|
||||
dns_retry_deadline: &DnsRetryDeadline,
|
||||
) -> Result<HashSet<IpAddr>> {
|
||||
retry_dns_operation(
|
||||
|| {
|
||||
let host = host.clone();
|
||||
async move { get_host_ip(host).await }
|
||||
},
|
||||
async_sleep,
|
||||
dns_retry_deadline,
|
||||
|err| Error::other(format!("endpoint '{context}' host '{host}' cannot resolve: {err}")),
|
||||
|attempts, timeout, err| {
|
||||
Error::other(format!(
|
||||
"endpoint '{context}' host '{host}' DNS resolution did not converge after {attempts} attempts over \
|
||||
{timeout:?} (stage=host_ip_resolution): {err}. {TOPOLOGY_TIMEOUT_HINT}"
|
||||
))
|
||||
},
|
||||
|attempts, delay, elapsed, err| {
|
||||
warn!(
|
||||
target = "rustfs::ecstore::endpoints",
|
||||
stage = "host_ip_resolution",
|
||||
context = %context,
|
||||
host = %host,
|
||||
attempt = attempts,
|
||||
delay_ms = delay.as_millis(),
|
||||
elapsed_ms = elapsed.as_millis(),
|
||||
error = %err,
|
||||
"retrying endpoint DNS resolution after temporary error"
|
||||
);
|
||||
},
|
||||
)
|
||||
.await
|
||||
.inspect_err(|err| {
|
||||
error!(
|
||||
target: "rustfs::ecstore::endpoints",
|
||||
event = EVENT_STARTUP_ENDPOINT_DNS_FAILED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_ENDPOINT_TOPOLOGY,
|
||||
state = "failed",
|
||||
host = %host,
|
||||
error_kind = ?err.kind(),
|
||||
"Startup endpoint DNS resolution failed"
|
||||
);
|
||||
})
|
||||
}
|
||||
|
||||
fn is_retryable_dns_error(err: &Error) -> bool {
|
||||
@@ -936,6 +901,26 @@ fn explicit_url_port(raw: &str) -> Result<Option<u16>> {
|
||||
port.parse().map(Some).map_err(|_| invalid())
|
||||
}
|
||||
|
||||
fn is_url_topology_with_non_literal_hosts(disks_layout: &DisksLayout) -> Result<bool> {
|
||||
let mut endpoints = disks_layout
|
||||
.pools
|
||||
.iter()
|
||||
.flat_map(|pool| pool.iter().flatten())
|
||||
.map(|endpoint| Endpoint::try_from(endpoint.as_str()));
|
||||
let Some(first) = endpoints.next().transpose()? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if first.get_type() != EndpointType::Url {
|
||||
return Ok(false);
|
||||
}
|
||||
for endpoint in std::iter::once(Ok(first)).chain(endpoints) {
|
||||
if !matches!(endpoint?.url.host(), Some(Host::Ipv4(_) | Host::Ipv6(_))) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn infer_kubernetes_local_endpoint_host(
|
||||
disks_layout: &DisksLayout,
|
||||
local_port: u16,
|
||||
@@ -1189,34 +1174,6 @@ fn parse_wait_duration(raw: &str) -> Option<Duration> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Collapses divergent local/remote verdicts for endpoints that share the same
|
||||
/// `host:port`. A `host:port` is a single network identity, so if any endpoint
|
||||
/// of the group resolved as local, all of them are local. This absorbs the
|
||||
/// transient inconsistency that orchestrated DNS churn can produce across the
|
||||
/// several drives exported by one host.
|
||||
fn normalize_same_host_local_state(pools: &mut [Endpoints]) {
|
||||
let mut local_hosts: HashSet<String> = HashSet::new();
|
||||
for endpoints in pools.iter() {
|
||||
for ep in endpoints.as_ref() {
|
||||
if ep.is_local && ep.url.has_host() {
|
||||
local_hosts.insert(ep.host_port());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if local_hosts.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for endpoints in pools.iter_mut() {
|
||||
for ep in endpoints.as_mut() {
|
||||
if !ep.is_local && ep.url.has_host() && local_hosts.contains(&ep.host_port()) {
|
||||
ep.is_local = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// represent endpoints in a given pool
|
||||
/// along with its setCount and setDriveCount.
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -1280,32 +1237,11 @@ impl EndpointServerPools {
|
||||
) -> Result<(EndpointServerPools, SetupType)> {
|
||||
let mut local_endpoint_host = get_env_opt_str(ENV_LOCAL_ENDPOINT_HOST);
|
||||
let mut policy_override = None;
|
||||
let first_endpoint = disks_layout
|
||||
.pools
|
||||
.iter()
|
||||
.flat_map(|pool| pool.iter().flatten())
|
||||
.next()
|
||||
.map(|endpoint| Endpoint::try_from(endpoint.as_str()))
|
||||
.transpose()?;
|
||||
let distributed = first_endpoint
|
||||
.as_ref()
|
||||
.is_some_and(|endpoint| endpoint.get_type() == EndpointType::Url);
|
||||
let mut all_distributed_hosts_are_ip_literals = distributed;
|
||||
if distributed {
|
||||
for raw_endpoint in disks_layout.pools.iter().flat_map(|pool| pool.iter().flatten()) {
|
||||
let endpoint = Endpoint::try_from(raw_endpoint.as_str())?;
|
||||
if !matches!(endpoint.url.host(), Some(Host::Ipv4(_) | Host::Ipv6(_))) {
|
||||
all_distributed_hosts_are_ip_literals = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let wait_mode = get_env_opt_str(ENV_STARTUP_TOPOLOGY_WAIT_MODE).map(|value| value.trim().to_ascii_lowercase());
|
||||
let infer_kubernetes_host = local_endpoint_host.is_none()
|
||||
&& distributed
|
||||
&& !all_distributed_hosts_are_ip_literals
|
||||
&& std::env::var_os(ENV_KUBERNETES_SERVICE_HOST).is_some()
|
||||
&& matches!(wait_mode.as_deref(), None | Some("") | Some("auto") | Some("orchestrated"));
|
||||
&& matches!(wait_mode.as_deref(), None | Some("") | Some("auto") | Some("orchestrated"))
|
||||
&& is_url_topology_with_non_literal_hosts(disks_layout)?;
|
||||
if infer_kubernetes_host {
|
||||
let kernel_hostname = kernel_hostname_for_endpoint_identity()?;
|
||||
let local_port = check_local_server_addr(server_addr)?.port();
|
||||
@@ -1317,7 +1253,7 @@ impl EndpointServerPools {
|
||||
policy_override = Some(StartupTopologyPolicy::resolve_from(
|
||||
Some("bounded"),
|
||||
true,
|
||||
distributed,
|
||||
true,
|
||||
get_env_opt_str(ENV_STARTUP_TOPOLOGY_WAIT_TIMEOUT).as_deref(),
|
||||
get_env_opt_str(ENV_STARTUP_TOPOLOGY_RETRY_MAX_DELAY).as_deref(),
|
||||
false,
|
||||
@@ -1788,7 +1724,7 @@ mod test {
|
||||
|
||||
#[tokio::test]
|
||||
async fn system_resolver_negative_result_reaches_the_dns_allowlist() {
|
||||
let Err(err) = get_host_ip(Host::Domain("rustfs-startup-negative.invalid")).await else {
|
||||
let Err(err) = lookup_startup_host_ips(Host::Domain("rustfs-startup-negative.invalid")).await else {
|
||||
// Some corporate and ISP resolvers synthesize an address for
|
||||
// unknown names, including the reserved .invalid suffix.
|
||||
return;
|
||||
@@ -1959,22 +1895,48 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_same_host_local_state_unifies_divergent_verdicts() {
|
||||
let mut d1 = Endpoint::try_from("http://node1:9000/d1").unwrap();
|
||||
let mut d2 = Endpoint::try_from("http://node1:9000/d2").unwrap();
|
||||
d1.is_local = true;
|
||||
d2.is_local = false; // divergent verdict for the same host:port
|
||||
let mut remote = Endpoint::try_from("http://node2:9000/d1").unwrap();
|
||||
remote.is_local = false;
|
||||
#[tokio::test]
|
||||
async fn startup_reuses_one_dns_answer_per_host_across_ports_and_pools() {
|
||||
let mut pools = PoolEndpointList {
|
||||
inner: vec![
|
||||
Endpoints::try_from(["http://node1:9000/d1", "http://node1:9000/d2", "http://node2:9000/d1"].as_slice())
|
||||
.expect("first pool endpoints should parse"),
|
||||
Endpoints::try_from(["http://node1:9000/d3", "http://node1:9001/d4"].as_slice())
|
||||
.expect("second pool endpoints should parse"),
|
||||
],
|
||||
setup_type: SetupType::Unknown,
|
||||
};
|
||||
let deadline = DnsRetryDeadline::new(Duration::ZERO, DNS_RETRY_MAX_DELAY);
|
||||
let node1_lookups = std::cell::Cell::new(0);
|
||||
let local_ip = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST);
|
||||
let stale_ip = IpAddr::V4(std::net::Ipv4Addr::new(192, 0, 2, 10));
|
||||
let resolve = async |host: Host<&str>| match host {
|
||||
Host::Domain("node1") => {
|
||||
let lookups = node1_lookups.get();
|
||||
node1_lookups.set(lookups + 1);
|
||||
Ok(HashSet::from([if lookups == 0 { stale_ip } else { local_ip }]))
|
||||
}
|
||||
Host::Domain("node2") => Ok(HashSet::from([stale_ip])),
|
||||
_ => panic!("unexpected hostname in test: {host}"),
|
||||
};
|
||||
|
||||
let mut pools = vec![Endpoints::from(vec![d1, d2, remote])];
|
||||
normalize_same_host_local_state(&mut pools);
|
||||
let first_start = pools
|
||||
.resolve_startup_hosts(9000, &deadline, resolve)
|
||||
.await
|
||||
.expect("first lookup");
|
||||
assert_eq!(node1_lookups.get(), 1);
|
||||
assert_eq!(first_start["node1"].addresses, HashSet::from([stale_ip]));
|
||||
assert_eq!(local_flags(&pools.inner[0]), [false, false, false]);
|
||||
assert_eq!(local_flags(&pools.inner[1]), [false, false]);
|
||||
|
||||
let eps = pools[0].as_ref();
|
||||
assert!(eps[0].is_local);
|
||||
assert!(eps[1].is_local, "same host:port must inherit the local verdict");
|
||||
assert!(!eps[2].is_local, "a genuinely remote host must stay remote");
|
||||
let restart = pools
|
||||
.resolve_startup_hosts(9000, &deadline, resolve)
|
||||
.await
|
||||
.expect("fresh lookup");
|
||||
assert_eq!(node1_lookups.get(), 2);
|
||||
assert_eq!(restart["node1"].addresses, HashSet::from([local_ip]));
|
||||
assert_eq!(local_flags(&pools.inner[0]), [true, true, false]);
|
||||
assert_eq!(local_flags(&pools.inner[1]), [true, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2020,11 +1982,11 @@ mod test {
|
||||
// trip the DNS-IP cross-port check in bounded mode but must be deferred
|
||||
// (allowed) in orchestrated mode, where headless-service records can
|
||||
// still be flapping.
|
||||
let args = vec![
|
||||
let args = [
|
||||
"http://192.0.2.10:9000/export",
|
||||
"http://192.0.2.10:9001/export",
|
||||
"http://192.0.2.11:9000/export",
|
||||
"http://192.0.2.12:9000/export",
|
||||
"http://127.0.0.1:9000/export",
|
||||
];
|
||||
let layout = DisksLayout::from_volumes(args.as_slice()).unwrap();
|
||||
|
||||
@@ -2046,6 +2008,24 @@ mod test {
|
||||
assert_eq!(resolved.setup_type, SetupType::DistErasure);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_startup_when_no_endpoint_is_local() {
|
||||
for volumes in [
|
||||
["http://192.0.2.10:9000/data", "http://192.0.2.11:9000/data"],
|
||||
["http://192.0.2.10:9000/data", "http://127.0.0.1:9001/data"],
|
||||
["http://192.0.2.10:9000/data1", "http://192.0.2.10:9000/data2"],
|
||||
] {
|
||||
let layout = DisksLayout::from_volumes(&volumes).expect("URL topology should parse");
|
||||
for policy in [bounded_test_policy(), orchestrated_test_policy()] {
|
||||
let err = EndpointServerPools::create_server_endpoints_with("0.0.0.0:9000", &layout, Some(policy), None)
|
||||
.await
|
||||
.expect_err("startup must reject a topology with no local endpoints");
|
||||
assert_eq!(err.kind(), ErrorKind::InvalidInput);
|
||||
assert!(err.to_string().contains("no local storage endpoints"), "{err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_local_endpoint_host_accepts_only_a_canonical_host() {
|
||||
assert_eq!(
|
||||
@@ -2274,7 +2254,7 @@ mod test {
|
||||
|
||||
#[serial]
|
||||
#[tokio::test]
|
||||
async fn create_server_endpoints_infers_kubernetes_pod_host_without_peer_dns() {
|
||||
async fn create_server_endpoints_infers_kubernetes_host_after_literal_peer_without_dns() {
|
||||
let _kernel_hostname = force_kernel_hostname_for_test("rustfs-0");
|
||||
let local_host = "rustfs-0.rustfs-headless.ns.svc.cluster.local";
|
||||
|
||||
@@ -2288,14 +2268,16 @@ mod test {
|
||||
let (pools, setup_type) = EndpointServerPools::from_volumes(
|
||||
"0.0.0.0:9000",
|
||||
vec![
|
||||
"http://192.0.2.10:9000/data2".to_string(),
|
||||
format!("http://{local_host}:9000/data0"),
|
||||
"http://permanently-missing.invalid:9000/data1".to_string(),
|
||||
"http://192.0.2.11:9000/data3".to_string(),
|
||||
],
|
||||
)
|
||||
.await
|
||||
.expect("kernel hostname inference should avoid resolving the missing peer");
|
||||
|
||||
assert_eq!(local_flags(&pools.0[0].endpoints), vec![true, false]);
|
||||
assert_eq!(local_flags(&pools.0[0].endpoints), vec![false, true, false, false]);
|
||||
assert_eq!(setup_type, SetupType::DistErasure);
|
||||
},
|
||||
)
|
||||
@@ -2815,6 +2797,40 @@ mod test {
|
||||
assert!(err.to_string().contains("timed out after 1 attempts"));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn startup_dns_deadline_stops_pending_and_later_lookups() {
|
||||
let timeout = Duration::from_secs(3);
|
||||
let deadline = DnsRetryDeadline::new(timeout, DNS_RETRY_MAX_DELAY);
|
||||
let lookups = std::cell::Cell::new(0);
|
||||
let resolve = async |_host: Host<&str>| {
|
||||
lookups.set(lookups.get() + 1);
|
||||
std::future::pending::<Result<HashSet<IpAddr>>>().await
|
||||
};
|
||||
|
||||
let err = tokio::time::timeout(
|
||||
timeout * 2,
|
||||
resolve_startup_host_with_retry(Host::Domain("node1"), "first endpoint", &deadline, &resolve),
|
||||
)
|
||||
.await
|
||||
.expect("a pending lookup must complete before the test deadline")
|
||||
.expect_err("a pending lookup must stop at the startup deadline");
|
||||
assert_eq!(err.kind(), ErrorKind::TimedOut);
|
||||
assert!(err.to_string().contains("first endpoint"));
|
||||
assert!(err.to_string().contains("startup DNS deadline elapsed"));
|
||||
assert_eq!(deadline.elapsed(), timeout);
|
||||
assert_eq!(lookups.get(), 1);
|
||||
|
||||
let err = tokio::time::timeout(
|
||||
timeout * 2,
|
||||
resolve_startup_host_with_retry(Host::Domain("node2"), "second endpoint", &deadline, &resolve),
|
||||
)
|
||||
.await
|
||||
.expect("a later lookup must complete before the test deadline")
|
||||
.expect_err("an exhausted startup budget must prevent a new lookup");
|
||||
assert!(err.to_string().contains("second endpoint"));
|
||||
assert_eq!(lookups.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_endpoints() {
|
||||
let test_cases = [
|
||||
|
||||
@@ -14,8 +14,9 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[cfg(test)]
|
||||
use crate::io_support::rio::Index;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::{mem::MaybeUninit, task::ready};
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
const DARE_PAYLOAD_SIZE: i64 = 64 * 1024;
|
||||
@@ -41,11 +42,8 @@ pub(crate) fn restore_request_active(opts: &ObjectOptions) -> bool {
|
||||
restore.type_.is_some() || restore.days.is_some() || restore.output_location.is_some() || restore.select_parameters.is_some()
|
||||
}
|
||||
|
||||
fn decode_compression_index(index: Option<&Bytes>) -> Option<Index> {
|
||||
crate::io_support::rio::decode_compression_index_bytes(index?)
|
||||
}
|
||||
|
||||
fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
fn get_encrypted_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64, u64) {
|
||||
let mut skip_length = 0_i64;
|
||||
let mut cumulative_actual_size = 0_i64;
|
||||
let mut first_part_idx = 0_usize;
|
||||
@@ -63,30 +61,20 @@ fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64
|
||||
}
|
||||
|
||||
let mut part_skip = offset - skip_length;
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let (mut decrypt_skip, mut seq_num) = (0_i64, 0_u64);
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
let (decrypt_skip, seq_num) = (0_i64, 0_u64);
|
||||
|
||||
if part_skip > 0
|
||||
&& let Some(part) = oi.parts.get(first_part_idx)
|
||||
&& let Some(index) = decode_compression_index(part.index.as_ref())
|
||||
&& let Some(index) = part
|
||||
.index
|
||||
.as_ref()
|
||||
.and_then(crate::io_support::rio::decode_compression_index_bytes)
|
||||
&& let Ok((comp_off, uncomp_off)) = index.find(part_skip)
|
||||
&& comp_off > 0
|
||||
{
|
||||
#[cfg(feature = "rio-v2")]
|
||||
if oi.is_encrypted() {
|
||||
seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
|
||||
decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
|
||||
compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
|
||||
} else {
|
||||
compressed_offset += comp_off;
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
{
|
||||
compressed_offset += comp_off;
|
||||
}
|
||||
seq_num = (comp_off / DARE_PAYLOAD_SIZE) as u64;
|
||||
decrypt_skip = comp_off % DARE_PAYLOAD_SIZE;
|
||||
compressed_offset += (comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE;
|
||||
|
||||
part_skip -= uncomp_off;
|
||||
}
|
||||
@@ -94,6 +82,68 @@ fn get_compressed_offsets(oi: &ObjectInfo, offset: i64) -> (i64, i64, usize, i64
|
||||
(compressed_offset, part_skip, first_part_idx, decrypt_skip, seq_num)
|
||||
}
|
||||
|
||||
// Plan a window of complete compression blocks in stored coordinates. The
|
||||
// index can omit the final block or record a stale total. Part metadata owns
|
||||
// the actual bounds, and missing checkpoints widen only the covering parts.
|
||||
fn compressed_storage_window(oi: &ObjectInfo, offset: usize, length: i64) -> Option<(usize, i64, usize)> {
|
||||
let start = i64::try_from(offset).ok()?;
|
||||
let end = start.checked_add(length)?;
|
||||
if start >= end {
|
||||
return None;
|
||||
}
|
||||
let (mut plaintext_offset, mut stored_offset) = (0_i64, 0_i64);
|
||||
let mut window_start = None;
|
||||
for part in oi.parts.iter() {
|
||||
let stored_size = i64::try_from(part.size).ok()?;
|
||||
let stored_end = stored_offset.checked_add(stored_size)?;
|
||||
if stored_end > oi.size || part.actual_size < 0 || (part.actual_size == 0) != (stored_size == 0) {
|
||||
return None;
|
||||
}
|
||||
let plaintext_end = plaintext_offset.checked_add(part.actual_size)?;
|
||||
let starts_here = window_start.is_none() && start < plaintext_end;
|
||||
let ends_here = end <= plaintext_end;
|
||||
if starts_here || ends_here {
|
||||
let index = part
|
||||
.index
|
||||
.as_ref()
|
||||
.filter(|_| (starts_here && start > plaintext_offset) || (ends_here && end < plaintext_end))
|
||||
.and_then(crate::io_support::rio::decode_compression_index_bytes);
|
||||
if starts_here {
|
||||
let relative_start = start - plaintext_offset;
|
||||
let (stored, plaintext) = index
|
||||
.as_ref()
|
||||
.filter(|_| relative_start > 0)
|
||||
.and_then(|index| index.checkpoint_at_or_before(relative_start))
|
||||
.filter(|&(stored, plaintext)| {
|
||||
(1..stored_size).contains(&stored) && (0..=relative_start).contains(&plaintext)
|
||||
})
|
||||
.unwrap_or((0, 0));
|
||||
window_start = Some((stored_offset + stored, relative_start - plaintext));
|
||||
}
|
||||
if ends_here {
|
||||
let (window_start, skip) = window_start?;
|
||||
let relative_end = end - plaintext_offset;
|
||||
let window_end = index
|
||||
.filter(|_| relative_end < part.actual_size)
|
||||
.as_ref()
|
||||
.and_then(|index| index.checkpoint_at_or_after(relative_end))
|
||||
.filter(|&(stored, plaintext)| {
|
||||
(1..=stored_size).contains(&stored) && (relative_end..=part.actual_size).contains(&plaintext)
|
||||
})
|
||||
.map_or(stored_end, |(stored, _)| stored_offset + stored);
|
||||
return (window_end > window_start).then_some((
|
||||
usize::try_from(window_start).ok()?,
|
||||
window_end - window_start,
|
||||
usize::try_from(skip).ok()?,
|
||||
));
|
||||
}
|
||||
}
|
||||
plaintext_offset = plaintext_end;
|
||||
stored_offset = stored_end;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
fn get_encrypted_offsets(oi: &ObjectInfo, offset: i64) -> Result<(i64, usize, usize, u32, i64)> {
|
||||
if oi.parts.is_empty() {
|
||||
@@ -713,10 +763,12 @@ impl ReadPlan {
|
||||
let actual_size = oi.get_actual_size()?;
|
||||
let (storage_offset, storage_length, decompressed_offset, decompressed_length) = if let Some(rs) = rs {
|
||||
let (req_off, req_length) = rs.get_offset_length(actual_size)?;
|
||||
let (physical_off, decompressed_skip, _, _, _) = get_compressed_offsets(oi, req_off as i64);
|
||||
let storage_offset = usize::try_from(physical_off)
|
||||
.map_err(|_| Error::other(format!("invalid compressed offset {physical_off}")))?;
|
||||
(storage_offset, oi.size - physical_off, decompressed_skip as usize, req_length)
|
||||
let (storage_offset, storage_length, skip) = if req_length < actual_size {
|
||||
compressed_storage_window(oi, req_off, req_length).unwrap_or((0, oi.size, req_off))
|
||||
} else {
|
||||
(0, oi.size, req_off)
|
||||
};
|
||||
(storage_offset, storage_length, skip, req_length)
|
||||
} else {
|
||||
(0, oi.size, 0, actual_size)
|
||||
};
|
||||
@@ -794,7 +846,7 @@ impl ReadPlan {
|
||||
)?
|
||||
} else if is_compressed {
|
||||
let (physical_off, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
|
||||
get_compressed_offsets(oi, requested_offset as i64);
|
||||
get_encrypted_compressed_offsets(oi, requested_offset as i64);
|
||||
(
|
||||
usize::try_from(physical_off)
|
||||
.map_err(|_| Error::other(format!("invalid encrypted compressed offset {physical_off}")))?,
|
||||
@@ -910,40 +962,14 @@ impl ReadPlan {
|
||||
decompressed_length,
|
||||
total_plaintext_size,
|
||||
} => {
|
||||
let dec_reader = crate::io_support::rio::decompression_reader(reader, algorithm, backend);
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let dec_reader = StreamConsumer::new(dec_reader);
|
||||
let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> = if decompressed_offset > 0
|
||||
|| decompressed_length != total_plaintext_size as i64
|
||||
{
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let ranged_result = RangedDecompressReader::new_draining(
|
||||
dec_reader,
|
||||
decompressed_offset,
|
||||
decompressed_length,
|
||||
total_plaintext_size,
|
||||
);
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
let ranged_result =
|
||||
RangedDecompressReader::new(dec_reader, decompressed_offset, decompressed_length, total_plaintext_size);
|
||||
|
||||
match ranged_result {
|
||||
Ok(ranged_reader) => {
|
||||
tracing::debug!(
|
||||
"Successfully created RangedDecompressReader for offset={}, length={}",
|
||||
decompressed_offset,
|
||||
decompressed_length
|
||||
);
|
||||
Box::new(ranged_reader)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("RangedDecompressReader failed with invalid range parameters: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Box::new(HardLimitReader::new(dec_reader, decompressed_length))
|
||||
};
|
||||
let final_reader = compressed_object_reader(
|
||||
reader,
|
||||
algorithm,
|
||||
backend,
|
||||
decompressed_offset,
|
||||
decompressed_length,
|
||||
total_plaintext_size,
|
||||
)?;
|
||||
|
||||
let mut object_info = oi.clone();
|
||||
object_info.size = self.object_size;
|
||||
@@ -1019,29 +1045,14 @@ impl ReadPlan {
|
||||
|
||||
let final_reader: Box<dyn AsyncRead + Unpin + Send + Sync> =
|
||||
if let Some((algo, compression_backend)) = compression {
|
||||
let decompressed_reader =
|
||||
crate::io_support::rio::decompression_reader(decrypted_reader, algo, compression_backend);
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let decompressed_reader = StreamConsumer::new(decompressed_reader);
|
||||
if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let ranged_reader = RangedDecompressReader::new_draining(
|
||||
decompressed_reader,
|
||||
plaintext_offset,
|
||||
plaintext_length,
|
||||
total_plaintext_size,
|
||||
)?;
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
let ranged_reader = RangedDecompressReader::new(
|
||||
decompressed_reader,
|
||||
plaintext_offset,
|
||||
plaintext_length,
|
||||
total_plaintext_size,
|
||||
)?;
|
||||
Box::new(ranged_reader)
|
||||
} else {
|
||||
Box::new(HardLimitReader::new(decompressed_reader, total_plaintext_size_i64))
|
||||
}
|
||||
compressed_object_reader(
|
||||
decrypted_reader,
|
||||
algo,
|
||||
compression_backend,
|
||||
plaintext_offset,
|
||||
plaintext_length,
|
||||
total_plaintext_size,
|
||||
)?
|
||||
} else if plaintext_offset > 0 || plaintext_length != total_plaintext_size_i64 {
|
||||
Box::new(RangedDecompressReader::new(
|
||||
decrypted_reader,
|
||||
@@ -1118,294 +1129,201 @@ impl AsyncRead for GetObjectReader {
|
||||
}
|
||||
}
|
||||
|
||||
fn compressed_object_reader(
|
||||
source: Box<dyn AsyncRead + Unpin + Send + Sync>,
|
||||
algorithm: CompressionAlgorithm,
|
||||
backend: crate::io_support::rio::ReadCompressionBackend,
|
||||
offset: usize,
|
||||
length: i64,
|
||||
total_size: usize,
|
||||
) -> Result<Box<dyn AsyncRead + Unpin + Send + Sync>> {
|
||||
let decoded = crate::io_support::rio::decompression_reader(source, algorithm, backend);
|
||||
if offset != 0 || usize::try_from(length).ok() != Some(total_size) {
|
||||
// A partial response needs the blocks covering its bytes. Dropping the
|
||||
// source closes the producer instead of draining unrelated blocks.
|
||||
return Ok(Box::new(RangedDecompressReader::new(decoded, offset, length, total_size)?));
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
let decoded = StreamConsumer::new(decoded);
|
||||
Ok(Box::new(HardLimitReader::new(decoded, length)))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SkipReader<R> {
|
||||
inner: R,
|
||||
bytes_to_skip: usize,
|
||||
bytes_skipped: usize,
|
||||
scratch: Box<[MaybeUninit<u8>]>,
|
||||
remaining_skip: usize,
|
||||
scratch: Option<Box<[MaybeUninit<u8>]>>,
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync> SkipReader<R> {
|
||||
impl<R: AsyncRead + Unpin> SkipReader<R> {
|
||||
fn new(inner: R, bytes_to_skip: usize) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
bytes_to_skip,
|
||||
bytes_skipped: 0,
|
||||
scratch: Box::<[u8]>::new_uninit_slice(8192),
|
||||
remaining_skip: bytes_to_skip,
|
||||
scratch: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync> AsyncRead for SkipReader<R> {
|
||||
impl<R: AsyncRead + Unpin> AsyncRead for SkipReader<R> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
let this = self.as_mut().get_mut();
|
||||
if buf.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
while this.bytes_skipped < this.bytes_to_skip {
|
||||
let remaining = this.bytes_to_skip - this.bytes_skipped;
|
||||
let scratch_len = remaining.min(this.scratch.len());
|
||||
let mut scratch_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
|
||||
match Pin::new(&mut this.inner).poll_read(cx, &mut scratch_buf) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
|
||||
Poll::Ready(Ok(())) => {
|
||||
let n = scratch_buf.filled().len();
|
||||
if n == 0 {
|
||||
return Poll::Ready(Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
format!("unexpected EOF while skipping {} bytes from decrypted stream", this.bytes_to_skip),
|
||||
)));
|
||||
}
|
||||
this.bytes_skipped += n;
|
||||
if this.remaining_skip != 0 {
|
||||
let scratch_len = this.remaining_skip.min(8192);
|
||||
let scratch = this.scratch.get_or_insert_with(|| Box::<[u8]>::new_uninit_slice(scratch_len));
|
||||
while this.remaining_skip > 0 {
|
||||
// An unindexed range can skip many decoded blocks without the source yielding.
|
||||
let budget = ready!(tokio::task::coop::poll_proceed(cx));
|
||||
let len = this.remaining_skip.min(scratch.len());
|
||||
let mut discard = ReadBuf::uninit(&mut scratch[..len]);
|
||||
ready!(Pin::new(&mut this.inner).poll_read(cx, &mut discard))?;
|
||||
let n = discard.filled().len();
|
||||
if n == 0 {
|
||||
return Poll::Ready(Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
"object stream ended before reaching the range start",
|
||||
)));
|
||||
}
|
||||
this.remaining_skip -= n;
|
||||
budget.made_progress();
|
||||
}
|
||||
this.scratch = None;
|
||||
}
|
||||
|
||||
Pin::new(&mut this.inner).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
/// A streaming decompression reader that supports range requests by skipping data in the decompressed stream.
|
||||
/// This implementation acknowledges that compressed streams (like LZ4) must be decompressed sequentially
|
||||
/// from the beginning, so it streams and discards data until reaching the target offset.
|
||||
/// Reads a bounded plaintext range from a stream positioned at or before its start.
|
||||
/// The source is released when the range completes. An early source EOF is an error.
|
||||
#[derive(Debug)]
|
||||
pub struct RangedDecompressReader<R: AsyncRead + Unpin + Send + Sync + 'static> {
|
||||
inner: Option<R>,
|
||||
target_offset: usize,
|
||||
target_length: usize,
|
||||
current_offset: usize,
|
||||
bytes_returned: usize,
|
||||
scratch: Box<[MaybeUninit<u8>]>,
|
||||
inner: Option<tokio::io::Take<SkipReader<R>>>,
|
||||
drain_on_done: bool,
|
||||
drain_task: Option<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync + 'static> RangedDecompressReader<R> {
|
||||
/// Skips `offset` bytes and yields up to `length` bytes, capped by `total_size`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an invalid range error if the offset is outside the stream or the length is negative.
|
||||
pub fn new(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
|
||||
Self::new_with_drain(inner, offset, length, total_size, false)
|
||||
}
|
||||
|
||||
/// Reads like [Self::new] and drains any remainder in the background once the range completes.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the same range validation errors as [Self::new].
|
||||
pub fn new_draining(inner: R, offset: usize, length: i64, total_size: usize) -> Result<Self> {
|
||||
Self::new_with_drain(inner, offset, length, total_size, true)
|
||||
}
|
||||
|
||||
fn new_with_drain(inner: R, offset: usize, length: i64, total_size: usize, drain_on_done: bool) -> Result<Self> {
|
||||
// Validate the range request
|
||||
if offset >= total_size {
|
||||
tracing::debug!("Range offset {} exceeds total size {}", offset, total_size);
|
||||
return Err(Error::InvalidRangeSpec("Range offset exceeds file size".to_string()));
|
||||
}
|
||||
|
||||
// Adjust length if it extends beyond file end
|
||||
let actual_length = std::cmp::min(length as usize, total_size - offset);
|
||||
|
||||
tracing::debug!(
|
||||
"Creating RangedDecompressReader: offset={}, length={}, total_size={}, actual_length={}",
|
||||
offset,
|
||||
length,
|
||||
total_size,
|
||||
actual_length
|
||||
);
|
||||
let length =
|
||||
u64::try_from(length).map_err(|_| Error::InvalidRangeSpec("Range length must be nonnegative".to_string()))?;
|
||||
let length = length.min((total_size - offset) as u64);
|
||||
|
||||
Ok(Self {
|
||||
inner: Some(inner),
|
||||
target_offset: offset,
|
||||
target_length: actual_length,
|
||||
current_offset: 0,
|
||||
bytes_returned: 0,
|
||||
scratch: Box::<[u8]>::new_uninit_slice(8192),
|
||||
inner: Some(SkipReader::new(inner, offset).take(length)),
|
||||
drain_on_done,
|
||||
drain_task: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn start_drain(&mut self) {
|
||||
if !self.drain_on_done || self.drain_task.is_some() {
|
||||
return;
|
||||
fn finish(&mut self) {
|
||||
if let Some(inner) = self.inner.take()
|
||||
&& self.drain_on_done
|
||||
{
|
||||
drain_stream(inner.into_inner().inner);
|
||||
}
|
||||
|
||||
let Some(mut inner) = self.inner.take() else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.drain_task = Some(tokio::spawn(async move {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
match inner.read(&mut buf).await {
|
||||
Ok(0) => break,
|
||||
Ok(_) => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync + 'static> AsyncRead for RangedDecompressReader<R> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
use std::pin::Pin;
|
||||
use std::task::Poll;
|
||||
use tokio::io::ReadBuf;
|
||||
|
||||
let this = self.as_mut().get_mut();
|
||||
|
||||
loop {
|
||||
// If we've returned all the bytes we need, return EOF
|
||||
if this.bytes_returned >= this.target_length {
|
||||
this.start_drain();
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
// Read from the inner stream
|
||||
let buf_capacity = buf.remaining();
|
||||
if buf_capacity == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
let scratch_len = std::cmp::min(this.scratch.len(), std::cmp::max(buf_capacity, 1));
|
||||
let mut temp_read_buf = ReadBuf::uninit(&mut this.scratch[..scratch_len]);
|
||||
|
||||
let Some(inner) = this.inner.as_mut() else {
|
||||
return Poll::Ready(Ok(()));
|
||||
};
|
||||
|
||||
match Pin::new(inner).poll_read(cx, &mut temp_read_buf) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
|
||||
Poll::Ready(Ok(())) => {
|
||||
let n = temp_read_buf.filled().len();
|
||||
if n == 0 {
|
||||
// EOF from inner stream
|
||||
if this.current_offset < this.target_offset {
|
||||
// We haven't reached the target offset yet - this is an error
|
||||
return Poll::Ready(Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
format!(
|
||||
"Unexpected EOF: only read {} bytes, target offset is {}",
|
||||
this.current_offset, this.target_offset
|
||||
),
|
||||
)));
|
||||
}
|
||||
// Normal EOF after reaching target
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
// Update current position
|
||||
let old_offset = this.current_offset;
|
||||
this.current_offset += n;
|
||||
|
||||
// Check if we're still in the skip phase
|
||||
if old_offset < this.target_offset {
|
||||
// We're still skipping data
|
||||
let skip_end = std::cmp::min(this.current_offset, this.target_offset);
|
||||
let bytes_to_skip_in_this_read = skip_end - old_offset;
|
||||
|
||||
if this.current_offset <= this.target_offset {
|
||||
// All data in this read should be skipped
|
||||
tracing::trace!("Skipping {} bytes at offset {}", n, old_offset);
|
||||
// Continue reading in the loop instead of recursive call
|
||||
continue;
|
||||
} else {
|
||||
// Partial skip: some data should be returned
|
||||
let data_start_in_buffer = bytes_to_skip_in_this_read;
|
||||
let available_data = n - data_start_in_buffer;
|
||||
let bytes_to_return = std::cmp::min(
|
||||
available_data,
|
||||
std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned),
|
||||
);
|
||||
|
||||
if bytes_to_return > 0 {
|
||||
let data_slice =
|
||||
&temp_read_buf.filled()[data_start_in_buffer..data_start_in_buffer + bytes_to_return];
|
||||
buf.put_slice(data_slice);
|
||||
this.bytes_returned += bytes_to_return;
|
||||
|
||||
tracing::trace!(
|
||||
"Skipped {} bytes, returned {} bytes at offset {}",
|
||||
bytes_to_skip_in_this_read,
|
||||
bytes_to_return,
|
||||
old_offset
|
||||
);
|
||||
}
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
} else {
|
||||
// We're in the data return phase
|
||||
let bytes_to_return =
|
||||
std::cmp::min(n, std::cmp::min(buf.remaining(), this.target_length - this.bytes_returned));
|
||||
|
||||
if bytes_to_return > 0 {
|
||||
buf.put_slice(&temp_read_buf.filled()[..bytes_to_return]);
|
||||
this.bytes_returned += bytes_to_return;
|
||||
|
||||
tracing::trace!("Returned {} bytes at offset {}", bytes_to_return, old_offset);
|
||||
}
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(inner) = this.inner.as_mut() else {
|
||||
return Poll::Ready(Ok(()));
|
||||
};
|
||||
if inner.limit() == 0 {
|
||||
this.finish();
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
if buf.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
let before = buf.filled().len();
|
||||
ready!(Pin::new(&mut *inner).poll_read(cx, buf))?;
|
||||
if before == buf.filled().len() {
|
||||
return Poll::Ready(Err(std::io::Error::new(
|
||||
std::io::ErrorKind::UnexpectedEof,
|
||||
"decompressed stream ended before the requested range was complete",
|
||||
)));
|
||||
}
|
||||
if inner.limit() == 0 {
|
||||
this.finish();
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + Sync + 'static> Drop for RangedDecompressReader<R> {
|
||||
fn drop(&mut self) {
|
||||
if self.bytes_returned >= self.target_length {
|
||||
self.start_drain();
|
||||
if self.inner.as_ref().is_some_and(|inner| inner.limit() == 0) {
|
||||
self.finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper that ensures the inner stream is fully consumed even if the outer reader stops early.
|
||||
/// This prevents broken pipe errors in erasure coding scenarios where the writer expects
|
||||
/// the full stream to be consumed.
|
||||
fn drain_stream<R: AsyncRead + Unpin + Send + 'static>(mut stream: R) {
|
||||
drop(tokio::spawn(async move {
|
||||
let mut buf = [0u8; 8192];
|
||||
while matches!(stream.read(&mut buf).await, Ok(n) if n > 0) {}
|
||||
}));
|
||||
}
|
||||
|
||||
/// Drains the source in the background if dropped before observing its EOF.
|
||||
pub struct StreamConsumer<R: AsyncRead + Unpin + Send + 'static> {
|
||||
inner: Option<R>,
|
||||
consumer_task: Option<tokio::task::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + 'static> StreamConsumer<R> {
|
||||
pub fn new(inner: R) -> Self {
|
||||
Self {
|
||||
inner: Some(inner),
|
||||
consumer_task: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_consumer_started(&mut self) {
|
||||
if self.consumer_task.is_none() && self.inner.is_some() {
|
||||
let mut inner = self.inner.take().unwrap();
|
||||
let task = tokio::spawn(async move {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
match inner.read(&mut buf).await {
|
||||
Ok(0) => break, // EOF
|
||||
Ok(_) => continue, // Keep consuming
|
||||
Err(_) => break, // Error, stop consuming
|
||||
}
|
||||
}
|
||||
});
|
||||
self.consumer_task = Some(task);
|
||||
}
|
||||
Self { inner: Some(inner) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + 'static> AsyncRead for StreamConsumer<R> {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
use std::pin::Pin;
|
||||
use std::task::Poll;
|
||||
|
||||
if let Some(ref mut inner) = self.inner {
|
||||
Pin::new(inner).poll_read(cx, buf)
|
||||
} else {
|
||||
Poll::Ready(Ok(())) // EOF
|
||||
let Some(inner) = self.inner.as_mut() else {
|
||||
return Poll::Ready(Ok(()));
|
||||
};
|
||||
if buf.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
let before = buf.filled().len();
|
||||
ready!(Pin::new(inner).poll_read(cx, buf))?;
|
||||
if before == buf.filled().len() {
|
||||
self.inner = None;
|
||||
}
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + Unpin + Send + 'static> Drop for StreamConsumer<R> {
|
||||
fn drop(&mut self) {
|
||||
self.ensure_consumer_started();
|
||||
if let Some(inner) = self.inner.take() {
|
||||
drain_stream(inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1666,6 +1584,129 @@ mod tests {
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_fills_large_buffers_without_overreading() {
|
||||
let data = vec![0x32; 128 * 1024];
|
||||
let length = 64 * 1024;
|
||||
let mut reader = RangedDecompressReader::new(Cursor::new(data.clone()), 0, length as i64, data.len()).unwrap();
|
||||
let mut output = vec![0xa5; data.len()];
|
||||
|
||||
assert_eq!(reader.read(&mut output).await.unwrap(), length);
|
||||
assert_eq!(&output[..length], &data[..length]);
|
||||
assert!(output[length..].iter().all(|&byte| byte == 0xa5));
|
||||
assert_eq!(reader.read(&mut output).await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_skips_in_bulk_with_a_small_response_buffer() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct CountReads {
|
||||
cursor: Cursor<Vec<u8>>,
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl AsyncRead for CountReads {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
|
||||
self.calls.fetch_add(1, Ordering::Relaxed);
|
||||
Pin::new(&mut self.cursor).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
let skip = 512 * 1024;
|
||||
let mut data = vec![0xa5; skip];
|
||||
data.extend_from_slice(b"wanted bytes here");
|
||||
let total = data.len();
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let inner = CountReads {
|
||||
cursor: Cursor::new(data),
|
||||
calls: Arc::clone(&calls),
|
||||
};
|
||||
let mut reader = RangedDecompressReader::new(inner, skip, 16, total).unwrap();
|
||||
let mut output = [0; 16];
|
||||
|
||||
reader.read_exact(&mut output).await.unwrap();
|
||||
assert_eq!(&output, b"wanted bytes her");
|
||||
assert_eq!(calls.load(Ordering::Relaxed), 65, "64 discards and one response read");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_yields_while_skipping_an_unindexed_prefix() {
|
||||
let skip = 2 * 1024 * 1024;
|
||||
let data = vec![0x36; skip + 1];
|
||||
let total = data.len();
|
||||
let mut reader = RangedDecompressReader::new(Cursor::new(data), skip, 1, total).unwrap();
|
||||
let mut output = [0; 1];
|
||||
let mut buf = ReadBuf::new(&mut output);
|
||||
let mut yielded = false;
|
||||
|
||||
std::future::poll_fn(|cx| {
|
||||
let poll = Pin::new(&mut reader).poll_read(cx, &mut buf);
|
||||
yielded |= poll.is_pending();
|
||||
poll
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(yielded, "a long discard must yield even when the source stays ready");
|
||||
assert_eq!(buf.filled(), &[0x36]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_releases_the_source_when_the_range_completes() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
let (source, mut producer) = tokio::io::duplex(16);
|
||||
producer.write_all(b"abcxyz").await.unwrap();
|
||||
let mut reader = RangedDecompressReader::new(source, 0, 3, 6).unwrap();
|
||||
let mut body = [0; 3];
|
||||
|
||||
reader.read_exact(&mut body).await.unwrap();
|
||||
assert_eq!(&body, b"abc");
|
||||
let error = producer
|
||||
.write_all(b"!")
|
||||
.await
|
||||
.expect_err("completed range must release the pipe");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::BrokenPipe);
|
||||
assert_eq!(reader.read(&mut body).await.unwrap(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_reader_drains_the_source_when_requested() {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
let (source, mut producer) = tokio::io::duplex(8);
|
||||
producer.write_all(b"abc").await.unwrap();
|
||||
let mut reader = RangedDecompressReader::new_draining(source, 0, 3, 19).unwrap();
|
||||
let mut body = [0; 3];
|
||||
|
||||
reader.read_exact(&mut body).await.unwrap();
|
||||
assert_eq!(&body, b"abc");
|
||||
tokio::time::timeout(std::time::Duration::from_secs(2), producer.write_all(b"0123456789abcdef"))
|
||||
.await
|
||||
.expect("completed range must start draining the source")
|
||||
.expect("draining must keep the pipe open");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_consumer_observes_eof_only_with_a_nonempty_buffer() {
|
||||
let mut reader = StreamConsumer::new(Cursor::new(b"body"));
|
||||
assert_eq!(reader.read(&mut []).await.unwrap(), 0);
|
||||
|
||||
let mut output = Vec::new();
|
||||
reader.read_to_end(&mut output).await.unwrap();
|
||||
assert_eq!(output, b"body");
|
||||
assert!(reader.inner.is_none(), "observed EOF needs no background drain");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ranged_decompress_reader_rejects_eof_inside_the_requested_range() {
|
||||
let mut reader = RangedDecompressReader::new(Cursor::new(b"abc"), 1, 3, 4).unwrap();
|
||||
let mut output = Vec::new();
|
||||
let error = reader.read_to_end(&mut output).await.expect_err("short range must fail");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::UnexpectedEof);
|
||||
assert_eq!(output, b"bc");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ranged_decompress_reader_from_start() {
|
||||
let original_data = b"Hello, World! This is a test.";
|
||||
@@ -2688,10 +2729,6 @@ mod tests {
|
||||
let (compressed_offset, uncompressed_offset) = decoded.find(2_097_152).expect("seek into decoded index");
|
||||
assert!(compressed_offset > 0);
|
||||
assert_eq!(uncompressed_offset, 2_097_152);
|
||||
let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, 2_097_152);
|
||||
assert!(physical_offset > 0);
|
||||
assert_eq!(decompressed_skip, 0);
|
||||
|
||||
let range = HTTPRangeSpec {
|
||||
is_suffix_length: false,
|
||||
start: 2_097_152,
|
||||
@@ -2830,7 +2867,8 @@ mod tests {
|
||||
assert!(compressed_offset > 0);
|
||||
assert_eq!(uncompressed_offset, range.start);
|
||||
|
||||
let (physical_offset, decompressed_skip, _, _, _) = get_compressed_offsets(&object_info, range.start);
|
||||
let (physical_offset, _, decompressed_skip) =
|
||||
compressed_storage_window(&object_info, range.start as usize, 10).expect("indexed range");
|
||||
assert!(physical_offset > 0);
|
||||
assert_eq!(decompressed_skip, 0);
|
||||
|
||||
@@ -2838,14 +2876,14 @@ mod tests {
|
||||
.await
|
||||
.expect("MinIO headerless compression index should be decoded");
|
||||
|
||||
assert_eq!(plan.storage_offset as i64, physical_offset);
|
||||
assert_eq!(plan.storage_offset, physical_offset);
|
||||
assert_eq!(plan.storage_length, object_info.size - plan.storage_offset as i64);
|
||||
assert_eq!(plan.object_size, 10);
|
||||
}
|
||||
|
||||
#[cfg(feature = "rio-v2")]
|
||||
#[test]
|
||||
fn test_get_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
|
||||
fn test_get_encrypted_compressed_offsets_aligns_encrypted_ranges_to_dare_packages() {
|
||||
let mut index = Index::new();
|
||||
index.add(0, 0).unwrap();
|
||||
index.add(200_000, 2_097_152).unwrap();
|
||||
@@ -2879,7 +2917,7 @@ mod tests {
|
||||
};
|
||||
|
||||
let (physical_offset, decompressed_skip, first_part_idx, decrypt_skip, seq_num) =
|
||||
get_compressed_offsets(&object_info, 2_097_152);
|
||||
get_encrypted_compressed_offsets(&object_info, 2_097_152);
|
||||
|
||||
assert_eq!(first_part_idx, 0);
|
||||
assert_eq!(physical_offset, (expected_comp_off / DARE_PAYLOAD_SIZE) * DARE_PACKAGE_SIZE);
|
||||
|
||||
@@ -12,7 +12,6 @@ const HISTORICAL_INDEX: &[u8] = include_bytes!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/tests/fixtures/compression-index/pre-zigzag-index.bin"
|
||||
));
|
||||
#[cfg(not(feature = "rio-v2"))]
|
||||
const CURRENT_INDEX: &[u8] =
|
||||
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/compression-index/zigzag-index.bin"));
|
||||
const PLAINTEXT_LEN: usize = 3 * 1024 * 1024 + 123;
|
||||
@@ -161,6 +160,16 @@ async fn truncated_index_falls_back_without_truncating_the_range() {
|
||||
assert_eq!(actual, fixture_plaintext()[start..start + 97]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compression_metadata_requires_one_complete_index() {
|
||||
use crate::io_support::rio::decode_compression_index_bytes;
|
||||
|
||||
let index = Bytes::from_static(CURRENT_INDEX);
|
||||
assert!(decode_compression_index_bytes(&index).is_some());
|
||||
let trailing = Bytes::from([CURRENT_INDEX, b"trailing bytes"].concat());
|
||||
assert!(decode_compression_index_bytes(&trailing).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn historical_index_fallback_does_not_hide_a_body_checksum_failure() {
|
||||
let info = fixture_info(HISTORICAL_INDEX);
|
||||
@@ -183,3 +192,105 @@ async fn historical_index_fallback_does_not_hide_a_body_checksum_failure() {
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
|
||||
assert!(actual.len() < PLAINTEXT_LEN);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compressed_ranges_bound_storage_for_large_index_and_unsampled_tail() {
|
||||
use crate::io_support::rio::compression_index_storage_bytes;
|
||||
use rustfs_rio::{CompressReader, TryGetIndex};
|
||||
|
||||
const BLOCK: usize = 1024 * 1024;
|
||||
const BLOCKS: usize = 203;
|
||||
const TAIL: usize = 32 * 1024;
|
||||
const LENGTH: usize = 16 * 1024;
|
||||
let len = BLOCK * BLOCKS + TAIL;
|
||||
let mut compressor = CompressReader::new(
|
||||
tokio::io::repeat(b'a')
|
||||
.take((len - TAIL) as u64)
|
||||
.chain(tokio::io::repeat(b'z').take(TAIL as u64)),
|
||||
CompressionAlgorithm::Lz4,
|
||||
);
|
||||
let mut stored = Vec::new();
|
||||
compressor.read_to_end(&mut stored).await.expect("compress fixture");
|
||||
let index = compressor.try_get_index().expect("legacy writer has an index");
|
||||
assert!(index.len() > 200);
|
||||
assert_eq!(index.total_uncompressed, (len - TAIL) as i64, "short final block is not indexed");
|
||||
let index = compression_index_storage_bytes(index);
|
||||
let mut info = fixture_info(&index);
|
||||
info.size = stored.len() as i64;
|
||||
info.actual_size = len as i64;
|
||||
let part = &mut Arc::make_mut(&mut info.parts)[0];
|
||||
part.size = stored.len();
|
||||
part.actual_size = len as i64;
|
||||
|
||||
for start in [1000, 9999, BLOCK - 7, len - LENGTH] {
|
||||
let range = if start == len - LENGTH {
|
||||
HTTPRangeSpec {
|
||||
is_suffix_length: true,
|
||||
start: -(LENGTH as i64),
|
||||
end: -1,
|
||||
}
|
||||
} else {
|
||||
HTTPRangeSpec {
|
||||
is_suffix_length: false,
|
||||
start: start as i64,
|
||||
end: (start + LENGTH - 1) as i64,
|
||||
}
|
||||
};
|
||||
let plan = ReadPlan::build(Some(range), &info, &ObjectOptions::default(), &HeaderMap::new())
|
||||
.await
|
||||
.expect("plan valid range");
|
||||
let physical_start = plan.storage_offset;
|
||||
let physical_end = physical_start + usize::try_from(plan.storage_length).expect("positive storage window");
|
||||
let mut output = Vec::new();
|
||||
let (mut reader, _, _) = plan
|
||||
.into_reader(Box::new(Cursor::new(stored[physical_start..physical_end].to_vec())), &info)
|
||||
.expect("valid plaintext range has a reader");
|
||||
reader.read_to_end(&mut output).await.expect("decode from planned window");
|
||||
let expected_byte = if start == len - LENGTH { b'z' } else { b'a' };
|
||||
assert_eq!(output, vec![expected_byte; LENGTH], "range starting at {start}");
|
||||
assert!(
|
||||
physical_end - physical_start < stored.len() / 20,
|
||||
"range at {start} reads too much compressed data"
|
||||
);
|
||||
if start == len - LENGTH {
|
||||
assert!(physical_start > stored.len() * 9 / 10, "suffix must seek within the final part");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn compressed_multipart_window_stops_at_the_last_covering_part() {
|
||||
let mut info = fixture_info(CURRENT_INDEX);
|
||||
let parts = Arc::make_mut(&mut info.parts);
|
||||
parts.push(ObjectPartInfo {
|
||||
number: 2,
|
||||
..parts[0].clone()
|
||||
});
|
||||
parts.push(ObjectPartInfo {
|
||||
number: 3,
|
||||
..parts[0].clone()
|
||||
});
|
||||
info.size *= 3;
|
||||
info.actual_size = (PLAINTEXT_LEN * 3) as i64;
|
||||
|
||||
let range = HTTPRangeSpec {
|
||||
is_suffix_length: false,
|
||||
start: PLAINTEXT_LEN as i64 - 16,
|
||||
end: PLAINTEXT_LEN as i64 + 15,
|
||||
};
|
||||
let plan = ReadPlan::build(Some(range), &info, &ObjectOptions::default(), &HeaderMap::new())
|
||||
.await
|
||||
.expect("valid range across parts");
|
||||
let physical_start = plan.storage_offset;
|
||||
let physical_end = physical_start + plan.storage_length as usize;
|
||||
assert!(physical_end > STREAM.len(), "range crosses the stored part boundary");
|
||||
assert!(physical_end < STREAM.len() * 2, "range should stop at the first checkpoint in part two");
|
||||
let stored = STREAM.repeat(3);
|
||||
let (mut reader, _, _) = plan
|
||||
.into_reader(Box::new(Cursor::new(stored[physical_start..physical_end].to_vec())), &info)
|
||||
.expect("create multipart range reader");
|
||||
let mut output = Vec::new();
|
||||
reader.read_to_end(&mut output).await.expect("decode part boundary");
|
||||
let plaintext = fixture_plaintext();
|
||||
assert_eq!(output, [&plaintext[PLAINTEXT_LEN - 16..], &plaintext[..16]].concat());
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ use crate::store::delete_recovery_runtime::DeleteRecoveryHints;
|
||||
use rustfs_lock::{GlobalLockManager, get_global_lock_manager};
|
||||
use rustfs_s3_types::Region;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::{
|
||||
Arc, OnceLock,
|
||||
atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
|
||||
@@ -234,6 +235,8 @@ pub struct InstanceContext {
|
||||
/// drift out of sync). Stored as one value so the three predicates can
|
||||
/// never observe a torn intermediate state.
|
||||
erasure_kind: RwLock<SetupType>,
|
||||
/// Snapshot of the creating thread's affinity and CPU quota for instance workers.
|
||||
worker_parallelism: NonZeroUsize,
|
||||
list_read_budget: OnceLock<ListReadBudget>,
|
||||
#[cfg(feature = "internode-transport")]
|
||||
internode_data_transport: OnceLock<Arc<dyn crate::api::rpc::InternodeDataTransport>>,
|
||||
@@ -464,6 +467,7 @@ impl InstanceContext {
|
||||
fn with_lock_manager(lock_manager: Arc<GlobalLockManager>) -> Self {
|
||||
Self {
|
||||
erasure_kind: RwLock::new(SetupType::Unknown),
|
||||
worker_parallelism: super::detect_worker_parallelism(),
|
||||
list_read_budget: OnceLock::new(),
|
||||
#[cfg(feature = "internode-transport")]
|
||||
internode_data_transport: OnceLock::new(),
|
||||
@@ -515,6 +519,10 @@ impl InstanceContext {
|
||||
Self::with_lock_manager(lock_manager)
|
||||
}
|
||||
|
||||
pub(crate) fn worker_parallelism(&self) -> NonZeroUsize {
|
||||
self.worker_parallelism
|
||||
}
|
||||
|
||||
/// This instance's namespace lock manager.
|
||||
pub fn lock_manager(&self) -> Arc<GlobalLockManager> {
|
||||
self.lock_manager.clone()
|
||||
|
||||
@@ -18,3 +18,7 @@ pub(crate) mod global;
|
||||
pub(crate) mod instance;
|
||||
pub(crate) mod sources;
|
||||
pub(crate) mod usage_watch;
|
||||
|
||||
pub(crate) fn detect_worker_parallelism() -> std::num::NonZeroUsize {
|
||||
std::thread::available_parallelism().unwrap_or(std::num::NonZeroUsize::MIN)
|
||||
}
|
||||
|
||||
@@ -73,18 +73,13 @@ impl SetDisks {
|
||||
pub(crate) async fn stat_bucket_with_quorum(&self, bucket: &str, quorum: BucketInfoQuorum) -> Result<BucketInfo> {
|
||||
let disks = self.disk_inventory().await;
|
||||
let disk_count = disks.len();
|
||||
let 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 results = join_all(disks.into_iter().map(|disk| async move {
|
||||
match disk {
|
||||
Some(disk) => disk.stat_volume(bucket).await,
|
||||
None => Err(DiskError::DiskNotFound),
|
||||
}
|
||||
}))
|
||||
.await;
|
||||
let mut infos = Vec::with_capacity(results.len());
|
||||
let mut errs = Vec::with_capacity(results.len());
|
||||
for result in results {
|
||||
|
||||
@@ -5035,27 +5035,37 @@ mod metadata_cache_tests {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
let mut reader = PutObjReader::from_vec(vec![7u8; 1024]);
|
||||
set.put_object(bucket, object, &mut reader, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("test object should be written");
|
||||
// A quorum-acknowledged PUT can leave a rename running on a healthy
|
||||
// disk. This test needs an error-free fanout to reach cache publication.
|
||||
set.put_object(
|
||||
bucket,
|
||||
object,
|
||||
&mut reader,
|
||||
&ObjectOptions {
|
||||
write_completion: crate::object_api::WriteCompletion::TailDrained,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("the fixture PUT should drain its commit fanout");
|
||||
|
||||
let barrier = MetadataCachePublishBarrier::install(bucket, object);
|
||||
let stale_generation = set
|
||||
.get_object_metadata_cache_generation(bucket, object)
|
||||
.expect("metadata cache generation should be active");
|
||||
let reader_set = Arc::clone(&set);
|
||||
let read = tokio::spawn(async move {
|
||||
reader_set
|
||||
.get_object_fileinfo(bucket, object, &ObjectOptions::default(), true, false)
|
||||
.await
|
||||
});
|
||||
barrier.wait_until_paused().await;
|
||||
let opts = ObjectOptions::default();
|
||||
let read = set.get_object_fileinfo(bucket, object, &opts, true, false);
|
||||
tokio::pin!(read);
|
||||
tokio::select! {
|
||||
() = barrier.wait_until_paused() => {}
|
||||
result = &mut read => match result {
|
||||
Ok(_) => panic!("metadata read returned without reaching cache publication"),
|
||||
Err(err) => panic!("metadata read failed before cache publication: {err}"),
|
||||
},
|
||||
}
|
||||
set.invalidate_get_object_metadata_cache(bucket, object).await;
|
||||
barrier.release();
|
||||
let snapshot = read
|
||||
.await
|
||||
.expect("metadata read task should not panic")
|
||||
.expect("metadata fanout should still return its selected FileInfo");
|
||||
let snapshot = read.await.expect("metadata fanout should still return its selected FileInfo");
|
||||
assert!(snapshot.owned.is_some());
|
||||
assert!(snapshot.has_valid_representation());
|
||||
|
||||
|
||||
@@ -6451,8 +6451,14 @@ mod tests {
|
||||
};
|
||||
if let Some(split) = multipart_split {
|
||||
assert!(split > 0 && split < body.len(), "multipart source split must create two non-empty parts");
|
||||
// Upload initiation belongs to the current bucket generation. The
|
||||
// historical object timestamp is assigned at completion.
|
||||
let init_opts = ObjectOptions {
|
||||
mod_time: None,
|
||||
..write_opts.clone()
|
||||
};
|
||||
let upload = pool
|
||||
.new_multipart_upload(bucket, object, &write_opts)
|
||||
.new_multipart_upload(bucket, object, &init_opts)
|
||||
.await
|
||||
.expect("create physical data-movement source upload");
|
||||
let mut completed_parts = Vec::with_capacity(2);
|
||||
@@ -7609,7 +7615,7 @@ mod tests {
|
||||
..versioned.clone()
|
||||
};
|
||||
let upload = store.pools[0]
|
||||
.new_multipart_upload(&bucket, object, &native_opts)
|
||||
.new_multipart_upload(&bucket, object, &versioned)
|
||||
.await
|
||||
.expect("real pool-zero Init");
|
||||
let part = store.pools[0]
|
||||
@@ -8801,9 +8807,9 @@ mod tests {
|
||||
let retain_until = (OffsetDateTime::now_utc() + time::Duration::days(1))
|
||||
.format(&time::format_description::well_known::Rfc3339)
|
||||
.expect("retain-until date should format");
|
||||
for (object, replacement_source, mode) in [
|
||||
("compliance-target.bin", "compliance-target-replacement.bin", "COMPLIANCE"),
|
||||
("governance-target.bin", "governance-target-replacement.bin", "GOVERNANCE"),
|
||||
for (object, mode) in [
|
||||
("compliance-target.bin", "COMPLIANCE"),
|
||||
("governance-target.bin", "GOVERNANCE"),
|
||||
] {
|
||||
let retained_metadata = HashMap::from([
|
||||
(rustfs_filemeta::metadata_keys::OBJECT_LOCK_MODE.to_string(), mode.to_string()),
|
||||
@@ -8816,26 +8822,44 @@ mod tests {
|
||||
store.clone(),
|
||||
0,
|
||||
bucket.clone(),
|
||||
source_reader(object, old_body.clone(), old_time, retained_metadata.clone()).await,
|
||||
source_reader(object, old_body.clone(), old_time, HashMap::new()).await,
|
||||
None,
|
||||
"test_retained_target_seed",
|
||||
)
|
||||
.await
|
||||
.expect("seed retained migrated target");
|
||||
let mut replacement_source_reader =
|
||||
source_reader(replacement_source, new_body.clone(), new_time, retained_metadata).await;
|
||||
replacement_source_reader.object_info.name = object.to_string();
|
||||
.expect("seed migrated target");
|
||||
// Model retention already present on the target independently of the source.
|
||||
// Preserve the migration ownership markers so WORM is the rejecting check.
|
||||
for disk in store.pools[1].disk_set[0].disk_inventory().await {
|
||||
disk.expect("target disk should be online")
|
||||
.update_metadata(
|
||||
&bucket,
|
||||
object,
|
||||
FileInfo {
|
||||
version_id: Some(version_id),
|
||||
metadata: retained_metadata.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
&crate::disk::UpdateMetadataOpts::default(),
|
||||
)
|
||||
.await
|
||||
.expect("seed retention on the exact target version");
|
||||
}
|
||||
let err = crate::data_movement::migrate_object(
|
||||
store.clone(),
|
||||
0,
|
||||
bucket.clone(),
|
||||
replacement_source_reader,
|
||||
source_reader(object, new_body.clone(), new_time, HashMap::new()).await,
|
||||
None,
|
||||
"test_retained_target_replace",
|
||||
)
|
||||
.await
|
||||
.expect_err("active retention must block stale target replacement");
|
||||
assert!(err.to_string().contains("complete_multipart_upload"), "unexpected retention error: {err}");
|
||||
assert!(
|
||||
crate::data_movement::data_movement_error_is_stage(&err, "complete_multipart_upload")
|
||||
&& err.to_string().contains("Prefix access is denied"),
|
||||
"unexpected retention error: {err}"
|
||||
);
|
||||
|
||||
let mut retained_reader = store.pools[1]
|
||||
.get_object_reader(
|
||||
@@ -22005,6 +22029,92 @@ mod tests {
|
||||
assert_eq!(body, original_body);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn single_put_records_object_lock_snapshot_stages() {
|
||||
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
|
||||
use rustfs_io_metrics::{
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ, PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK, put_stage_metrics_enabled, set_put_stage_metrics_enabled,
|
||||
};
|
||||
|
||||
struct RestorePutStageFlag(bool);
|
||||
impl Drop for RestorePutStageFlag {
|
||||
fn drop(&mut self) {
|
||||
set_put_stage_metrics_enabled(self.0);
|
||||
}
|
||||
}
|
||||
|
||||
let temp = tempfile::tempdir().expect("create snapshot test store dir");
|
||||
let (ctx, store, _shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(temp.path(), "put-snapshot-stages", &[4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
|
||||
let bucket = format!("snapshot-stages-{}", uuid::Uuid::new_v4());
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create snapshot bucket");
|
||||
let opts = ObjectOptions {
|
||||
expected_bucket_incarnation_id: Some(store.bucket_incarnation_id(&bucket).await.expect("load bucket incarnation")),
|
||||
write_completion: crate::object_api::WriteCompletion::TailDrained,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
let _recorder = metrics::set_default_local_recorder(&recorder);
|
||||
let _flag = RestorePutStageFlag(put_stage_metrics_enabled());
|
||||
let take_stage_counts = || {
|
||||
let stages = [
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
|
||||
];
|
||||
let mut counts = [0; 3];
|
||||
for (key, _, _, value) in snapshotter.snapshot().into_vec() {
|
||||
let key = key.key();
|
||||
if key.name() != "rustfs_s3_put_object_stage_duration_ms" {
|
||||
continue;
|
||||
}
|
||||
if let Some(index) = stages
|
||||
.iter()
|
||||
.position(|stage| key.labels().any(|label| label.key() == "stage" && label.value() == *stage))
|
||||
{
|
||||
assert_eq!(key.labels().count(), 1, "snapshot timings must have only a static stage label");
|
||||
let DebugValue::Histogram(samples) = value else {
|
||||
panic!("snapshot timing must be recorded as a histogram");
|
||||
};
|
||||
counts[index] += samples.len();
|
||||
}
|
||||
}
|
||||
counts
|
||||
};
|
||||
|
||||
set_put_stage_metrics_enabled(false);
|
||||
store
|
||||
.put_object(&bucket, "metrics-off", &mut PutObjReader::from_vec(vec![1]), &opts)
|
||||
.await
|
||||
.expect("ordinary PUT with metrics disabled");
|
||||
assert_eq!(take_stage_counts(), [0, 0, 0]);
|
||||
|
||||
set_put_stage_metrics_enabled(true);
|
||||
store
|
||||
.put_object(&bucket, "metrics-on", &mut PutObjReader::from_vec(vec![1]), &opts)
|
||||
.await
|
||||
.expect("ordinary PUT with metrics enabled");
|
||||
assert_eq!(take_stage_counts(), [1, 1, 1]);
|
||||
|
||||
crate::bucket::metadata_sys::inject_object_lock_disk_read_error_in(&ctx, &bucket)
|
||||
.await
|
||||
.expect("inject authority read error");
|
||||
let error = store
|
||||
.put_object(&bucket, "read-failed", &mut PutObjReader::from_vec(vec![1]), &opts)
|
||||
.await
|
||||
.expect_err("authority failure must still reject the PUT");
|
||||
assert!(error.to_string().contains("injected Object Lock metadata disk read failure"));
|
||||
assert_eq!(take_stage_counts(), [1, 1, 1], "each stage records once even when the final read fails");
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
|
||||
@@ -100,12 +100,15 @@ mod multipart_copy_heal_tests {
|
||||
.collect::<Vec<_>>();
|
||||
let options = ObjectOptions {
|
||||
versioned: true,
|
||||
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixed native C timestamp")),
|
||||
write_completion: WriteCompletion::TailDrained,
|
||||
..Default::default()
|
||||
};
|
||||
let init_opts = ObjectOptions {
|
||||
mod_time: None,
|
||||
..options.clone()
|
||||
};
|
||||
let upload = store.pools[0]
|
||||
.new_multipart_upload(&bucket, &object, &options)
|
||||
.new_multipart_upload(&bucket, &object, &init_opts)
|
||||
.await
|
||||
.expect("actual native C Init");
|
||||
let part = store.pools[0]
|
||||
@@ -130,7 +133,11 @@ mod multipart_copy_heal_tests {
|
||||
etag: part.etag,
|
||||
..Default::default()
|
||||
}],
|
||||
&options,
|
||||
&ObjectOptions {
|
||||
// Pin the committed timestamp without backdating the staged upload.
|
||||
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("fixed native C timestamp")),
|
||||
..options
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("actual native C quorum publication");
|
||||
|
||||
+252
-142
@@ -2110,8 +2110,22 @@ fn batch_delete_action_key(object: &ObjectToDelete) -> (&str, Option<Uuid>) {
|
||||
(object.object_name.as_str(), object.version_id)
|
||||
}
|
||||
|
||||
fn batch_delete_targets_pool(creates_latest_marker: bool, marker_target_pool_idx: Option<usize>, pool_idx: usize) -> bool {
|
||||
!creates_latest_marker || marker_target_pool_idx == Some(pool_idx)
|
||||
#[derive(Clone, Copy)]
|
||||
enum BatchDeleteRoute {
|
||||
Inactive,
|
||||
AllPools,
|
||||
PendingMarker,
|
||||
Marker(usize),
|
||||
}
|
||||
|
||||
impl BatchDeleteRoute {
|
||||
fn targets(self, pool_idx: usize) -> bool {
|
||||
match self {
|
||||
Self::Inactive | Self::PendingMarker => false,
|
||||
Self::AllPools => true,
|
||||
Self::Marker(target) => target == pool_idx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2197,52 +2211,33 @@ fn inject_batch_delete_pool_errors(
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_batch_delete_pool_results<'a>(
|
||||
initial_error: Option<Error>,
|
||||
pool_results: impl IntoIterator<Item = (&'a DeletedObject, &'a Option<Error>)>,
|
||||
) -> (Option<DeletedObject>, Option<Error>, bool) {
|
||||
let mut failure = initial_error.map(|err| (None, err));
|
||||
let mut deleted = None;
|
||||
let mut fallback: Option<(DeletedObject, Option<Error>)> = None;
|
||||
let mut attempted = false;
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum BatchDeleteOutcome {
|
||||
SilentMiss,
|
||||
Missing,
|
||||
Deleted,
|
||||
Failed,
|
||||
}
|
||||
|
||||
for (pool_delete, pool_error) in pool_results {
|
||||
attempted = true;
|
||||
match pool_error {
|
||||
Some(err) if is_err_object_not_found(err) || is_err_version_not_found(err) => {
|
||||
if fallback.as_ref().is_none_or(|(_, error)| error.is_none()) {
|
||||
fallback = Some(((*pool_delete).clone(), Some(err.clone())));
|
||||
}
|
||||
}
|
||||
Some(err) => {
|
||||
if failure.is_none() {
|
||||
failure = Some((Some((*pool_delete).clone()), err.clone()));
|
||||
}
|
||||
}
|
||||
None if pool_delete.found => {
|
||||
if deleted.is_none() {
|
||||
deleted = Some((*pool_delete).clone());
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if fallback.is_none() {
|
||||
fallback = Some(((*pool_delete).clone(), None));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn apply_batch_delete_pool_result(
|
||||
selected: &mut Option<BatchDeleteOutcome>,
|
||||
deleted: &mut DeletedObject,
|
||||
error: &mut Option<Error>,
|
||||
pool_delete: DeletedObject,
|
||||
pool_error: Option<Error>,
|
||||
) {
|
||||
let outcome = match &pool_error {
|
||||
Some(err) if is_err_object_not_found(err) || is_err_version_not_found(err) => BatchDeleteOutcome::Missing,
|
||||
Some(_) => BatchDeleteOutcome::Failed,
|
||||
None if pool_delete.found => BatchDeleteOutcome::Deleted,
|
||||
None => BatchDeleteOutcome::SilentMiss,
|
||||
};
|
||||
// Results arrive in pool order. Equal priorities keep the first result.
|
||||
if selected.is_none_or(|current| outcome > current) {
|
||||
*selected = Some(outcome);
|
||||
*deleted = pool_delete;
|
||||
*error = pool_error;
|
||||
}
|
||||
|
||||
if let Some((failed_delete, err)) = failure {
|
||||
return (failed_delete, Some(err), attempted);
|
||||
}
|
||||
if let Some(deleted) = deleted {
|
||||
return (Some(deleted), None, attempted);
|
||||
}
|
||||
if let Some((deleted, err)) = fallback {
|
||||
return (Some(deleted), err, attempted);
|
||||
}
|
||||
|
||||
(None, None, attempted)
|
||||
}
|
||||
|
||||
fn transition_restore_pool_opts(opts: &ObjectOptions) -> ObjectOptions {
|
||||
@@ -2774,6 +2769,7 @@ async fn await_conditional_capability_set_probe_gate(bucket: &str) -> Result<()>
|
||||
}
|
||||
|
||||
struct BatchDeletePhasePlan<'a> {
|
||||
/// Unique input positions in request order.
|
||||
indices: &'a [usize],
|
||||
pool_generations: HashMap<usize, HashMap<String, CurrentDeleteGeneration>>,
|
||||
marker_targets: &'a HashMap<String, usize>,
|
||||
@@ -3308,15 +3304,34 @@ impl ECStore {
|
||||
|
||||
pub(crate) async fn object_lock_config_snapshot_for_single_put(&self, bucket: &str) -> Result<Arc<ObjectLockConfigSnapshot>> {
|
||||
check_valid_bucket_name(bucket)?;
|
||||
let lifecycle_guard = self.acquire_bucket_lifecycle_read_lock(bucket).await?;
|
||||
let lifecycle_lock_started = rustfs_io_metrics::put_stage_timer();
|
||||
let lifecycle_guard = self.acquire_bucket_lifecycle_read_lock(bucket).await;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
|
||||
lifecycle_lock_started,
|
||||
);
|
||||
let lifecycle_guard = lifecycle_guard?;
|
||||
|
||||
let metadata_lock_started = rustfs_io_metrics::put_stage_timer();
|
||||
let metadata_guard = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_read_lock_in_for_purpose(
|
||||
&self.ctx,
|
||||
bucket,
|
||||
"object_lock_snapshot_metadata_read",
|
||||
)
|
||||
.await?;
|
||||
let (state, bucket_incarnation_id, config_revision, quota_res) =
|
||||
get_object_lock_and_quota_config_from_disk_with_guard_in(&self.ctx, bucket, Some(&lifecycle_guard)).await?;
|
||||
.await;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
|
||||
metadata_lock_started,
|
||||
);
|
||||
let metadata_guard = metadata_guard?;
|
||||
|
||||
let authority_read_started = rustfs_io_metrics::put_stage_timer();
|
||||
let authority = get_object_lock_and_quota_config_from_disk_with_guard_in(&self.ctx, bucket, Some(&lifecycle_guard)).await;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
|
||||
authority_read_started,
|
||||
);
|
||||
let (state, bucket_incarnation_id, config_revision, quota_res) = authority?;
|
||||
if lifecycle_guard.is_lock_lost() || metadata_guard.is_lock_lost() {
|
||||
return Err(Error::other("bucket lifecycle lock was lost while loading the Object Lock snapshot"));
|
||||
}
|
||||
@@ -6204,10 +6219,7 @@ impl ECStore {
|
||||
mut pool_generations,
|
||||
marker_targets: conditional_marker_targets,
|
||||
} = plan;
|
||||
let mut active = vec![false; objects.len()];
|
||||
for idx in indices {
|
||||
active[*idx] = true;
|
||||
}
|
||||
debug_assert!(indices.windows(2).all(|pair| pair[0] < pair[1]));
|
||||
let mut del_objects = vec![DeletedObject::default(); objects.len()];
|
||||
let mut del_errs = vec![None; objects.len()];
|
||||
let mut accounting = vec![None; objects.len()];
|
||||
@@ -6215,46 +6227,55 @@ impl ECStore {
|
||||
.delete_replication_config_snapshot
|
||||
.as_deref()
|
||||
.expect("batch delete replication config snapshot should be loaded");
|
||||
let latest_marker_objects = objects
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, object)| {
|
||||
active[idx] && del_errs[idx].is_none() && batch_delete_creates_latest_marker(object, delete_config_snapshot)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let marker_target_results = join_all(objects.iter().zip(&latest_marker_objects).map(|(object, creates_marker)| {
|
||||
let admitted_target = conditional_marker_targets.get(&object.object_name).copied();
|
||||
async move {
|
||||
if *creates_marker {
|
||||
// Routing is part of condition admission. A rebalance
|
||||
// start cannot replace the validated current owner.
|
||||
Some(match admitted_target {
|
||||
Some(pool_idx) => Ok(pool_idx),
|
||||
None => self.get_pool_idx_no_lock(bucket, &object.object_name, 0).await,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let mut routes = vec![BatchDeleteRoute::Inactive; objects.len()];
|
||||
let mut has_markers = false;
|
||||
let mut pending_markers = 0;
|
||||
for &idx in indices {
|
||||
let object = &objects[idx];
|
||||
if !batch_delete_creates_latest_marker(object, delete_config_snapshot) {
|
||||
routes[idx] = BatchDeleteRoute::AllPools;
|
||||
continue;
|
||||
}
|
||||
}))
|
||||
.await;
|
||||
let mut marker_target_pool_indices = Vec::with_capacity(objects.len());
|
||||
for (idx, target_result) in marker_target_results.into_iter().enumerate() {
|
||||
match target_result {
|
||||
Some(Ok(pool_idx)) => marker_target_pool_indices.push(Some(pool_idx)),
|
||||
Some(Err(err)) => {
|
||||
del_errs[idx] = Some(err);
|
||||
marker_target_pool_indices.push(None);
|
||||
}
|
||||
None => marker_target_pool_indices.push(None),
|
||||
has_markers = true;
|
||||
// Rebalancing cannot replace the owner used to admit a conditional delete.
|
||||
if let Some(&pool_idx) = conditional_marker_targets.get(&object.object_name) {
|
||||
routes[idx] = BatchDeleteRoute::Marker(pool_idx);
|
||||
} else {
|
||||
routes[idx] = BatchDeleteRoute::PendingMarker;
|
||||
pending_markers += 1;
|
||||
}
|
||||
}
|
||||
if pending_markers != 0 {
|
||||
let lookups = indices
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&idx| matches!(routes[idx], BatchDeleteRoute::PendingMarker))
|
||||
// Bound join_all's size hint by the unresolved markers.
|
||||
.take(pending_markers)
|
||||
.map(|idx| async move { (idx, self.get_pool_idx_no_lock(bucket, &objects[idx].object_name, 0).await) });
|
||||
let lookup_results = join_all(lookups).await;
|
||||
for (idx, result) in lookup_results {
|
||||
routes[idx] = match result {
|
||||
Ok(pool_idx) => BatchDeleteRoute::Marker(pool_idx),
|
||||
Err(err) => {
|
||||
del_errs[idx] = Some(err);
|
||||
BatchDeleteRoute::Inactive
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
let _capacity_fence = if !self.single_pool() && latest_marker_objects.iter().any(|creates_marker| *creates_marker) {
|
||||
let _capacity_fence = if !self.single_pool() && has_markers {
|
||||
// Only marker destinations can grow. Other pools participate in
|
||||
// exact deletion under the same metadata read fence and must not
|
||||
// be treated as publication targets merely because they retire.
|
||||
let mut target_pool_indices = marker_target_pool_indices.iter().flatten().copied().collect::<Vec<_>>();
|
||||
let mut target_pool_indices = indices
|
||||
.iter()
|
||||
.filter_map(|&idx| match routes[idx] {
|
||||
BatchDeleteRoute::Marker(pool_idx) => Some(pool_idx),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
target_pool_indices.sort_unstable();
|
||||
target_pool_indices.dedup();
|
||||
match self
|
||||
@@ -6282,16 +6303,15 @@ impl ECStore {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (object_indices, pool_objects): (Vec<_>, Vec<_>) = objects
|
||||
let (object_indices, pool_objects): (Vec<_>, Vec<_>) = indices
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|&idx| (idx, &objects[idx]))
|
||||
.filter(|(idx, object)| {
|
||||
active[*idx] && del_errs[*idx].is_none()
|
||||
routes[*idx].targets(pool.pool_idx)
|
||||
// A newly rebalancing pool still owes every admitted
|
||||
// conditional key its guarded mutation. Ordinary keys
|
||||
// retain the existing rebalance skip behavior.
|
||||
&& (!rebalancing || guarded_generations.is_some_and(|generations| generations.contains_key(&object.object_name)))
|
||||
&& batch_delete_targets_pool(latest_marker_objects[*idx], marker_target_pool_indices[*idx], pool.pool_idx)
|
||||
})
|
||||
.map(|(idx, object)| (idx, object.clone()))
|
||||
.unzip();
|
||||
@@ -6319,20 +6339,23 @@ impl ECStore {
|
||||
});
|
||||
}
|
||||
|
||||
let results = join_all(futures).await;
|
||||
|
||||
for idx in 0..del_objects.len() {
|
||||
let pool_results = results.iter().filter_map(|(object_indices, (dels, errs, _))| {
|
||||
let pool_object_idx = object_indices.binary_search(&idx).ok()?;
|
||||
Some((&dels[pool_object_idx], &errs[pool_object_idx]))
|
||||
});
|
||||
let (deleted, error, attempted) = resolve_batch_delete_pool_results(del_errs[idx].take(), pool_results);
|
||||
if let Some(deleted) = deleted {
|
||||
del_objects[idx] = deleted;
|
||||
let mut selected: Vec<_> = del_errs
|
||||
.iter()
|
||||
.map(|error| error.as_ref().map(|_| BatchDeleteOutcome::Failed))
|
||||
.collect();
|
||||
for (object_indices, (pool_deleted, pool_errors, pool_accounting)) in join_all(futures).await {
|
||||
debug_assert_eq!(object_indices.len(), pool_deleted.len());
|
||||
debug_assert_eq!(object_indices.len(), pool_errors.len());
|
||||
let mut pool_accounting = pool_accounting.into_iter();
|
||||
for (idx, (deleted, error)) in object_indices.into_iter().zip(pool_deleted.into_iter().zip(pool_errors)) {
|
||||
apply_batch_delete_pool_result(&mut selected[idx], &mut del_objects[idx], &mut del_errs[idx], deleted, error);
|
||||
// Accounting follows the last pool that attempted this index.
|
||||
accounting[idx] = pool_accounting.next().flatten();
|
||||
}
|
||||
del_errs[idx] = error;
|
||||
}
|
||||
|
||||
if !attempted && del_errs[idx].is_none() && latest_marker_objects[idx] {
|
||||
for &idx in indices {
|
||||
if matches!(routes[idx], BatchDeleteRoute::Marker(_)) && selected[idx].is_none() {
|
||||
del_objects[idx] = DeletedObject {
|
||||
object_name: objects[idx].object_name.clone(),
|
||||
version_id: objects[idx].version_id,
|
||||
@@ -6342,12 +6365,6 @@ impl ECStore {
|
||||
}
|
||||
}
|
||||
|
||||
for (object_indices, (_, _, pool_accounting)) in &results {
|
||||
for (pool_object_idx, object_idx) in object_indices.iter().enumerate() {
|
||||
accounting[*object_idx] = pool_accounting.get(pool_object_idx).cloned().flatten();
|
||||
}
|
||||
}
|
||||
|
||||
(del_objects, del_errs, accounting)
|
||||
}
|
||||
|
||||
@@ -6360,9 +6377,8 @@ impl ECStore {
|
||||
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
|
||||
// encode object name
|
||||
let objects: Vec<ObjectToDelete> = objects
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let mut v = v.clone();
|
||||
.into_iter()
|
||||
.map(|mut v| {
|
||||
v.object_name = encode_dir_object(v.object_name.as_str());
|
||||
v
|
||||
})
|
||||
@@ -6595,7 +6611,7 @@ impl ECStore {
|
||||
// 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 (phase_deleted, mut phase_errors, mut phase_accounting) = self
|
||||
let (mut phase_deleted, mut phase_errors, mut phase_accounting) = self
|
||||
.run_batch_delete_phase(
|
||||
bucket,
|
||||
&objects,
|
||||
@@ -6608,7 +6624,7 @@ impl ECStore {
|
||||
)
|
||||
.await;
|
||||
for idx in indices {
|
||||
del_objects[idx] = phase_deleted[idx].clone();
|
||||
del_objects[idx] = std::mem::take(&mut phase_deleted[idx]);
|
||||
del_errs[idx] = phase_errors[idx].take();
|
||||
accounting[idx] = phase_accounting[idx].take();
|
||||
}
|
||||
@@ -6625,7 +6641,7 @@ impl ECStore {
|
||||
}
|
||||
}
|
||||
if !conditional_indices.is_empty() {
|
||||
let (deleted, mut errors, mut receipts) = self
|
||||
let (mut deleted, mut errors, mut receipts) = self
|
||||
.run_batch_delete_phase(
|
||||
bucket,
|
||||
&objects,
|
||||
@@ -6638,7 +6654,7 @@ impl ECStore {
|
||||
)
|
||||
.await;
|
||||
for idx in &conditional_indices {
|
||||
del_objects[*idx] = deleted[*idx].clone();
|
||||
del_objects[*idx] = std::mem::take(&mut deleted[*idx]);
|
||||
del_errs[*idx] = errors[*idx].take();
|
||||
accounting[*idx] = receipts[*idx].take();
|
||||
}
|
||||
@@ -6671,7 +6687,7 @@ impl ECStore {
|
||||
if !ordinary_indices.is_empty() {
|
||||
// The guarded phase has finished all rollback/receipt work.
|
||||
// These actions receive neither its CAS nor its transaction.
|
||||
let (deleted, mut errors, mut receipts) = self
|
||||
let (mut deleted, mut errors, mut receipts) = self
|
||||
.run_batch_delete_phase(
|
||||
bucket,
|
||||
&objects,
|
||||
@@ -6684,7 +6700,7 @@ impl ECStore {
|
||||
)
|
||||
.await;
|
||||
for idx in ordinary_indices {
|
||||
del_objects[idx] = deleted[idx].clone();
|
||||
del_objects[idx] = std::mem::take(&mut deleted[idx]);
|
||||
del_errs[idx] = errors[idx].take();
|
||||
accounting[idx] = receipts[idx].take();
|
||||
}
|
||||
@@ -9762,9 +9778,11 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
assert!(batch_delete_creates_latest_marker(&latest, &versioned));
|
||||
assert!(!batch_delete_targets_pool(true, Some(1), 0));
|
||||
assert!(batch_delete_targets_pool(true, Some(1), 1));
|
||||
assert!(!batch_delete_targets_pool(true, Some(1), 2));
|
||||
assert!(!BatchDeleteRoute::Marker(1).targets(0));
|
||||
assert!(BatchDeleteRoute::Marker(1).targets(1));
|
||||
assert!(!BatchDeleteRoute::Marker(1).targets(2));
|
||||
assert!(!BatchDeleteRoute::Inactive.targets(0));
|
||||
assert!(!BatchDeleteRoute::PendingMarker.targets(0));
|
||||
|
||||
let explicit = ObjectToDelete {
|
||||
object_name: "explicit".to_string(),
|
||||
@@ -9772,11 +9790,23 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!batch_delete_creates_latest_marker(&explicit, &versioned));
|
||||
assert!(batch_delete_targets_pool(false, Some(1), 0));
|
||||
assert!(BatchDeleteRoute::AllPools.targets(0));
|
||||
|
||||
let unversioned = DeleteReplicationConfigSnapshot::default();
|
||||
assert!(!batch_delete_creates_latest_marker(&latest, &unversioned));
|
||||
assert!(batch_delete_targets_pool(false, None, 0));
|
||||
assert!(BatchDeleteRoute::AllPools.targets(1));
|
||||
}
|
||||
|
||||
fn reduce_test_pool_results(
|
||||
mut error: Option<Error>,
|
||||
pool_results: impl IntoIterator<Item = (DeletedObject, Option<Error>)>,
|
||||
) -> (DeletedObject, Option<Error>, Option<BatchDeleteOutcome>) {
|
||||
let mut selected = error.as_ref().map(|_| BatchDeleteOutcome::Failed);
|
||||
let mut deleted = DeletedObject::default();
|
||||
for (pool_delete, pool_error) in pool_results {
|
||||
apply_batch_delete_pool_result(&mut selected, &mut deleted, &mut error, pool_delete, pool_error);
|
||||
}
|
||||
(deleted, error, selected)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -9802,15 +9832,14 @@ mod tests {
|
||||
let failed = (DeletedObject::default(), Some(source_error.clone()));
|
||||
let succeeded = (success.clone(), None);
|
||||
let pool_results = if source_first {
|
||||
vec![failed, succeeded]
|
||||
[failed, succeeded]
|
||||
} else {
|
||||
vec![succeeded, failed]
|
||||
[succeeded, failed]
|
||||
};
|
||||
|
||||
let (_, error, attempted) =
|
||||
resolve_batch_delete_pool_results(None, pool_results.iter().map(|(deleted, error)| (deleted, error)));
|
||||
let (_, error, selected) = reduce_test_pool_results(None, pool_results);
|
||||
|
||||
assert!(attempted);
|
||||
assert!(matches!(selected, Some(BatchDeleteOutcome::Failed)));
|
||||
assert_eq!(error, Some(source_error.clone()));
|
||||
}
|
||||
}
|
||||
@@ -9833,34 +9862,54 @@ mod tests {
|
||||
for missing_first in [true, false] {
|
||||
let succeeded = (success.clone(), None);
|
||||
let pool_results = if missing_first {
|
||||
vec![missing.clone(), succeeded]
|
||||
[missing.clone(), succeeded]
|
||||
} else {
|
||||
vec![succeeded, missing.clone()]
|
||||
[succeeded, missing.clone()]
|
||||
};
|
||||
let (deleted, error, attempted) =
|
||||
resolve_batch_delete_pool_results(None, pool_results.iter().map(|(deleted, error)| (deleted, error)));
|
||||
let (deleted, error, selected) = reduce_test_pool_results(None, pool_results);
|
||||
|
||||
assert!(attempted);
|
||||
let deleted = deleted.expect("successful pool result should be retained");
|
||||
assert!(matches!(selected, Some(BatchDeleteOutcome::Deleted)));
|
||||
assert!(deleted.found);
|
||||
assert_eq!(deleted.object_name, success.object_name.as_str());
|
||||
assert!(error.is_none());
|
||||
}
|
||||
|
||||
let missing_only = [missing];
|
||||
let (_, error, attempted) =
|
||||
resolve_batch_delete_pool_results(None, missing_only.iter().map(|(deleted, error)| (deleted, error)));
|
||||
assert!(attempted);
|
||||
let (_, error, selected) = reduce_test_pool_results(None, [missing]);
|
||||
assert!(matches!(selected, Some(BatchDeleteOutcome::Missing)));
|
||||
assert_eq!(error, Some(missing_error));
|
||||
}
|
||||
|
||||
let silent_missing = [(DeletedObject::default(), None)];
|
||||
let (_, error, attempted) =
|
||||
resolve_batch_delete_pool_results(None, silent_missing.iter().map(|(deleted, error)| (deleted, error)));
|
||||
assert!(attempted);
|
||||
let (_, error, selected) = reduce_test_pool_results(None, [(DeletedObject::default(), None)]);
|
||||
assert!(matches!(selected, Some(BatchDeleteOutcome::SilentMiss)));
|
||||
assert!(error.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_delete_pool_reduction_keeps_the_first_equal_outcome_and_preflight_error() {
|
||||
let miss = |name: &str| {
|
||||
(
|
||||
DeletedObject {
|
||||
object_name: name.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
Some(StorageError::ObjectNotFound("bucket".to_owned(), name.to_owned())),
|
||||
)
|
||||
};
|
||||
let silent = (DeletedObject::default(), None);
|
||||
let (deleted, error, selected) = reduce_test_pool_results(None, [silent, miss("first"), miss("second")]);
|
||||
assert!(matches!(selected, Some(BatchDeleteOutcome::Missing)));
|
||||
assert_eq!(deleted.object_name, "first");
|
||||
assert_eq!(error, miss("first").1);
|
||||
|
||||
let (deleted, error, _) = reduce_test_pool_results(
|
||||
Some(StorageError::PreconditionFailed),
|
||||
[(miss("pool").0, Some(StorageError::ErasureWriteQuorum))],
|
||||
);
|
||||
assert!(deleted.object_name.is_empty());
|
||||
assert_eq!(error, Some(StorageError::PreconditionFailed));
|
||||
assert!(reduce_test_pool_results(None, []).2.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lifecycle_null_version_cas_distinguishes_absent_and_replacement_pools() {
|
||||
use rustfs_gateway_types::persistence::PersistedVersioningConfiguration as VersioningConfiguration;
|
||||
@@ -13116,6 +13165,67 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn batch_delete_preserves_results_and_accounting_across_sets() {
|
||||
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
|
||||
ctx.update_erasure_type(SetupType::Erasure).await;
|
||||
let (_temp_dirs, sets) = make_local_two_set_sets_with_ctx(Arc::clone(&ctx)).await;
|
||||
let store = Arc::new(new_prepared_reader_test_store_from_pools(
|
||||
vec![Arc::clone(&sets)],
|
||||
vec![sets.endpoints.clone()],
|
||||
ctx,
|
||||
));
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(Arc::clone(&store), Vec::new()).await;
|
||||
let bucket = format!("batch-delete-{}", Uuid::new_v4().simple());
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create bucket on both sets");
|
||||
let keys: Vec<_> = [1, 0, 1]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, set)| {
|
||||
(0..100)
|
||||
.map(|suffix| format!("{index}-{suffix}"))
|
||||
.find(|key| Arc::ptr_eq(&sets.get_disks_by_key(key), &sets.disk_set[set]))
|
||||
.expect("fixture key routed to the selected set")
|
||||
})
|
||||
.collect();
|
||||
for indices in [&[0, 1, 2][..], &[0, 2, 1], &[0, 2], &[1]] {
|
||||
for &index in indices {
|
||||
let mut data = PutObjReader::from_vec(vec![0; index + 1]);
|
||||
sets.put_object(&bucket, &keys[index], &mut data, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("seed an object with a distinct size");
|
||||
}
|
||||
let batch = indices
|
||||
.iter()
|
||||
.map(|&index| ObjectToDelete {
|
||||
object_name: keys[index].clone(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
let (deleted, errors, accounting) = sets
|
||||
.delete_objects_with_accounting(&bucket, batch, ObjectOptions::default())
|
||||
.await;
|
||||
|
||||
assert_eq!(errors.len(), indices.len());
|
||||
assert!(errors.iter().all(Option::is_none), "{errors:?}");
|
||||
assert_eq!(
|
||||
deleted.iter().map(|object| object.object_name.as_str()).collect::<Vec<_>>(),
|
||||
indices.iter().map(|&index| keys[index].as_str()).collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
accounting
|
||||
.into_iter()
|
||||
.map(|receipt| receipt.and_then(|receipt| receipt.size))
|
||||
.collect::<Vec<_>>(),
|
||||
indices.iter().map(|&index| u64::try_from(index + 1).ok()).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn select_snapshot_allows_store_delete_for_object_in_nonzero_set() {
|
||||
|
||||
@@ -74,7 +74,7 @@ static GET_STAGE_LOCAL_SUMMARY_SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
type GetStageLocalSummaryKey = (&'static str, &'static str, &'static str, &'static str);
|
||||
|
||||
/// Sampled local aggregate for one bounded GetObject stage label set.
|
||||
/// Sampled local aggregate for one bounded stage label set.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct GetStageLocalSummary {
|
||||
pub path: &'static str,
|
||||
@@ -85,7 +85,21 @@ pub struct GetStageLocalSummary {
|
||||
pub duration_nanoseconds: u64,
|
||||
}
|
||||
|
||||
static GET_STAGE_LOCAL_SUMMARY: LazyLock<Mutex<HashMap<GetStageLocalSummaryKey, GetStageLocalSummary>>> =
|
||||
impl GetStageLocalSummary {
|
||||
fn key(&self) -> GetStageLocalSummaryKey {
|
||||
(self.path, self.stage, self.object_class, self.size_bucket)
|
||||
}
|
||||
}
|
||||
|
||||
/// A local summary row with its peak in the same sampling window.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct GetStageLocalSummaryWithMax {
|
||||
pub summary: GetStageLocalSummary,
|
||||
/// Largest sampled duration since the previous drain.
|
||||
pub max_duration_nanoseconds: u64,
|
||||
}
|
||||
|
||||
static GET_STAGE_LOCAL_SUMMARY: LazyLock<Mutex<HashMap<GetStageLocalSummaryKey, GetStageLocalSummaryWithMax>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Global switch for all remaining (non GET/PUT-stage) metric emission in this
|
||||
@@ -130,12 +144,23 @@ pub fn get_stage_local_summary_sample_rate() -> u64 {
|
||||
}
|
||||
|
||||
pub fn take_get_stage_local_summary() -> Vec<GetStageLocalSummary> {
|
||||
let mut rows = drain_get_stage_local_summary(|row| row.summary);
|
||||
rows.sort_unstable_by_key(GetStageLocalSummary::key);
|
||||
rows
|
||||
}
|
||||
|
||||
/// Drain the same sampling window as [`take_get_stage_local_summary`] and include each sorted row's maximum.
|
||||
pub fn take_get_stage_local_summary_with_max() -> Vec<GetStageLocalSummaryWithMax> {
|
||||
let mut rows = drain_get_stage_local_summary(std::convert::identity);
|
||||
rows.sort_unstable_by_key(|row| row.summary.key());
|
||||
rows
|
||||
}
|
||||
|
||||
fn drain_get_stage_local_summary<T>(mut project: impl FnMut(GetStageLocalSummaryWithMax) -> T) -> Vec<T> {
|
||||
let Ok(mut summary) = GET_STAGE_LOCAL_SUMMARY.lock() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut rows = summary.drain().map(|(_, row)| row).collect::<Vec<_>>();
|
||||
rows.sort_unstable_by_key(|row| (row.path, row.stage, row.object_class, row.size_bucket));
|
||||
rows
|
||||
summary.drain().map(|(_, row)| project(row)).collect()
|
||||
}
|
||||
|
||||
fn record_get_stage_local_summary(
|
||||
@@ -165,16 +190,20 @@ fn record_get_stage_local_summary(
|
||||
let Ok(mut summary) = GET_STAGE_LOCAL_SUMMARY.lock() else {
|
||||
return;
|
||||
};
|
||||
let row = summary.entry(key).or_insert_with(|| GetStageLocalSummary {
|
||||
path,
|
||||
stage,
|
||||
object_class,
|
||||
size_bucket,
|
||||
sampled_count: 0,
|
||||
duration_nanoseconds: 0,
|
||||
let row = summary.entry(key).or_insert_with(|| GetStageLocalSummaryWithMax {
|
||||
summary: GetStageLocalSummary {
|
||||
path,
|
||||
stage,
|
||||
object_class,
|
||||
size_bucket,
|
||||
sampled_count: 0,
|
||||
duration_nanoseconds: 0,
|
||||
},
|
||||
max_duration_nanoseconds: 0,
|
||||
});
|
||||
row.sampled_count = row.sampled_count.saturating_add(1);
|
||||
row.duration_nanoseconds = row.duration_nanoseconds.saturating_add(duration_nanoseconds);
|
||||
row.summary.sampled_count = row.summary.sampled_count.saturating_add(1);
|
||||
row.summary.duration_nanoseconds = row.summary.duration_nanoseconds.saturating_add(duration_nanoseconds);
|
||||
row.max_duration_nanoseconds = row.max_duration_nanoseconds.max(duration_nanoseconds);
|
||||
}
|
||||
|
||||
/// Enable or disable general (non GET/PUT-stage) metric emission.
|
||||
@@ -232,6 +261,9 @@ pub const PUT_STAGE_PUT_OBJECT_OPERATION_AWAIT_TOTAL: &str = "put_object_operati
|
||||
pub const PUT_STAGE_PUT_OBJECT_OPERATION_BODY_TO_COMMIT_SUBMIT: &str = "put_object_operation_body_to_commit_submit";
|
||||
pub const PUT_STAGE_PUT_OBJECT_OPERATION_RESULT_RETURN: &str = "put_object_operation_result_return";
|
||||
pub const PUT_STAGE_PUT_OBJECT_OPERATION_FIRST_POLL_DELAY: &str = "put_object_operation_first_poll_delay";
|
||||
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK: &str = "put_object_commit_ready_snapshot_lifecycle_lock";
|
||||
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK: &str = "put_object_commit_ready_snapshot_metadata_lock";
|
||||
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ: &str = "put_object_commit_ready_snapshot_authority_read";
|
||||
pub const PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_ACQUIRED_TO_COMMIT_READY: &str =
|
||||
"put_object_commit_namespace_lock_acquired_to_commit_ready";
|
||||
pub const PUT_STAGE_PUT_OBJECT_COMMIT_READY_PRECONDITION_AND_TIMESTAMP: &str =
|
||||
@@ -4547,6 +4579,9 @@ mod tests {
|
||||
PUT_STAGE_PUT_OBJECT_OPERATION_BODY_TO_COMMIT_SUBMIT,
|
||||
PUT_STAGE_PUT_OBJECT_OPERATION_RESULT_RETURN,
|
||||
PUT_STAGE_PUT_OBJECT_OPERATION_FIRST_POLL_DELAY,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_LIFECYCLE_LOCK,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_METADATA_LOCK,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_SNAPSHOT_AUTHORITY_READ,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_ACQUIRED_TO_COMMIT_READY,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_PRECONDITION_AND_TIMESTAMP,
|
||||
PUT_STAGE_PUT_OBJECT_COMMIT_READY_EXPECTED_VERSION_LOOKUP,
|
||||
|
||||
@@ -21,13 +21,17 @@ pub(super) fn rules() -> Vec<Rule> {
|
||||
vec![
|
||||
Rule {
|
||||
evidence_fields: strings(["host"]),
|
||||
anchors: strings(["Create pool endpoints host"]),
|
||||
anchors: strings(["startup_endpoint_dns_failed", "Startup endpoint DNS resolution failed"]),
|
||||
..base(
|
||||
"endpoint-resolve-failed",
|
||||
P1Unavailable,
|
||||
"startup",
|
||||
"启动期端点主机名解析失败",
|
||||
all([contains("Create pool endpoints host"), contains("not found")]),
|
||||
any([
|
||||
field("event", "startup_endpoint_dns_failed"),
|
||||
contains("Startup endpoint DNS resolution failed"),
|
||||
all([contains("Create pool endpoints host"), contains("not found")]),
|
||||
]),
|
||||
"启动期端点主机名解析失败(DNS 未就绪/拼写错误/hosts 缺失)。",
|
||||
"容器/K8s 场景确认 DNS 就绪顺序;核对 volumes 参数拼写。",
|
||||
)
|
||||
|
||||
@@ -453,6 +453,15 @@ fn smoke_samples_hit_exact_rule_sets() {
|
||||
&["unknown-access-key"],
|
||||
);
|
||||
exact(&msg("HTTP transport failed: BrokenPipe while streaming response body"), &[]);
|
||||
exact(
|
||||
&Sample {
|
||||
fields: &[("event", "startup_endpoint_dns_failed"), ("host", "node5")],
|
||||
..msg("DNS deadline exhausted")
|
||||
},
|
||||
&["endpoint-resolve-failed"],
|
||||
);
|
||||
exact(&msg("Startup endpoint DNS resolution failed"), &["endpoint-resolve-failed"]);
|
||||
exact(&msg("retrying endpoint local-host detection after temporary DNS error"), &[]);
|
||||
// Internode auth failures legitimately hit both the internode rule and
|
||||
// the generic client signature rule.
|
||||
exact(
|
||||
|
||||
@@ -65,10 +65,17 @@ pub fn minio_index_storage_bytes(index: &Index) -> Bytes {
|
||||
.unwrap_or(encoded)
|
||||
}
|
||||
|
||||
/// Decodes a complete framed S2 index or its headerless metadata payload.
|
||||
pub fn decode_minio_index_bytes(bytes: &Bytes) -> Option<Index> {
|
||||
let decoded = S2Index::load(bytes.as_ref())
|
||||
.or_else(|_| S2Index::load(&restore_index_headers(bytes.as_ref())))
|
||||
.ok()?;
|
||||
let bytes = bytes.as_ref();
|
||||
// An unframed index starts with a nonnegative signed varint. Its
|
||||
// low bit is clear, so it cannot start with the odd frame marker.
|
||||
let body = if bytes.first() == Some(&CHUNK_TYPE_INDEX) {
|
||||
remove_index_headers(bytes)?
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
let decoded = S2Index::load_body(body).ok()?;
|
||||
|
||||
let mut index = Index::new();
|
||||
for info in decoded.info {
|
||||
@@ -165,26 +172,7 @@ impl S2Index {
|
||||
false
|
||||
}
|
||||
|
||||
fn load(mut bytes: &[u8]) -> io::Result<Self> {
|
||||
if bytes.len() <= SKIPPABLE_FRAME_HEADER + S2_INDEX_HEADER.len() + S2_INDEX_TRAILER.len() {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
|
||||
}
|
||||
if bytes[0] != CHUNK_TYPE_INDEX {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index chunk type"));
|
||||
}
|
||||
|
||||
let chunk_len = (bytes[1] as usize) | ((bytes[2] as usize) << 8) | ((bytes[3] as usize) << 16);
|
||||
bytes = &bytes[SKIPPABLE_FRAME_HEADER..];
|
||||
if bytes.len() < chunk_len {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
|
||||
}
|
||||
bytes = &bytes[..chunk_len];
|
||||
|
||||
if !bytes.starts_with(S2_INDEX_HEADER) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index header"));
|
||||
}
|
||||
bytes = &bytes[S2_INDEX_HEADER.len()..];
|
||||
|
||||
fn load_body(mut bytes: &[u8]) -> io::Result<Self> {
|
||||
let (total_uncompressed, used) = read_varint(bytes)?;
|
||||
if total_uncompressed < 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid uncompressed size"));
|
||||
@@ -234,7 +222,10 @@ impl S2Index {
|
||||
|
||||
if idx > 0 {
|
||||
let prev = info[idx - 1].uncompressed_offset;
|
||||
uncompressed_offset += prev + est_block_uncompressed;
|
||||
uncompressed_offset = prev
|
||||
.checked_add(est_block_uncompressed)
|
||||
.and_then(|base| base.checked_add(uncompressed_offset))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "uncompressed index offset overflow"))?;
|
||||
if uncompressed_offset <= prev {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid uncompressed offset"));
|
||||
}
|
||||
@@ -251,9 +242,14 @@ impl S2Index {
|
||||
bytes = &bytes[used..];
|
||||
|
||||
if idx > 0 {
|
||||
let next_compressed_predict = compressed_predict + compressed_offset / 2;
|
||||
let next_compressed_predict = compressed_predict
|
||||
.checked_add(compressed_offset / 2)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index prediction overflow"))?;
|
||||
let prev = info[idx - 1].compressed_offset;
|
||||
compressed_offset += prev + compressed_predict;
|
||||
compressed_offset = prev
|
||||
.checked_add(compressed_predict)
|
||||
.and_then(|base| base.checked_add(compressed_offset))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index offset overflow"))?;
|
||||
if compressed_offset <= prev {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid compressed offset"));
|
||||
}
|
||||
@@ -265,12 +261,8 @@ impl S2Index {
|
||||
info[idx].compressed_offset = compressed_offset;
|
||||
}
|
||||
|
||||
if bytes.len() < 4 + S2_INDEX_TRAILER.len() {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "buffer too small"));
|
||||
}
|
||||
bytes = &bytes[4..];
|
||||
if !bytes.starts_with(S2_INDEX_TRAILER) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid index trailer"));
|
||||
if !bytes.is_empty() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "trailing bytes in index body"));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
@@ -290,10 +282,9 @@ fn remove_index_headers(bytes: &[u8]) -> Option<&[u8]> {
|
||||
|
||||
let chunk_len = (bytes[1] as usize) | ((bytes[2] as usize) << 8) | ((bytes[3] as usize) << 16);
|
||||
let bytes = &bytes[SKIPPABLE_FRAME_HEADER..];
|
||||
if bytes.len() < chunk_len {
|
||||
if bytes.len() != chunk_len {
|
||||
return None;
|
||||
}
|
||||
let bytes = &bytes[..chunk_len];
|
||||
|
||||
let bytes = bytes.strip_prefix(S2_INDEX_HEADER)?;
|
||||
let bytes = bytes.strip_suffix(S2_INDEX_TRAILER)?;
|
||||
@@ -303,25 +294,6 @@ fn remove_index_headers(bytes: &[u8]) -> Option<&[u8]> {
|
||||
Some(&bytes[..bytes.len() - 4])
|
||||
}
|
||||
|
||||
fn restore_index_headers(input: &[u8]) -> Vec<u8> {
|
||||
if input.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut bytes = Vec::with_capacity(SKIPPABLE_FRAME_HEADER + S2_INDEX_HEADER.len() + input.len() + 4 + S2_INDEX_TRAILER.len());
|
||||
bytes.extend_from_slice(&[CHUNK_TYPE_INDEX, 0, 0, 0]);
|
||||
bytes.extend_from_slice(S2_INDEX_HEADER);
|
||||
bytes.extend_from_slice(input);
|
||||
bytes.extend_from_slice(&((bytes.len() + 4 + S2_INDEX_TRAILER.len()) as u32).to_le_bytes());
|
||||
bytes.extend_from_slice(S2_INDEX_TRAILER);
|
||||
|
||||
let chunk_len = bytes.len() - SKIPPABLE_FRAME_HEADER;
|
||||
bytes[1] = chunk_len as u8;
|
||||
bytes[2] = (chunk_len >> 8) as u8;
|
||||
bytes[3] = (chunk_len >> 16) as u8;
|
||||
bytes
|
||||
}
|
||||
|
||||
fn write_varint(out: &mut Vec<u8>, value: i64) {
|
||||
let mut unsigned = ((value as u64) << 1) ^ ((value >> 63) as u64);
|
||||
while unsigned >= 0x80 {
|
||||
@@ -342,10 +314,10 @@ fn read_uvarint(bytes: &[u8]) -> io::Result<(u64, usize)> {
|
||||
let mut shift = 0_u32;
|
||||
|
||||
for (idx, byte) in bytes.iter().copied().enumerate() {
|
||||
if idx == 9 && byte > 1 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "varint overflow"));
|
||||
}
|
||||
if byte < 0x80 {
|
||||
if idx > 9 || (idx == 9 && byte > 1) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "varint overflow"));
|
||||
}
|
||||
return Ok((value | ((byte as u64) << shift), idx + 1));
|
||||
}
|
||||
|
||||
@@ -388,15 +360,7 @@ mod tests {
|
||||
source.total_compressed = 3_000_000;
|
||||
|
||||
let stored = minio_index_storage_bytes(&source);
|
||||
assert!(!stored.starts_with(&[CHUNK_TYPE_INDEX, 0x2a, 0x4d, 0x18]));
|
||||
assert_eq!(
|
||||
S2Index::load(&restore_index_headers(&stored))
|
||||
.expect("restore full index")
|
||||
.info
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
|
||||
assert_ne!(stored.first(), Some(&CHUNK_TYPE_INDEX));
|
||||
let decoded = decode_minio_index_bytes(&stored).expect("decode headerless MinIO index");
|
||||
assert_eq!(decoded.total_uncompressed, source.total_uncompressed);
|
||||
assert_eq!(decoded.total_compressed, source.total_compressed);
|
||||
@@ -423,12 +387,17 @@ mod tests {
|
||||
let full = index.into_full_bytes();
|
||||
assert_eq!(full[0], CHUNK_TYPE_INDEX);
|
||||
let headerless = Bytes::copy_from_slice(remove_index_headers(full.as_ref()).expect("strip index headers"));
|
||||
let restored = restore_index_headers(&headerless);
|
||||
assert_eq!(restored[0], CHUNK_TYPE_INDEX);
|
||||
for bytes in [&full, &headerless] {
|
||||
let decoded = decode_minio_index_bytes(bytes).expect("decode index with unknown compressed total");
|
||||
assert_eq!(decoded.total_uncompressed, 4_194_304);
|
||||
assert_eq!(decoded.total_compressed, -1);
|
||||
assert_eq!(decoded.find(2_097_152).unwrap(), (1_048_576, 2_097_152));
|
||||
|
||||
let decoded = decode_minio_index_bytes(&headerless).expect("decode index with unknown compressed total");
|
||||
assert_eq!(decoded.total_uncompressed, 4_194_304);
|
||||
assert_eq!(decoded.total_compressed, -1);
|
||||
assert_eq!(decoded.find(2_097_152).unwrap(), (1_048_576, 2_097_152));
|
||||
let truncated = bytes.slice(..bytes.len() - 1);
|
||||
assert!(decode_minio_index_bytes(&truncated).is_none());
|
||||
let mut trailing = bytes.to_vec();
|
||||
trailing.push(0);
|
||||
assert!(decode_minio_index_bytes(&Bytes::from(trailing)).is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ impl Index {
|
||||
));
|
||||
}
|
||||
|
||||
if latest.uncompressed_offset + MIN_INDEX_DIST > uncompressed_offset {
|
||||
if uncompressed_offset.saturating_sub(latest.uncompressed_offset) < MIN_INDEX_DIST {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -150,34 +150,23 @@ impl Index {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "empty index"));
|
||||
}
|
||||
|
||||
if self.info.len() > 200 {
|
||||
let n = self
|
||||
.info
|
||||
.binary_search_by(|info| {
|
||||
if info.uncompressed_offset > offset {
|
||||
std::cmp::Ordering::Greater
|
||||
} else {
|
||||
std::cmp::Ordering::Less
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|i| i);
|
||||
Ok(self.checkpoint_at_or_before(offset).unwrap_or((0, 0)))
|
||||
}
|
||||
|
||||
if n == 0 {
|
||||
return Ok((self.info[0].compressed_offset, self.info[0].uncompressed_offset));
|
||||
}
|
||||
return Ok((self.info[n - 1].compressed_offset, self.info[n - 1].uncompressed_offset));
|
||||
}
|
||||
/// Returns the last recorded (stored, plaintext) offset at or before `offset`.
|
||||
/// Index totals can be stale, so the caller must check the actual part bounds.
|
||||
pub fn checkpoint_at_or_before(&self, offset: i64) -> Option<(i64, i64)> {
|
||||
let next = self.info.partition_point(|entry| entry.uncompressed_offset <= offset);
|
||||
let entry = self.info.get(next.checked_sub(1)?)?;
|
||||
Some((entry.compressed_offset, entry.uncompressed_offset))
|
||||
}
|
||||
|
||||
let mut compressed_off = 0;
|
||||
let mut uncompressed_off = 0;
|
||||
for info in &self.info {
|
||||
if info.uncompressed_offset > offset {
|
||||
break;
|
||||
}
|
||||
compressed_off = info.compressed_offset;
|
||||
uncompressed_off = info.uncompressed_offset;
|
||||
}
|
||||
Ok((compressed_off, uncompressed_off))
|
||||
/// Returns the first recorded (stored, plaintext) offset at or after `offset`.
|
||||
/// Index totals can be stale, so the caller must check the actual part bounds.
|
||||
pub fn checkpoint_at_or_after(&self, offset: i64) -> Option<(i64, i64)> {
|
||||
let next = self.info.partition_point(|entry| entry.uncompressed_offset < offset);
|
||||
let entry = self.info.get(next)?;
|
||||
Some((entry.compressed_offset, entry.uncompressed_offset))
|
||||
}
|
||||
|
||||
fn reduce(&mut self) {
|
||||
@@ -366,7 +355,10 @@ impl Index {
|
||||
|
||||
if idx > 0 {
|
||||
let prev = self.info[idx - 1].uncompressed_offset;
|
||||
u_off += prev + self.est_block_uncomp;
|
||||
u_off = prev
|
||||
.checked_add(self.est_block_uncomp)
|
||||
.and_then(|base| base.checked_add(u_off))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "uncompressed index offset overflow"))?;
|
||||
if u_off <= prev {
|
||||
return Err(io::Error::other("invalid offset"));
|
||||
}
|
||||
@@ -385,9 +377,14 @@ impl Index {
|
||||
b = &b[n..];
|
||||
|
||||
if idx > 0 {
|
||||
let next_c_predict = c_predict + c_off / 2;
|
||||
let next_c_predict = c_predict
|
||||
.checked_add(c_off / 2)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index prediction overflow"))?;
|
||||
let prev = self.info[idx - 1].compressed_offset;
|
||||
c_off += prev + c_predict;
|
||||
c_off = prev
|
||||
.checked_add(c_predict)
|
||||
.and_then(|base| base.checked_add(c_off))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "compressed index offset overflow"))?;
|
||||
if c_off <= prev {
|
||||
return Err(io::Error::other("invalid offset"));
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
use crate::compress_index::{Index, TryGetIndex};
|
||||
use pin_project_lite::pin_project;
|
||||
use rustfs_utils::compress::{CompressionAlgorithm, compress_block, decompress_block_with_limit};
|
||||
use rustfs_utils::compress::{CompressionAlgorithm, compress_block, decompress_block_into};
|
||||
use rustfs_utils::{put_uvarint, uvarint};
|
||||
use std::cmp::min;
|
||||
use std::io::{self};
|
||||
@@ -177,7 +177,7 @@ where
|
||||
delegate_reader_capabilities_generic_no_index!(CompressReader<R>, inner);
|
||||
|
||||
pin_project! {
|
||||
/// A reader wrapper that decompresses data on the fly using DEFLATE algorithm.
|
||||
/// Streams legacy compressed blocks after verifying their decoded length and checksum.
|
||||
/// Header format:
|
||||
/// - First byte: compression type (00 = compressed, 01 = uncompressed, FF = end)
|
||||
/// - Bytes 1-3: length of compressed data (little-endian)
|
||||
@@ -347,97 +347,19 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
let typ = this.header_buf[0];
|
||||
let crc = (this.header_buf[4] as u32)
|
||||
| ((this.header_buf[5] as u32) << 8)
|
||||
| ((this.header_buf[6] as u32) << 16)
|
||||
| ((this.header_buf[7] as u32) << 24);
|
||||
let compressed_buf = &this.compressed_buf[..*this.compressed_len];
|
||||
// `compressed_buf`'s length comes from the untrusted 24-bit header length field, so it
|
||||
// can be shorter than 16 bytes. `uvarint` is safe on any slice length (reads at most 10
|
||||
// bytes and stops at the terminator), so pass the whole slice instead of a fixed
|
||||
// `[0..16]` index that panics on corrupted/truncated blocks shorter than 16 bytes.
|
||||
let (uncompress_len, uvarint) = uvarint(compressed_buf);
|
||||
// Reject a length prefix that could not be decoded: `uvarint <= 0` means the varint was
|
||||
// empty/unterminated (0) or overflowed (negative — as usize it would index far past the
|
||||
// buffer and panic the slice below). The `> len` bound is belt-and-suspenders (uvarint's
|
||||
// positive return is always <= buf.len()) but keeps the slice panic-free regardless.
|
||||
if uvarint <= 0 || uvarint as usize > compressed_buf.len() {
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid compressed block length prefix")));
|
||||
}
|
||||
// Bound the untrusted declared plaintext length up front and enforce it
|
||||
// inside the decoder so a small block cannot expand into GiB before the
|
||||
// post-decode length check runs.
|
||||
if uncompress_len > MAX_BLOCK_PLAINTEXT_LEN {
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Compressed block declares an oversized length",
|
||||
)));
|
||||
}
|
||||
let Ok(uncompress_len_usize) = usize::try_from(uncompress_len) else {
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"Compressed block declares an oversized length",
|
||||
)));
|
||||
};
|
||||
let compressed_data = &compressed_buf[uvarint as usize..];
|
||||
let decompressed = if typ == COMPRESS_TYPE_COMPRESSED {
|
||||
match decompress_block_with_limit(compressed_data, *this.compression_algorithm, uncompress_len_usize) {
|
||||
Ok(out) => out,
|
||||
Err(e) => {
|
||||
// error!("DecompressReader decompress_block error: {e}");
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(e));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// The header phase already rejected every type other than
|
||||
// COMPRESS_TYPE_COMPRESSED / COMPRESS_TYPE_UNCOMPRESSED.
|
||||
compressed_data.to_vec()
|
||||
};
|
||||
if decompressed.is_empty() {
|
||||
// The writer never emits zero-length plaintext blocks; an empty
|
||||
// decode surfacing as Ready(Ok) with no bytes would read as EOF and
|
||||
// silently truncate the stream.
|
||||
*this.poisoned = true;
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Empty compressed block")));
|
||||
}
|
||||
if decompressed.len() != uncompress_len_usize {
|
||||
// error!("DecompressReader decompressed length mismatch: {} != {}", decompressed.len(), uncompress_len);
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "Decompressed length mismatch")));
|
||||
}
|
||||
let actual_crc = {
|
||||
let mut hasher = crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc32IsoHdlc);
|
||||
hasher.update(&decompressed);
|
||||
hasher.finalize() as u32
|
||||
};
|
||||
if actual_crc != crc {
|
||||
// error!("DecompressReader CRC32 mismatch: actual {actual_crc} != expected {crc}");
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::InvalidData, "CRC32 mismatch")));
|
||||
}
|
||||
*this.buffer = decompressed;
|
||||
*this.buffer_pos = 0;
|
||||
let result = decode_block(
|
||||
this.header_buf,
|
||||
&this.compressed_buf[..*this.compressed_len],
|
||||
*this.compression_algorithm,
|
||||
this.buffer,
|
||||
);
|
||||
*this.compressed_read = 0;
|
||||
*this.compressed_len = 0;
|
||||
if let Err(error) = result {
|
||||
this.buffer.clear();
|
||||
*this.poisoned = true;
|
||||
return Poll::Ready(Err(error));
|
||||
}
|
||||
let to_copy = min(buf.remaining(), this.buffer.len());
|
||||
buf.put_slice(&this.buffer[..to_copy]);
|
||||
*this.buffer_pos += to_copy;
|
||||
@@ -451,6 +373,50 @@ where
|
||||
|
||||
delegate_reader_capabilities_generic_no_index!(DecompressReader<R>, inner);
|
||||
|
||||
fn decode_block(
|
||||
header: &[u8; HEADER_LEN],
|
||||
payload: &[u8],
|
||||
algorithm: CompressionAlgorithm,
|
||||
output: &mut Vec<u8>,
|
||||
) -> io::Result<()> {
|
||||
let (declared_len, prefix_len) = uvarint(payload);
|
||||
let data = usize::try_from(prefix_len)
|
||||
.ok()
|
||||
.filter(|len| *len != 0)
|
||||
.and_then(|len| payload.get(len..))
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Invalid compressed block length prefix"))?;
|
||||
let declared_len = usize::try_from(declared_len)
|
||||
.ok()
|
||||
.filter(|_| declared_len <= MAX_BLOCK_PLAINTEXT_LEN)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Compressed block declares an oversized length"))?;
|
||||
|
||||
let compressed = header[0] == COMPRESS_TYPE_COMPRESSED;
|
||||
let plaintext = if compressed {
|
||||
decompress_block_into(data, algorithm, declared_len, output)?;
|
||||
output.as_slice()
|
||||
} else {
|
||||
data
|
||||
};
|
||||
if plaintext.is_empty() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "Empty compressed block"));
|
||||
}
|
||||
if plaintext.len() != declared_len {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "Decompressed length mismatch"));
|
||||
}
|
||||
let expected_crc = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
|
||||
let mut hasher = crc_fast::Digest::new(crc_fast::CrcAlgorithm::Crc32IsoHdlc);
|
||||
hasher.update(plaintext);
|
||||
if hasher.finalize() as u32 != expected_crc {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "CRC32 mismatch"));
|
||||
}
|
||||
|
||||
if !compressed {
|
||||
output.clear();
|
||||
output.extend_from_slice(data);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build compressed block with header + uvarint + compressed data
|
||||
fn build_compressed_block(uncompressed_data: &[u8], compression_algorithm: CompressionAlgorithm) -> Vec<u8> {
|
||||
let crc = {
|
||||
@@ -503,6 +469,43 @@ mod tests {
|
||||
assert_eq!(&decompressed, data);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decompress_reader_reuses_the_verified_plaintext_buffer() {
|
||||
let algorithm = CompressionAlgorithm::Lz4;
|
||||
let len = 128 * 1024;
|
||||
let first = vec![0x23; len];
|
||||
let second = vec![0x45; len];
|
||||
let mut stored = build_compressed_block(&first, algorithm);
|
||||
stored.extend_from_slice(&build_compressed_block(&second, algorithm));
|
||||
let mut bad_crc = build_compressed_block(&first, algorithm);
|
||||
bad_crc[4] ^= 1;
|
||||
stored.extend_from_slice(&bad_crc);
|
||||
|
||||
let mut reader = DecompressReader::new(Cursor::new(stored), algorithm);
|
||||
let mut output = vec![0; len];
|
||||
reader.read_exact(&mut output).await.unwrap();
|
||||
assert_eq!(output, first);
|
||||
let allocation = reader.buffer.as_ptr();
|
||||
|
||||
reader.read_exact(&mut output).await.unwrap();
|
||||
assert_eq!(output, second);
|
||||
assert_eq!(
|
||||
reader.buffer.as_ptr(),
|
||||
allocation,
|
||||
"equal-sized blocks should reuse the output allocation"
|
||||
);
|
||||
|
||||
let mut probe = [0xa5; 16];
|
||||
for _ in 0..2 {
|
||||
let error = reader
|
||||
.read(&mut probe)
|
||||
.await
|
||||
.expect_err("a rejected block must never be readable");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
|
||||
assert_eq!(probe, [0xa5; 16]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_compress_reader_basic_deflate() {
|
||||
let data = b"hello world, hello world, hello world!";
|
||||
|
||||
@@ -141,37 +141,57 @@ pub fn decompress_block(compressed: &[u8], algorithm: CompressionAlgorithm) -> i
|
||||
/// Returns [`io::ErrorKind::InvalidData`] if the decompressed output exceeds `max_len`,
|
||||
/// or propagates any underlying codec initialization or decoding error.
|
||||
pub fn decompress_block_with_limit(compressed: &[u8], algorithm: CompressionAlgorithm, max_len: usize) -> io::Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
decompress_block_into(compressed, algorithm, max_len, &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decodes a block into a reusable buffer. Replaces its contents and caps the output at `max_len`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`io::ErrorKind::InvalidData`] if the output exceeds the limit, or propagates
|
||||
/// a codec error. The output is empty on error and retains its capacity for reuse.
|
||||
pub fn decompress_block_into(
|
||||
compressed: &[u8],
|
||||
algorithm: CompressionAlgorithm,
|
||||
max_len: usize,
|
||||
out: &mut Vec<u8>,
|
||||
) -> io::Result<()> {
|
||||
out.clear();
|
||||
let input = std::io::Cursor::new(compressed);
|
||||
match algorithm {
|
||||
CompressionAlgorithm::Gzip => read_to_end_with_limit(flate2::read::GzDecoder::new(input), max_len),
|
||||
CompressionAlgorithm::Deflate => read_to_end_with_limit(flate2::read::DeflateDecoder::new(input), max_len),
|
||||
let result = match algorithm {
|
||||
CompressionAlgorithm::Gzip => read_to_end_with_limit(flate2::read::GzDecoder::new(input), max_len, out),
|
||||
CompressionAlgorithm::Deflate => read_to_end_with_limit(flate2::read::DeflateDecoder::new(input), max_len, out),
|
||||
CompressionAlgorithm::Zstd => {
|
||||
let mut decoder = zstd::Decoder::new(input)?;
|
||||
if max_len <= ZSTD_BOUNDED_BLOCK_LIMIT {
|
||||
decoder.window_log_max(ZSTD_BLOCK_MAX_WINDOW_LOG)?;
|
||||
}
|
||||
read_to_end_with_limit(decoder, max_len)
|
||||
read_to_end_with_limit(decoder, max_len, out)
|
||||
}
|
||||
CompressionAlgorithm::Lz4 => read_to_end_with_limit(lz4::Decoder::new(input)?, max_len),
|
||||
CompressionAlgorithm::Brotli => read_to_end_with_limit(brotli::Decompressor::new(input, 4096), max_len),
|
||||
CompressionAlgorithm::Snappy => read_to_end_with_limit(snap::read::FrameDecoder::new(input), max_len),
|
||||
CompressionAlgorithm::None => Ok(Vec::new()),
|
||||
CompressionAlgorithm::Lz4 => read_to_end_with_limit(lz4::Decoder::new(input)?, max_len, out),
|
||||
CompressionAlgorithm::Brotli => read_to_end_with_limit(brotli::Decompressor::new(input, 4096), max_len, out),
|
||||
CompressionAlgorithm::Snappy => read_to_end_with_limit(snap::read::FrameDecoder::new(input), max_len, out),
|
||||
CompressionAlgorithm::None => Ok(()),
|
||||
};
|
||||
if result.is_err() {
|
||||
out.clear();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn read_to_end_with_limit(decoder: impl Read, max_len: usize) -> io::Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
// Read at most one byte past `max_len`: enough to distinguish an exact-length
|
||||
// frame (and verify its trailer) from an over-limit expansion without unbounded allocation.
|
||||
fn read_to_end_with_limit(decoder: impl Read, max_len: usize, out: &mut Vec<u8>) -> io::Result<()> {
|
||||
// Probe past the limit to verify an exact-length frame's trailer and reject expansion.
|
||||
let probe_len = u64::try_from(max_len).unwrap_or(u64::MAX).saturating_add(1);
|
||||
decoder.take(probe_len).read_to_end(&mut out)?;
|
||||
decoder.take(probe_len).read_to_end(out)?;
|
||||
if out.len() > max_len {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"decompressed block exceeds its declared length",
|
||||
));
|
||||
}
|
||||
Ok(out)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -254,10 +274,11 @@ mod tests {
|
||||
CompressionAlgorithm::Snappy,
|
||||
] {
|
||||
let compressed = compress_block(&data, algo);
|
||||
let exact = decompress_block_with_limit(&compressed, algo, data.len()).expect("exact limit should succeed");
|
||||
let mut exact = decompress_block_with_limit(&compressed, algo, data.len()).expect("exact limit should succeed");
|
||||
assert_eq!(exact, data, "{algo}");
|
||||
|
||||
let err = decompress_block_with_limit(&compressed, algo, data.len() - 1).expect_err("limit must be enforced");
|
||||
let err = decompress_block_into(&compressed, algo, data.len() - 1, &mut exact).expect_err("limit must be enforced");
|
||||
assert!(exact.is_empty(), "an error must clear reused output");
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{algo}");
|
||||
assert_eq!(err.to_string(), "decompressed block exceeds its declared length", "{algo}");
|
||||
|
||||
|
||||
+6
-14
@@ -26,7 +26,7 @@ use tracing::{error, info};
|
||||
use transform_stream::AsyncTryStream;
|
||||
use url::{Host, Url};
|
||||
|
||||
static LOCAL_IPS: LazyLock<Vec<IpAddr>> = LazyLock::new(get_local_ips_with_fallback);
|
||||
static LOCAL_IPS: LazyLock<HashSet<IpAddr>> = LazyLock::new(|| get_local_ips_with_fallback().into_iter().collect());
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct DnsCacheEntry {
|
||||
@@ -203,15 +203,10 @@ pub fn check_local_server_addr(server_addr: &str) -> std::io::Result<SocketAddr>
|
||||
/// checks if the given parameter correspond to one of
|
||||
/// the local IP of the current machine
|
||||
pub fn is_local_host(host: Host<&str>, port: u16, local_port: u16) -> std::io::Result<bool> {
|
||||
let local_set: HashSet<IpAddr> = LOCAL_IPS.iter().copied().collect();
|
||||
let is_local_host = match host {
|
||||
Host::Domain(domain) => {
|
||||
let ips = resolve_domain(domain)?.into_iter().collect::<Vec<_>>();
|
||||
|
||||
ips.iter().any(|ip| is_local_ip(&local_set, ip))
|
||||
}
|
||||
Host::Ipv4(ip) => is_local_ip(&local_set, &IpAddr::V4(ip)),
|
||||
Host::Ipv6(ip) => is_local_ip(&local_set, &IpAddr::V6(ip)),
|
||||
Host::Domain(domain) => resolve_domain(domain)?.iter().any(is_local_ip),
|
||||
Host::Ipv4(ip) => is_local_ip(&IpAddr::V4(ip)),
|
||||
Host::Ipv6(ip) => is_local_ip(&IpAddr::V6(ip)),
|
||||
};
|
||||
|
||||
if port > 0 {
|
||||
@@ -224,11 +219,8 @@ pub fn is_local_host(host: Host<&str>, port: u16, local_port: u16) -> std::io::R
|
||||
/// Whether `ip` belongs to this host: it is either configured on a local
|
||||
/// interface or, where the platform routes the full loopback space, a loopback
|
||||
/// address.
|
||||
fn is_local_ip(local_set: &HashSet<IpAddr>, ip: &IpAddr) -> bool {
|
||||
if local_set.contains(ip) {
|
||||
return true;
|
||||
}
|
||||
is_loopback_local(ip)
|
||||
pub fn is_local_ip(ip: &IpAddr) -> bool {
|
||||
LOCAL_IPS.contains(ip) || is_loopback_local(ip)
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
|
||||
@@ -178,7 +178,7 @@ requires a compatibility window and a dedicated cleanup entry.
|
||||
| `.scanner-cycle.lock` | scanner runtime lock | Serializes cycle-level work. A missing lock object is not itself usage evidence. |
|
||||
| `.scanner-pause-backlog.json` | scanner pause and catch-up ledger | Tracks dirty usage, discovered lifecycle work, and full-scan catch-up while authoritative publication is fenced by data movement. It never grants publication admission. |
|
||||
|
||||
The authoritative snapshot may include an optional `bucket_incarnation` in each bucket usage entry. The coordinator writes it only when every contributing set reports the same non-nil bucket UUID. Missing or conflicting identities leave that entry uncertified without affecting publication or quota admission. Veeam SOSAPI reports numeric `Used` only when this proof matches the current bucket incarnation. Missing usage, a readable legacy snapshot without proof, explicit pending entries, and proof for a previous bucket incarnation yield `Used=-1`. Contradictory snapshot certification metadata and malformed incarnation proofs return a retryable error. With a hard quota, `Available` is also undefined unless live free space is zero. Failures to read authoritative bucket metadata or usage, or obtain live storage capacity, yield a retryable capacity error. The proof is additive for older snapshot readers and identifies the bucket generation without making scanner usage a real-time quota ledger.
|
||||
The authoritative snapshot may include an optional `bucket_incarnation` in each bucket usage entry. The coordinator writes it only when every contributing set reports the same non-nil bucket UUID. Missing or conflicting identities leave that entry uncertified without affecting publication or quota admission. Veeam SOSAPI reports numeric `Used` only when this proof matches the current bucket incarnation. Missing usage or a snapshot without valid proof, including legacy and pending entries, yields `Used=-1`. With a hard quota, `Available` is also undefined unless live free space is zero. Failures to read authoritative bucket metadata or usage, or obtain live storage capacity, yield a retryable capacity error. The proof is additive for older snapshot readers and identifies the bucket generation without making scanner usage a real-time quota ledger.
|
||||
|
||||
SOSAPI retains the XML and its content-derived ETag when the reported figures match the previous sample. Once Last-Modified reaches nine minutes of age, a successful refresh renews the timestamp ahead of Veeam's ten-minute limit. Refresh failures still return an error.
|
||||
|
||||
|
||||
@@ -1295,9 +1295,10 @@ mod tests {
|
||||
bucket_policy(&store, &bucket, serde_json::json!({"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":"*","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":format!("arn:aws:s3:::{bucket}/*")}
|
||||
]})).await;
|
||||
let denied_object = "explicitly-denied";
|
||||
let denied = rustfs_policy::policy::Policy::parse_config(
|
||||
serde_json::to_string(&serde_json::json!({"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Action":["s3:PutObject","s3:DeleteObject"],"Resource":format!("arn:aws:s3:::{bucket}/*")}
|
||||
{"Effect":"Deny","Action":["s3:PutObject","s3:DeleteObject"],"Resource":format!("arn:aws:s3:::{bucket}/{denied_object}")}
|
||||
]}))
|
||||
.expect("identity denial JSON")
|
||||
.as_bytes(),
|
||||
@@ -1307,22 +1308,24 @@ mod tests {
|
||||
iam.policy_db_set(&cred.access_key, UserType::Reg, false, "permission-denial")
|
||||
.await
|
||||
.expect("attach denial");
|
||||
for (action, expected) in [
|
||||
("s3:GetObject", Decision::Allowed),
|
||||
("s3:PutObject", Decision::Denied),
|
||||
("s3:DeleteObject", Decision::Denied),
|
||||
for (action, object, expected) in [
|
||||
("s3:PutObject", "bucket-grant", Decision::Allowed),
|
||||
("s3:DeleteObject", "bucket-grant", Decision::Allowed),
|
||||
("s3:GetObject", denied_object, Decision::Allowed),
|
||||
("s3:PutObject", denied_object, Decision::Denied),
|
||||
("s3:DeleteObject", denied_object, Decision::Denied),
|
||||
] {
|
||||
let request = parse(serde_json::json!({"checks":[{"id":"x","action":action,"bucket":bucket,"object":"object"}]}));
|
||||
let request = parse(serde_json::json!({"checks":[{"id":"x","action":action,"bucket":bucket,"object":object}]}));
|
||||
let result = evaluate_check(
|
||||
&envelope,
|
||||
&cred,
|
||||
false,
|
||||
&request.checks[0],
|
||||
request.validate().expect("valid denial query")[0],
|
||||
request.validate().expect("valid permission query")[0],
|
||||
)
|
||||
.await
|
||||
.expect("non-owner query");
|
||||
assert_eq!(result.decision, expected, "real gate semantics for {action}");
|
||||
assert_eq!(result.decision, expected, "real gate semantics for {action} on {object}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+146
-43
@@ -450,31 +450,18 @@ fn is_delete_objects_not_found(error: &EcstoreError) -> bool {
|
||||
/// a 1000-key batch from serializing while capping the disk fanout pressure.
|
||||
const DELETE_OBJECTS_PRE_STAT_CONCURRENCY: usize = 16;
|
||||
|
||||
/// backlog#929 (HP-8): whether the pre-delete `get_object_info` for one entry
|
||||
/// of a DeleteObjects batch can be skipped without changing behavior.
|
||||
///
|
||||
/// The stat result feeds four consumers, and each must be provably idle:
|
||||
/// - the app-layer object-lock admission check never runs for deletes that
|
||||
/// create a delete marker, and non-lock buckets cannot hold retention or
|
||||
/// legal-hold metadata (`bucket_lock_enabled == false`);
|
||||
/// - replication reads its authoritative source metadata later while the
|
||||
/// SetDisks write lock is held, so it does not consume this advisory stat;
|
||||
/// - usage accounting for delete-marker creation goes through
|
||||
/// `record_bucket_delete_marker_memory` and never reads the object size
|
||||
/// (`accounting_creates_delete_marker` is computed from the same versioning
|
||||
/// snapshot the accounting branch uses);
|
||||
/// - transitioned-object (ILM tier) cleanup journaling is a no-op for
|
||||
/// delete-marker creation because no version is removed, so `ObjSweeper`
|
||||
/// produces no journal entry regardless of the stat result.
|
||||
///
|
||||
/// Object-lock enabled buckets always keep the stat, so their delete path is
|
||||
/// byte-for-byte the pre-#929 one (see PR #4297).
|
||||
/// Plain deletes get authoritative metadata for accounting, retention and tier
|
||||
/// cleanup under the storage write lock. An advisory read would take a second
|
||||
/// namespace lock per request entry, including duplicates of a busy key.
|
||||
fn can_skip_delete_objects_pre_stat(
|
||||
bucket_lock_enabled: bool,
|
||||
opts: &ObjectOptions,
|
||||
accounting_creates_delete_marker: bool,
|
||||
has_entry_condition: bool,
|
||||
) -> bool {
|
||||
!bucket_lock_enabled && delete_creates_delete_marker(opts) && accounting_creates_delete_marker
|
||||
!bucket_lock_enabled
|
||||
&& ((delete_creates_delete_marker(opts) && accounting_creates_delete_marker)
|
||||
|| (!opts.versioned && opts.version_id.is_none() && opts.http_preconditions.is_none() && !has_entry_condition))
|
||||
}
|
||||
|
||||
fn complete_delete_noop(
|
||||
@@ -869,7 +856,12 @@ impl DefaultObjectUsecase {
|
||||
// so evaluate it here with the same inputs to keep the stat-skip
|
||||
// decision and the accounting path provably consistent.
|
||||
let accounting_creates_delete_marker = object.version_id.is_none() && opts.versioned && !opts.version_suspended;
|
||||
let skip_stat = can_skip_delete_objects_pre_stat(bucket_lock_enabled, &opts, accounting_creates_delete_marker);
|
||||
let skip_stat = can_skip_delete_objects_pre_stat(
|
||||
bucket_lock_enabled,
|
||||
&opts,
|
||||
accounting_creates_delete_marker,
|
||||
object.delete_condition.is_some(),
|
||||
);
|
||||
|
||||
prepared_deletes.push(PreparedDelete {
|
||||
idx,
|
||||
@@ -2932,6 +2924,109 @@ mod tests {
|
||||
assert_eq!(err.message(), Some("Not init"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn execute_plain_unversioned_bulk_delete_reaches_storage_for_disabled_and_suspended_buckets() {
|
||||
use crate::app::storage_api::test::DeleteAfterObjectLockSnapshotBarrier;
|
||||
use crate::app::storage_api::test::contract::bucket::{BucketOperations as _, DeleteBucketOptions, MakeBucketOptions};
|
||||
|
||||
let store = crate::app::gating_test_env::shared_gating_ecstore().await;
|
||||
let ambient = crate::app::gating_test_env::shared_gating_ambient().await;
|
||||
let context = Arc::new(AppContext::new(Arc::clone(&store), ambient.iam(), ambient.kms()));
|
||||
for suspended in [false, true] {
|
||||
let bucket = format!("delete-objects-contended-{}", Uuid::new_v4());
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create authorized bucket");
|
||||
let mut reader = PutObjReader::from_vec(b"contended object".to_vec());
|
||||
store
|
||||
.put_object(&bucket, "object", &mut reader, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("put contended object");
|
||||
if suspended {
|
||||
store
|
||||
.update_bucket_metadata_config(
|
||||
&bucket,
|
||||
crate::app::storage_api::test::bucket::metadata::BUCKET_VERSIONING_CONFIG,
|
||||
b"<VersioningConfiguration><Status>Suspended</Status></VersioningConfiguration>".to_vec(),
|
||||
)
|
||||
.await
|
||||
.expect("suspend fixture versioning");
|
||||
}
|
||||
|
||||
let policy_json = format!(
|
||||
r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Principal":{{"AWS":"*"}},"Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::{bucket}/*"]}}]}}"#
|
||||
);
|
||||
let mut metadata = (*store
|
||||
.get_bucket_metadata(&bucket)
|
||||
.await
|
||||
.expect("authorized bucket metadata should be cached"))
|
||||
.clone();
|
||||
metadata.policy_config = Some(serde_json::from_str(&policy_json).expect("test policy should parse"));
|
||||
metadata.policy_config_json = policy_json.clone().into_bytes();
|
||||
crate::storage::storage_api::set_bucket_metadata(bucket.clone(), metadata)
|
||||
.await
|
||||
.expect("publish test bucket policy");
|
||||
|
||||
let writer = store
|
||||
.new_ns_lock(&bucket, "object")
|
||||
.await
|
||||
.expect("open object namespace lock")
|
||||
.get_write_lock(tokio::time::Duration::from_secs(5))
|
||||
.await
|
||||
.expect("hold a concurrent writer's lock");
|
||||
let admission = DeleteAfterObjectLockSnapshotBarrier::install(&bucket);
|
||||
let usecase = DefaultObjectUsecase::with_context(Some(Arc::clone(&context)));
|
||||
let input = DeleteBatchInput {
|
||||
bucket: bucket.clone(),
|
||||
objects: (0..16)
|
||||
.map(|_| DeleteBatchEntry {
|
||||
key: "object".to_owned(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
quiet: None,
|
||||
};
|
||||
let mut req = method_only_delete_envelope(Method::POST);
|
||||
req.install_req_info(crate::storage::req_info::ReqInfo::default());
|
||||
let delete = tokio::spawn(async move { usecase.execute_delete_objects(req, input).await });
|
||||
|
||||
tokio::time::timeout(tokio::time::Duration::from_secs(5), admission.wait_until_paused())
|
||||
.await
|
||||
.expect("a plain batch must reach storage admission without acquiring an advisory read lock");
|
||||
drop(writer);
|
||||
admission.release();
|
||||
let response = tokio::time::timeout(tokio::time::Duration::from_secs(10), delete)
|
||||
.await
|
||||
.expect("delete finishes once the writer releases the key")
|
||||
.expect("delete task joins")
|
||||
.expect("delete returns per-entry results");
|
||||
let deleted = response.deleted.expect("non-quiet delete");
|
||||
assert_eq!(deleted.len(), 16);
|
||||
assert!(
|
||||
deleted
|
||||
.iter()
|
||||
.all(|entry| entry.delete_marker.unwrap_or_default() == suspended)
|
||||
);
|
||||
assert!(response.errors.is_none_or(|errors| errors.is_empty()));
|
||||
let read = store
|
||||
.get_object_reader(&bucket, "object", None, HeaderMap::new(), &ObjectOptions::default())
|
||||
.await;
|
||||
assert!(matches!(read, Err(ref error) if is_err_object_not_found(error) || is_err_version_not_found(error)));
|
||||
store
|
||||
.delete_bucket(
|
||||
&bucket,
|
||||
&DeleteBucketOptions {
|
||||
force: suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("remove verification bucket");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn execute_delete_objects_rejects_bucket_recreated_before_publication_admission() {
|
||||
@@ -3896,9 +3991,6 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
// backlog#929 (HP-8): the pre-delete stat may only be skipped when every
|
||||
// consumer of its result is provably idle. Each guard flips one condition
|
||||
// to prove the skip is fenced on all four data dependencies.
|
||||
fn delete_marker_creating_opts() -> ObjectOptions {
|
||||
ObjectOptions {
|
||||
version_id: None,
|
||||
@@ -3910,12 +4002,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn delete_objects_pre_stat_skippable_for_delete_marker_on_plain_bucket() {
|
||||
assert!(can_skip_delete_objects_pre_stat(false, &delete_marker_creating_opts(), true));
|
||||
assert!(can_skip_delete_objects_pre_stat(false, &delete_marker_creating_opts(), true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_objects_pre_stat_kept_for_object_lock_buckets() {
|
||||
assert!(!can_skip_delete_objects_pre_stat(true, &delete_marker_creating_opts(), true));
|
||||
assert!(!can_skip_delete_objects_pre_stat(true, &delete_marker_creating_opts(), true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3926,39 +4018,50 @@ mod tests {
|
||||
version_suspended: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &opts, true));
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &opts, true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_objects_pre_stat_kept_for_unversioned_buckets() {
|
||||
// Unversioned deletes remove the current object: usage accounting needs
|
||||
// the object size and ILM tier cleanup needs the transition metadata.
|
||||
let opts = ObjectOptions {
|
||||
version_id: None,
|
||||
versioned: false,
|
||||
version_suspended: false,
|
||||
fn delete_objects_pre_stat_skips_plain_unversioned_entries() {
|
||||
let opts = ObjectOptions::default();
|
||||
assert!(can_skip_delete_objects_pre_stat(false, &opts, false, false));
|
||||
assert!(!can_skip_delete_objects_pre_stat(true, &opts, false, false));
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &opts, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_objects_pre_stat_keeps_unversioned_http_conditions_and_version_ids() {
|
||||
let header_condition = ObjectOptions {
|
||||
http_preconditions: Some(Default::default()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &opts, false));
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &header_condition, false, false));
|
||||
|
||||
for synthetic_version_id in [false, true] {
|
||||
let version_address = ObjectOptions {
|
||||
version_id: Some(Uuid::nil().to_string()),
|
||||
synthetic_version_id,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &version_address, false, false));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_objects_pre_stat_kept_for_suspended_versioning() {
|
||||
fn delete_objects_pre_stat_skips_plain_suspended_entries() {
|
||||
let opts = ObjectOptions {
|
||||
version_id: None,
|
||||
versioned: true,
|
||||
version_suspended: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &opts, false));
|
||||
assert!(can_skip_delete_objects_pre_stat(false, &opts, false, false));
|
||||
assert!(!can_skip_delete_objects_pre_stat(true, &opts, false, false));
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &opts, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_objects_pre_stat_kept_when_accounting_snapshot_disagrees() {
|
||||
// If the accounting-side versioning snapshot does not also classify the
|
||||
// delete as a delete-marker creation, the stat must stay so usage
|
||||
// accounting keeps its size input.
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &delete_marker_creating_opts(), false));
|
||||
// Keep the existing marker-specific skip tied to the accounting decision.
|
||||
assert!(!can_skip_delete_objects_pre_stat(false, &delete_marker_creating_opts(), false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -32,9 +32,7 @@ use rustfs_s3_types::{S3Error, S3ErrorCode, S3Result};
|
||||
use time::OffsetDateTime;
|
||||
use tracing::debug;
|
||||
|
||||
use super::super::storage_api::object_usecase::data_usage::{
|
||||
BucketUsagePendingReason, BucketUsageStatus, load_bucket_usage_certification_from_backend_cached,
|
||||
};
|
||||
use super::super::storage_api::object_usecase::data_usage::load_bucket_usage_from_backend_cached;
|
||||
use super::super::storage_api::object_usecase::{ECStore, StorageObjectInfo as ObjectInfo, check_preconditions};
|
||||
use super::HTTPRangeSpec;
|
||||
use super::shared::{LOG_COMPONENT_APP, LOG_SUBSYSTEM_OBJECT};
|
||||
@@ -390,17 +388,12 @@ fn capacity_unavailable() -> S3Error {
|
||||
}
|
||||
|
||||
async fn load_capacity_inputs(store: &Arc<ECStore>, bucket: &str, incarnation: Uuid) -> S3Result<CapacityInputs> {
|
||||
let used_bucket = match load_bucket_usage_certification_from_backend_cached(Arc::clone(store), bucket, incarnation)
|
||||
let used_bucket = load_bucket_usage_from_backend_cached(Arc::clone(store), bucket, incarnation)
|
||||
.await
|
||||
.map_err(|_| capacity_unavailable())?
|
||||
{
|
||||
BucketUsageStatus::Certified(bytes) => Some(bytes),
|
||||
BucketUsageStatus::Pending(reason) => {
|
||||
log_usage_missing_once(bucket, reason);
|
||||
None
|
||||
}
|
||||
BucketUsageStatus::Unavailable(_) => return Err(capacity_unavailable()),
|
||||
};
|
||||
.map_err(|_| capacity_unavailable())?;
|
||||
if used_bucket.is_none() {
|
||||
log_usage_missing_once(bucket);
|
||||
}
|
||||
let (capacity_cluster, free_cluster) = cached_cluster_capacity(store).await?;
|
||||
// The authoritative quota read also fences publication of the sampled capacity to this incarnation.
|
||||
let (quota, quota_incarnation, _) = store.bucket_quota_and_incarnation_from_disk(bucket).await.map_err(|_| {
|
||||
@@ -540,7 +533,7 @@ fn conservative_cluster_capacity(info: &rustfs_madmin::StorageInfo) -> Option<(u
|
||||
Some((total, free))
|
||||
}
|
||||
|
||||
fn log_usage_missing_once(bucket: &str, reason: BucketUsagePendingReason) {
|
||||
fn log_usage_missing_once(bucket: &str) {
|
||||
if LOGGED_USAGE_MISSING
|
||||
.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
@@ -550,7 +543,6 @@ fn log_usage_missing_once(bucket: &str, reason: BucketUsagePendingReason) {
|
||||
component = LOG_COMPONENT_APP,
|
||||
subsystem = LOG_SUBSYSTEM_OBJECT,
|
||||
state = "snapshot_missing",
|
||||
reason = ?reason,
|
||||
bucket = %bucket,
|
||||
"Veeam SOSAPI is reporting undefined bucket usage"
|
||||
);
|
||||
|
||||
@@ -1018,23 +1018,15 @@ fn veeam_sosapi_http_contract() {
|
||||
assert_eq!(stale.status(), http::StatusCode::OK);
|
||||
let stale_body = BodyExt::collect(stale.into_body()).await.expect("stale capacity body").to_bytes();
|
||||
assert_eq!(element_text(std::str::from_utf8(&stale_body).unwrap(), "Used"), "-1");
|
||||
let recycled_key = CapacityCacheKey { store_id: store.id, bucket: recycled.clone(), incarnation: new_id };
|
||||
snapshot.last_update = Some(std::time::SystemTime::now() + Duration::from_secs(5));
|
||||
snapshot.buckets_usage.get_mut(&recycled).expect("recycled bucket").bucket_incarnation = Some("invalid UUID".into());
|
||||
crate::app::storage_api::test::data_usage::store_data_usage_in_backend(snapshot.clone(), Arc::clone(&store))
|
||||
.await.expect("seed malformed incarnation proof");
|
||||
caches.current.invalidate(&recycled_key).await;
|
||||
for method in [Method::GET, Method::HEAD] {
|
||||
let malformed = owner.call(owner_call(method, recycled_uri.clone(), Vec::new(), Bytes::new()))
|
||||
.await.expect("malformed capacity");
|
||||
assert_eq!(malformed.status(), http::StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
snapshot.last_update = Some(std::time::SystemTime::now() + Duration::from_secs(6));
|
||||
snapshot.buckets_usage.get_mut(&recycled).unwrap().bucket_incarnation = Some(new_id.to_string());
|
||||
snapshot.buckets_usage.get_mut(&recycled).unwrap().size = 17;
|
||||
snapshot.bucket_sizes.insert(recycled.clone(), 17);
|
||||
crate::app::storage_api::test::data_usage::store_data_usage_in_backend(snapshot, Arc::clone(&store))
|
||||
.await.expect("seed new incarnation snapshot");
|
||||
capacity_caches().current.invalidate(&CapacityCacheKey {
|
||||
store_id: store.id, bucket: recycled.clone(), incarnation: new_id,
|
||||
}).await;
|
||||
let fresh = owner.call(owner_call(Method::GET, recycled_uri, Vec::new(), Bytes::new())).await.expect("new capacity");
|
||||
assert_eq!(fresh.status(), http::StatusCode::OK);
|
||||
let fresh_body = BodyExt::collect(fresh.into_body()).await.expect("new capacity body").to_bytes();
|
||||
|
||||
@@ -14,8 +14,8 @@
|
||||
|
||||
//! GetObjectLegalHold: the legal hold status an object's metadata stores.
|
||||
//!
|
||||
//! Responsible for: reading the stored status, `OFF` when none is stored, on a bucket with Object
|
||||
//! Lock enabled. A stored status outside the model's set is answered as stored.
|
||||
//! Responsible for: reading the stored status on a bucket with Object Lock enabled. Missing hold
|
||||
//! metadata produces `NoSuchObjectLockConfiguration`. Other statuses are answered as stored.
|
||||
//! Also writes lock metadata to the requested version and schedules metadata replication.
|
||||
//! NOT responsible for: authorization.
|
||||
//! Upstream: both edges. Downstream: the object store and the bucket's Object Lock configuration.
|
||||
@@ -154,9 +154,10 @@ impl ObjectMetaUsecase {
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `MethodNotAllowed` for a Veeam SOSAPI system object; `InternalError` before the store is up
|
||||
/// or when the object cannot be read; `NoSuchBucket`; the Object Lock refusal of a bucket
|
||||
/// without Object Lock.
|
||||
/// `MethodNotAllowed` for a Veeam SOSAPI system object or an explicitly selected delete marker.
|
||||
/// `NoSuchBucket`, `NoSuchKey`, or `NoSuchVersion` for a missing resource.
|
||||
/// `InvalidRequest` if Object Lock is disabled and `NoSuchObjectLockConfiguration` if no hold
|
||||
/// status is stored for the object version. Storage failures can return `InternalError`.
|
||||
pub async fn execute_get_object_legal_hold(
|
||||
&self,
|
||||
envelope: RequestEnvelope,
|
||||
@@ -180,18 +181,17 @@ impl ObjectMetaUsecase {
|
||||
)
|
||||
.suppress_event();
|
||||
let store = self.store_outside_veeam_sosapi(bucket, key).await?;
|
||||
store
|
||||
.get_bucket_info(bucket, &BucketOptions::default())
|
||||
.await
|
||||
.map_err(ApiError::from)?;
|
||||
let object_info = locked_object_info(&store, &envelope, bucket, key, version_id.clone()).await?;
|
||||
|
||||
let status = object_info
|
||||
.user_defined
|
||||
.get(AMZ_OBJECT_LOCK_LEGAL_HOLD_LOWER)
|
||||
.map_or(Status::OFF, |status| Status::custom(status.clone()));
|
||||
.filter(|status| !status.is_empty())
|
||||
.ok_or_else(|| S3Error::new(S3ErrorCode::NoSuchObjectLockConfiguration))?;
|
||||
let output = GetObjectLegalHoldOutput {
|
||||
legal_hold: Some(ObjectLockLegalHold { status: Some(status) }),
|
||||
legal_hold: Some(ObjectLockLegalHold {
|
||||
status: Some(Status::custom(status.clone())),
|
||||
}),
|
||||
};
|
||||
|
||||
let version_id = version_id.unwrap_or_else(|| Uuid::new_v4().to_string());
|
||||
|
||||
@@ -32,8 +32,8 @@ use crate::app::RequestEnvelope;
|
||||
use crate::app::object::shared::reject_veeam_sosapi_mutation;
|
||||
use crate::app::runtime_sources::{AppContext, current_object_store_handle_for_context};
|
||||
use crate::app::storage_api::object_meta_usecase::contract::ObjectOperations as _;
|
||||
use crate::app::storage_api::object_meta_usecase::validate_bucket_object_lock_enabled;
|
||||
use crate::app::storage_api::object_usecase::error::is_err_version_not_found;
|
||||
use crate::app::storage_api::object_meta_usecase::validate_bucket_object_lock_enabled_for_read;
|
||||
use crate::app::storage_api::object_usecase::error::{StorageError, is_err_object_not_found, is_err_version_not_found};
|
||||
use crate::app::storage_api::object_usecase::options::get_opts;
|
||||
use crate::app::storage_api::object_usecase::{ECStore, StorageObjectInfo as ObjectInfo};
|
||||
use crate::error::ApiError;
|
||||
@@ -72,26 +72,44 @@ async fn locked_object_info(
|
||||
key: &str,
|
||||
version_id: Option<String>,
|
||||
) -> S3Result<ObjectInfo> {
|
||||
validate_bucket_object_lock_enabled(bucket).await?;
|
||||
validate_bucket_object_lock_enabled_for_read(bucket).await?;
|
||||
let explicit_version = version_id.is_some();
|
||||
let opts = get_opts(bucket, key, version_id, None, envelope.headers())
|
||||
.await
|
||||
.map_err(ApiError::from)?;
|
||||
store.get_object_info(bucket, key, &opts).await.map_err(|error| {
|
||||
if explicit_version && is_err_version_not_found(&error) {
|
||||
return ApiError::from(error).into();
|
||||
let code = match store.get_object_info(bucket, key, &opts).await {
|
||||
Ok(info) if !info.delete_marker => return Ok(info),
|
||||
// A single pool can return the marker snapshot, while multi-pool lookup can reject it.
|
||||
Ok(_) | Err(StorageError::MethodNotAllowed) => {
|
||||
if explicit_version {
|
||||
S3ErrorCode::MethodNotAllowed
|
||||
} else {
|
||||
S3ErrorCode::NoSuchKey
|
||||
}
|
||||
}
|
||||
error!(
|
||||
component = "storage",
|
||||
subsystem = "object",
|
||||
event = "object_info_load_failed",
|
||||
bucket = %bucket,
|
||||
object = %key,
|
||||
error = %error,
|
||||
"Failed to load object info"
|
||||
);
|
||||
s3_error!(InternalError, "{}", error.to_string())
|
||||
})
|
||||
Err(error) if is_err_object_not_found(&error) || is_err_version_not_found(&error) => {
|
||||
if explicit_version {
|
||||
S3ErrorCode::NoSuchVersion
|
||||
} else {
|
||||
S3ErrorCode::NoSuchKey
|
||||
}
|
||||
}
|
||||
Err(StorageError::BucketNotFound(_) | StorageError::VolumeNotFound) => S3ErrorCode::NoSuchBucket,
|
||||
Err(error) => {
|
||||
error!(
|
||||
component = "storage",
|
||||
subsystem = "object",
|
||||
event = "object_info_load_failed",
|
||||
bucket = %bucket,
|
||||
object = %key,
|
||||
error = %error,
|
||||
"Failed to load object info"
|
||||
);
|
||||
return Err(s3_error!(InternalError, "{}", error.to_string()));
|
||||
}
|
||||
};
|
||||
let message = ApiError::error_code_to_message(&code);
|
||||
Err(S3Error::with_message(code, message))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -181,9 +181,11 @@ impl ObjectMetaUsecase {
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// `MethodNotAllowed` for a Veeam SOSAPI system object; `InternalError` before the store is up,
|
||||
/// when the object cannot be read, or for a stored date outside the answerable range; the
|
||||
/// Object Lock refusal of a bucket without Object Lock.
|
||||
/// `MethodNotAllowed` for a Veeam SOSAPI system object or an explicitly selected delete marker.
|
||||
/// `NoSuchBucket`, `NoSuchKey`, or `NoSuchVersion` for an absent resource.
|
||||
/// `InvalidRequest` if Object Lock is disabled and `NoSuchObjectLockConfiguration` if no
|
||||
/// retention is stored for the object version. Storage failures and out-of-range dates can
|
||||
/// return `InternalError`.
|
||||
pub async fn execute_get_object_retention(
|
||||
&self,
|
||||
envelope: RequestEnvelope,
|
||||
@@ -220,14 +222,22 @@ impl ObjectMetaUsecase {
|
||||
}
|
||||
}
|
||||
|
||||
/// The retention `metadata` stores. An unparseable date is answered as absent, as before.
|
||||
/// Decode stored retention, preserving a legacy mode even if its date cannot be parsed.
|
||||
fn stored_retention(metadata: &HashMap<String, String>) -> S3Result<ObjectLockRetention> {
|
||||
let mode = metadata
|
||||
.get(AMZ_OBJECT_LOCK_MODE_LOWER)
|
||||
.map(|mode| Mode::custom(mode.clone()));
|
||||
let retain_until_date = metadata
|
||||
let mode = metadata.get(AMZ_OBJECT_LOCK_MODE_LOWER).filter(|mode| !mode.is_empty());
|
||||
let retain_until = metadata
|
||||
.get(AMZ_OBJECT_LOCK_RETAIN_UNTIL_DATE_LOWER)
|
||||
.and_then(|value| OffsetDateTime::parse(value, &Rfc3339).ok())
|
||||
.filter(|date| !date.is_empty());
|
||||
// PutObjectRetention clears both fields by storing empty strings.
|
||||
if mode.is_none() && retain_until.is_none() {
|
||||
return Err(S3Error::new(S3ErrorCode::NoSuchObjectLockConfiguration));
|
||||
}
|
||||
let parsed_date = match retain_until.map(|value| OffsetDateTime::parse(value, &Rfc3339)).transpose() {
|
||||
Ok(date) => date,
|
||||
Err(_) if mode.is_some() => None,
|
||||
Err(_) => return Err(S3Error::with_message(S3ErrorCode::InternalError, "Stored retention date is invalid")),
|
||||
};
|
||||
let retain_until_date = parsed_date
|
||||
.map(|date| {
|
||||
date.checked_to_offset(time::UtcOffset::UTC)
|
||||
.filter(|date| (0..=9999).contains(&date.year()))
|
||||
@@ -241,7 +251,7 @@ fn stored_retention(metadata: &HashMap<String, String>) -> S3Result<ObjectLockRe
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(ObjectLockRetention {
|
||||
mode,
|
||||
mode: mode.map(|mode| Mode::custom(mode.clone())),
|
||||
retain_until_date,
|
||||
..Default::default()
|
||||
})
|
||||
|
||||
@@ -89,19 +89,12 @@ pub(crate) mod data_usage {
|
||||
crate::storage::storage_api::ecstore_data_usage::load_admin_data_usage_with_memory_overlay(store).await
|
||||
}
|
||||
|
||||
pub(crate) use crate::storage::storage_api::ecstore_data_usage::{BucketUsagePendingReason, BucketUsageStatus};
|
||||
|
||||
pub(crate) async fn load_bucket_usage_certification_from_backend_cached(
|
||||
pub(crate) async fn load_bucket_usage_from_backend_cached(
|
||||
store: Arc<crate::storage::storage_api::ECStore>,
|
||||
bucket: &str,
|
||||
incarnation: uuid::Uuid,
|
||||
) -> Result<BucketUsageStatus, crate::storage::storage_api::StorageError> {
|
||||
crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_certification_from_backend_cached(
|
||||
store,
|
||||
bucket,
|
||||
incarnation,
|
||||
)
|
||||
.await
|
||||
) -> Result<Option<u64>, crate::storage::storage_api::StorageError> {
|
||||
crate::storage::storage_api::ecstore_data_usage::load_bucket_usage_from_backend_cached(store, bucket, incarnation).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1735,7 +1728,8 @@ pub(crate) mod object_meta_usecase {
|
||||
pub(crate) use crate::storage::storage_api::check_retention_for_modification;
|
||||
|
||||
pub(crate) use crate::storage::storage_api::ecfs_consumer::object_lock::{
|
||||
load_bucket_object_lock_config_state, validate_bucket_object_lock_enabled, validate_bucket_object_lock_enabled_state,
|
||||
load_bucket_object_lock_config_state, validate_bucket_object_lock_enabled, validate_bucket_object_lock_enabled_for_read,
|
||||
validate_bucket_object_lock_enabled_state,
|
||||
};
|
||||
pub(crate) use crate::storage::storage_api::ecstore_bucket::metadata::validate_tag_set_entries;
|
||||
pub(crate) use crate::storage::storage_api::ecstore_bucket::tagging::{
|
||||
@@ -1878,7 +1872,9 @@ pub(crate) mod test {
|
||||
}
|
||||
pub(crate) use crate::storage::storage_api::bootstrap_instance_ctx;
|
||||
pub(crate) use crate::storage::storage_api::ecstore_bucket::install_all_v6_fleet_capability_proof;
|
||||
pub(crate) use crate::storage::storage_api::test_consumer::{get_global_bucket_metadata_sys, set_bucket_metadata};
|
||||
pub(crate) use crate::storage::storage_api::test_consumer::{
|
||||
DeleteAfterObjectLockSnapshotBarrier, get_global_bucket_metadata_sys, set_bucket_metadata,
|
||||
};
|
||||
pub(crate) use crate::storage::storage_api::{
|
||||
ECStore, Endpoint, Endpoints, PoolEndpoints, StorageObjectInfo, StorageObjectOptions, StoragePutObjReader,
|
||||
};
|
||||
|
||||
@@ -25,7 +25,9 @@ use crate::{
|
||||
startup_preflight::{StartupServerPreflightError, bootstrap_external_prefix_compat, init_startup_server_preflight},
|
||||
startup_server::{StartupHttpServers, StartupListenContext, init_startup_http_servers, init_startup_listen_context},
|
||||
startup_services::init_startup_runtime_services,
|
||||
startup_storage::{StartupStorageRuntime, init_startup_storage_foundation, init_startup_storage_runtime},
|
||||
startup_storage::{
|
||||
StartupEndpointDiscoveryTimeout, StartupStorageRuntime, init_startup_storage_foundation, init_startup_storage_runtime,
|
||||
},
|
||||
storage_api::server::http::ServerContextSlot,
|
||||
storage_api::startup::storage::bootstrap_instance_ctx,
|
||||
};
|
||||
@@ -129,12 +131,27 @@ fn run_process_on_current_thread(#[cfg(feature = "internode-transport")] build:
|
||||
} else {
|
||||
ExitCode::SUCCESS
|
||||
};
|
||||
drop(result);
|
||||
// block_on has left its entered scope; the startup thread owns teardown.
|
||||
drop(runtime);
|
||||
shutdown_process_runtime(runtime, result);
|
||||
exit_code
|
||||
}
|
||||
|
||||
fn shutdown_process_runtime(runtime: tokio::runtime::Runtime, result: Result<()>) {
|
||||
let endpoint_discovery_timed_out = result
|
||||
.as_ref()
|
||||
.err()
|
||||
.and_then(Error::get_ref)
|
||||
.is_some_and(|source| source.is::<StartupEndpointDiscoveryTimeout>());
|
||||
drop(result);
|
||||
|
||||
// The topology timed out before publishing disks or opening listeners. A
|
||||
// system DNS call may still be running on the blocking pool after cancellation.
|
||||
if endpoint_discovery_timed_out {
|
||||
runtime.shutdown_background();
|
||||
} else {
|
||||
drop(runtime);
|
||||
}
|
||||
}
|
||||
|
||||
fn format_fatal_stderr_message(context: &str, error: impl std::fmt::Display) -> String {
|
||||
format!("[FATAL] {context}: {error}")
|
||||
}
|
||||
@@ -2186,6 +2203,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_discovery_timeout_does_not_wait_for_a_blocking_resolver() {
|
||||
std::thread::scope(|scope| {
|
||||
let (started, wait_for_start) = std::sync::mpsc::channel();
|
||||
let (release, wait_for_release) = std::sync::mpsc::channel::<()>();
|
||||
let (stopped, wait_for_stop) = std::sync::mpsc::channel();
|
||||
let (completed, wait_for_completion) = std::sync::mpsc::channel();
|
||||
scope.spawn(move || {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("create owned startup runtime");
|
||||
runtime.spawn_blocking(move || {
|
||||
started.send(()).expect("report resolver start");
|
||||
let _ = wait_for_release.recv();
|
||||
completed.send(()).expect("report resolver completion");
|
||||
});
|
||||
wait_for_start.recv_timeout(Duration::from_secs(5)).expect("resolver started");
|
||||
let err = Error::new(std::io::ErrorKind::TimedOut, "startup DNS deadline elapsed");
|
||||
shutdown_process_runtime(runtime, Err(Error::other(StartupEndpointDiscoveryTimeout(err))));
|
||||
let _ = stopped.send(());
|
||||
});
|
||||
|
||||
let before_release = wait_for_stop.recv_timeout(Duration::from_secs(5));
|
||||
drop(release);
|
||||
wait_for_completion
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("resolver completed");
|
||||
before_release.expect("startup shutdown must return while the resolver is still blocked");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_thread_propagates_panics() {
|
||||
let result = std::panic::catch_unwind(|| run_on_startup_thread(|| panic!("startup thread panic")));
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -59,6 +60,25 @@ fn configure_metric_gates(metrics_enabled: bool) {
|
||||
startup_runtime_sources::set_metrics_enabled(metrics_enabled);
|
||||
}
|
||||
|
||||
fn format_stage_local_summary(rows: &[rustfs_io_metrics::GetStageLocalSummaryWithMax]) -> (String, String) {
|
||||
let mut summary = String::new();
|
||||
let mut max_ns = String::new();
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
if index != 0 {
|
||||
summary.push(';');
|
||||
max_ns.push(';');
|
||||
}
|
||||
let stage = &row.summary;
|
||||
let _ = write!(
|
||||
summary,
|
||||
"{}|{}|{}|{}|{}|{}",
|
||||
stage.path, stage.stage, stage.object_class, stage.size_bucket, stage.sampled_count, stage.duration_nanoseconds,
|
||||
);
|
||||
let _ = write!(max_ns, "{}", row.max_duration_nanoseconds);
|
||||
}
|
||||
(summary, max_ns)
|
||||
}
|
||||
|
||||
fn init_get_stage_local_summary_runtime(ctx: CancellationToken) {
|
||||
let interval_secs =
|
||||
rustfs_utils::get_env_u64(rustfs_config::observability::ENV_OBS_GET_STAGE_LOCAL_SUMMARY_INTERVAL_SECS, 15).max(1);
|
||||
@@ -71,20 +91,19 @@ fn init_get_stage_local_summary_runtime(ctx: CancellationToken) {
|
||||
tokio::select! {
|
||||
_ = ctx.cancelled() => break,
|
||||
_ = interval.tick() => {
|
||||
let rows = rustfs_io_metrics::take_get_stage_local_summary();
|
||||
let rows = rustfs_io_metrics::take_get_stage_local_summary_with_max();
|
||||
let rename = rustfs_io_metrics::snapshot_ecstore_rename_diagnostics();
|
||||
if rows.is_empty() && rename.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let summary = rows.iter().map(|row| {
|
||||
format!("{}|{}|{}|{}|{}|{}", row.path, row.stage, row.object_class, row.size_bucket, row.sampled_count, row.duration_nanoseconds)
|
||||
}).collect::<Vec<_>>().join(";");
|
||||
// Each maximum uses the same row index as the existing stages field.
|
||||
let (summary, max_ns) = format_stage_local_summary(&rows);
|
||||
let timestamp_ms = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis();
|
||||
let line = format!(
|
||||
"timestamp_ms={timestamp_ms}\tsample_rate={}\tstage_count={}\tstages={summary}\trename_diag_version=4\trename_rpc={}\trename_remote_width={}\trename_batchable_width={}\trename_coverage={}\trename_batch_execution={}\trename_admission={}\trename_quarantine={}\trename_batch_timing_count={}\trename_batch_timing_total_ns={}\trename_batch_timing_max_ns={}\n",
|
||||
"timestamp_ms={timestamp_ms}\tsample_rate={}\tstage_count={}\tstages={summary}\trename_diag_version=4\trename_rpc={}\trename_remote_width={}\trename_batchable_width={}\trename_coverage={}\trename_batch_execution={}\trename_admission={}\trename_quarantine={}\trename_batch_timing_count={}\trename_batch_timing_total_ns={}\trename_batch_timing_max_ns={}\tstage_max_ns={max_ns}\n",
|
||||
rustfs_io_metrics::get_stage_local_summary_sample_rate(),
|
||||
rows.len(),
|
||||
rustfs_io_metrics::ECSTORE_RENAME_RPC_KINDS.iter().zip(rename.rpc_counts).map(|(label, count)| format!("{label}:{count}")).collect::<Vec<_>>().join(","),
|
||||
@@ -141,6 +160,7 @@ mod tests {
|
||||
|
||||
rustfs_io_metrics::record_get_object_stage_duration("legacy_duplex", "metadata", 0.001);
|
||||
rustfs_io_metrics::record_get_object_stage_duration("legacy_duplex", "metadata", 0.003);
|
||||
rustfs_io_metrics::record_get_object_stage_duration("legacy_duplex", "metadata", 0.002);
|
||||
rustfs_io_metrics::record_get_object_stage_duration_by_size(
|
||||
"legacy_duplex",
|
||||
"inline_direct.decode",
|
||||
@@ -149,14 +169,29 @@ mod tests {
|
||||
0.002,
|
||||
);
|
||||
|
||||
let rows = rustfs_io_metrics::take_get_stage_local_summary();
|
||||
let rows = rustfs_io_metrics::take_get_stage_local_summary_with_max();
|
||||
let metadata = rows
|
||||
.iter()
|
||||
.find(|row| row.path == "legacy_duplex" && row.stage == "metadata")
|
||||
.find(|row| row.summary.path == "legacy_duplex" && row.summary.stage == "metadata")
|
||||
.expect("local summary should retain sampled metadata observations");
|
||||
assert_eq!(metadata.sampled_count, 2);
|
||||
assert_eq!(metadata.duration_nanoseconds, 4_000_000);
|
||||
assert!(rows.iter().any(|row| row.size_bucket == "le_4kib"));
|
||||
assert_eq!(metadata.summary.sampled_count, 3);
|
||||
assert_eq!(metadata.summary.duration_nanoseconds, 6_000_000);
|
||||
assert_eq!(metadata.max_duration_nanoseconds, 3_000_000);
|
||||
assert_eq!(
|
||||
format_stage_local_summary(&rows),
|
||||
(
|
||||
"legacy_duplex|inline_direct.decode|plain_single_part|le_4kib|1|2000000;legacy_duplex|metadata|||3|6000000"
|
||||
.into(),
|
||||
"2000000;3000000".into(),
|
||||
)
|
||||
);
|
||||
|
||||
rustfs_io_metrics::record_get_object_stage_duration("legacy_duplex", "metadata", 0.001);
|
||||
let rows = rustfs_io_metrics::take_get_stage_local_summary_with_max();
|
||||
assert_eq!(
|
||||
format_stage_local_summary(&rows),
|
||||
("legacy_duplex|metadata|||1|1000000".into(), "1000000".into())
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::storage_api::startup::storage::{
|
||||
};
|
||||
use rustfs_common::{GlobalReadiness, SystemStage};
|
||||
use std::{
|
||||
io::{Error, Result},
|
||||
io::{Error, ErrorKind, Result},
|
||||
net::SocketAddr,
|
||||
sync::Arc,
|
||||
};
|
||||
@@ -44,6 +44,10 @@ pub(crate) struct StartupStorageRuntime {
|
||||
pub(crate) shutdown_token: CancellationToken,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error(transparent)]
|
||||
pub(crate) struct StartupEndpointDiscoveryTimeout(pub(crate) Error);
|
||||
|
||||
pub(crate) async fn init_startup_storage_foundation(
|
||||
server_address: &str,
|
||||
volumes: &[String],
|
||||
@@ -72,7 +76,13 @@ pub(crate) async fn init_startup_storage_foundation(
|
||||
"Endpoint parsing failed"
|
||||
);
|
||||
})
|
||||
.map_err(Error::other)?;
|
||||
.map_err(|err| {
|
||||
if err.kind() == ErrorKind::TimedOut {
|
||||
Error::new(ErrorKind::TimedOut, StartupEndpointDiscoveryTimeout(err))
|
||||
} else {
|
||||
Error::other(err)
|
||||
}
|
||||
})?;
|
||||
ECStore::validate_startup_storage_class(&endpoint_pools)
|
||||
.inspect_err(|err| {
|
||||
error!(
|
||||
|
||||
@@ -546,6 +546,16 @@ pub(crate) async fn validate_bucket_object_lock_enabled(bucket: &str) -> S3Resul
|
||||
validate_bucket_object_lock_enabled_state(bucket, &state)
|
||||
}
|
||||
|
||||
pub(crate) async fn validate_bucket_object_lock_enabled_for_read(bucket: &str) -> S3Result<()> {
|
||||
// Metadata authority already distinguishes a missing bucket from a missing
|
||||
// lock configuration. Warm reads need no separate namespace quorum probe.
|
||||
let Some(result) = metadata_sys::find_object_lock_config_state(bucket).await.transpose() else {
|
||||
return Err(ApiError::from(StorageError::BucketNotFound(bucket.to_owned())).into());
|
||||
};
|
||||
let state = map_bucket_object_lock_config_state(bucket, result)?;
|
||||
validate_bucket_object_lock_enabled_state(bucket, &state)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_bucket_object_lock_enabled_state(bucket: &str, state: &ObjectLockConfigState) -> S3Result<()> {
|
||||
match state {
|
||||
ObjectLockConfigState::Configured { config, .. } if config.object_lock_enabled.as_deref() == Some("Enabled") => Ok(()),
|
||||
|
||||
@@ -245,7 +245,8 @@ pub(crate) mod ecfs_consumer {
|
||||
|
||||
pub(crate) mod object_lock {
|
||||
pub(crate) use super::super::super::{
|
||||
load_bucket_object_lock_config_state, validate_bucket_object_lock_enabled, validate_bucket_object_lock_enabled_state,
|
||||
load_bucket_object_lock_config_state, validate_bucket_object_lock_enabled,
|
||||
validate_bucket_object_lock_enabled_for_read, validate_bucket_object_lock_enabled_state,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -485,6 +486,7 @@ pub(crate) mod tonic_service_consumer {
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_consumer {
|
||||
pub(crate) use super::super::access_owned::object_read::authorize_head_object;
|
||||
pub(crate) use rustfs_ecstore::api::object::test_util::DeleteAfterObjectLockSnapshotBarrier;
|
||||
pub(crate) mod sse {
|
||||
pub(crate) use super::super::super::sse::{RecordingKmsKeyAuthorizer, TestAuthorizationHooks, sse_kms_object_metadata};
|
||||
}
|
||||
@@ -553,12 +555,12 @@ pub(crate) mod ecstore_config {
|
||||
|
||||
pub(crate) mod ecstore_data_usage {
|
||||
pub(crate) use rustfs_ecstore::api::data_usage::{
|
||||
BucketUsagePendingReason, BucketUsageStatus, get_bucket_usage_memory, init_compression_total_memory_from_backend,
|
||||
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
|
||||
load_bucket_scan_progress_for_admin, load_bucket_usage_certification_from_backend_cached, load_data_usage_from_backend,
|
||||
lookup_degraded_bucket_usage_baseline, quota_object_size, record_bucket_delete_marker_memory,
|
||||
record_bucket_object_delete_memory, record_bucket_object_version_write_memory, record_bucket_object_write_memory,
|
||||
record_bucket_object_write_unknown_previous_memory, store_compression_total_in_backend, verified_account_bucket_usage,
|
||||
get_bucket_usage_memory, init_compression_total_memory_from_backend, load_admin_data_usage_from_backend_cached,
|
||||
load_admin_data_usage_with_memory_overlay, load_bucket_scan_progress_for_admin, load_bucket_usage_from_backend_cached,
|
||||
load_data_usage_from_backend, lookup_degraded_bucket_usage_baseline, quota_object_size,
|
||||
record_bucket_delete_marker_memory, record_bucket_object_delete_memory, record_bucket_object_version_write_memory,
|
||||
record_bucket_object_write_memory, record_bucket_object_write_unknown_previous_memory,
|
||||
store_compression_total_in_backend, verified_account_bucket_usage,
|
||||
};
|
||||
// Test-only observables for the rustfs/backlog#1306 revert detector.
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -356,6 +356,7 @@ async fn every_served_operation_serves_root_and_refuses_the_callers_it_cannot_ad
|
||||
create_bucket_in_the_store(bucket_replication_lifecycle::REPLICATION_MATRIX_BUCKET).await;
|
||||
create_bucket_in_the_store(bucket_replication_lifecycle::LOCK_CONFIGURATION_MATRIX_BUCKET).await;
|
||||
create_bucket_in_the_store(object_meta::MATRIX_BUCKET).await;
|
||||
object_meta::seed_object_lock_matrix().await;
|
||||
create_bucket_in_the_store(object_misc::MATRIX_BUCKET).await;
|
||||
object_misc::seed_restore_object(object_misc::MATRIX_BUCKET, false).await;
|
||||
object_misc::seed_select_matrix().await;
|
||||
|
||||
@@ -34,6 +34,7 @@ use std::collections::HashMap;
|
||||
/// The object every call names.
|
||||
const KEY: &str = "object-meta";
|
||||
pub(super) const MATRIX_BUCKET: &str = "object-meta-matrix";
|
||||
const LOCKED_KEY: &str = "object-meta-protected";
|
||||
|
||||
pub(crate) const MATRIX: &[MatrixRow] = &[
|
||||
MatrixRow {
|
||||
@@ -114,18 +115,16 @@ fn put_object_acl<'a>(client: &'a Client, _bucket: &'a str) -> BoxFuture<'a, Out
|
||||
}
|
||||
|
||||
fn get_object_legal_hold<'a>(client: &'a Client, _bucket: &'a str) -> BoxFuture<'a, Outcome> {
|
||||
let bucket = MATRIX_BUCKET;
|
||||
Box::pin(async move {
|
||||
let bucket = locked_bucket(bucket).await;
|
||||
outcome(client.get_object_legal_hold().bucket(&bucket).key(KEY).send().await)
|
||||
let bucket = format!("{MATRIX_BUCKET}-locked");
|
||||
outcome(client.get_object_legal_hold().bucket(bucket).key(LOCKED_KEY).send().await)
|
||||
})
|
||||
}
|
||||
|
||||
fn get_object_retention<'a>(client: &'a Client, _bucket: &'a str) -> BoxFuture<'a, Outcome> {
|
||||
let bucket = MATRIX_BUCKET;
|
||||
Box::pin(async move {
|
||||
let bucket = locked_bucket(bucket).await;
|
||||
outcome(client.get_object_retention().bucket(&bucket).key(KEY).send().await)
|
||||
let bucket = format!("{MATRIX_BUCKET}-locked");
|
||||
outcome(client.get_object_retention().bucket(bucket).key(LOCKED_KEY).send().await)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -190,16 +189,30 @@ async fn locked_bucket(bucket: &str) -> String {
|
||||
versioning_enabled: true,
|
||||
..Default::default()
|
||||
};
|
||||
// A second call finds the bucket made by the first.
|
||||
let _ = get_global_app_context()
|
||||
get_global_app_context()
|
||||
.expect("embedded server context")
|
||||
.object_store()
|
||||
.make_bucket(&locked, &options)
|
||||
.await;
|
||||
.await
|
||||
.expect("create Object Lock bucket");
|
||||
put_object_in_the_store(&locked, KEY, HashMap::new()).await;
|
||||
locked
|
||||
}
|
||||
|
||||
pub(super) async fn seed_object_lock_matrix() {
|
||||
let bucket = locked_bucket(MATRIX_BUCKET).await;
|
||||
put_object_in_the_store(
|
||||
&bucket,
|
||||
LOCKED_KEY,
|
||||
HashMap::from([
|
||||
("x-amz-object-lock-legal-hold".to_owned(), "OFF".to_owned()),
|
||||
("x-amz-object-lock-mode".to_owned(), "GOVERNANCE".to_owned()),
|
||||
("x-amz-object-lock-retain-until-date".to_owned(), "2035-01-02T00:00:00Z".to_owned()),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Writes `key` with `metadata` as stored user metadata.
|
||||
async fn put_object_in_the_store(bucket: &str, key: &str, metadata: HashMap<String, String>) {
|
||||
let options = ObjectOptions {
|
||||
@@ -252,45 +265,99 @@ async fn object_metadata_answers_as_stored(server: rustfs::embedded::RustFSServe
|
||||
.expect_err("XML grants are refused");
|
||||
assert_eq!(refusal(&refused), (Some("NotImplemented".to_owned()), Some(501)));
|
||||
|
||||
let unlocked = client
|
||||
.get_object_legal_hold()
|
||||
.bucket(BUCKET)
|
||||
.key(KEY)
|
||||
.send()
|
||||
.await
|
||||
.expect_err("no Object Lock");
|
||||
assert_eq!(refusal(&unlocked), (Some("InvalidRequest".to_owned()), Some(400)));
|
||||
let unlocked = client
|
||||
.get_object_retention()
|
||||
.bucket(BUCKET)
|
||||
.key(KEY)
|
||||
.send()
|
||||
.await
|
||||
.expect_err("no Object Lock");
|
||||
assert_eq!(refusal(&unlocked), (Some("InvalidRequest".to_owned()), Some(400)));
|
||||
for (bucket, code, status) in [(BUCKET, "InvalidRequest", 400), ("object-meta-absent", "NoSuchBucket", 404)] {
|
||||
let retention = client.get_object_retention().bucket(bucket).key(KEY).send().await;
|
||||
let hold = client.get_object_legal_hold().bucket(bucket).key(KEY).send().await;
|
||||
let expected = (Some(code.to_owned()), Some(status));
|
||||
assert_eq!(refusal(&retention.expect_err("lock query refused")), expected, "retention for {bucket}");
|
||||
assert_eq!(refusal(&hold.expect_err("lock query refused")), expected, "legal hold for {bucket}");
|
||||
}
|
||||
|
||||
let locked = locked_bucket(BUCKET).await;
|
||||
let missing = client
|
||||
put_object_in_the_store(
|
||||
&locked,
|
||||
"cleared",
|
||||
HashMap::from([
|
||||
("x-amz-object-lock-mode".to_owned(), String::new()),
|
||||
("x-amz-object-lock-retain-until-date".to_owned(), String::new()),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
for (key, code, status) in [
|
||||
("missing", "NoSuchKey", 404),
|
||||
(KEY, "NoSuchObjectLockConfiguration", 404),
|
||||
("cleared", "NoSuchObjectLockConfiguration", 404),
|
||||
] {
|
||||
let retention = client.get_object_retention().bucket(&locked).key(key).send().await;
|
||||
let hold = client.get_object_legal_hold().bucket(&locked).key(key).send().await;
|
||||
let expected = (Some(code.to_owned()), Some(status));
|
||||
assert_eq!(refusal(&retention.expect_err("no retention")), expected, "retention for {key}");
|
||||
assert_eq!(refusal(&hold.expect_err("no legal hold")), expected, "legal hold for {key}");
|
||||
}
|
||||
|
||||
put_object_in_the_store(
|
||||
&locked,
|
||||
"explicit-off",
|
||||
HashMap::from([("x-amz-object-lock-legal-hold".to_owned(), "OFF".to_owned())]),
|
||||
)
|
||||
.await;
|
||||
put_object_in_the_store(
|
||||
&locked,
|
||||
"unreadable-retention",
|
||||
HashMap::from([("x-amz-object-lock-retain-until-date".to_owned(), "invalid date".to_owned())]),
|
||||
)
|
||||
.await;
|
||||
let unreadable = client
|
||||
.get_object_retention()
|
||||
.bucket(&locked)
|
||||
.key("missing")
|
||||
.key("unreadable-retention")
|
||||
.send()
|
||||
.await
|
||||
.expect_err("a missing key");
|
||||
assert_eq!(refusal(&missing), (Some("InternalError".to_owned()), Some(500)));
|
||||
.expect_err("an unreadable date alone cannot produce a retention response");
|
||||
assert_eq!(refusal(&unreadable), (Some("InternalError".to_owned()), Some(500)));
|
||||
|
||||
let hold = client
|
||||
.get_object_legal_hold()
|
||||
.bucket(&locked)
|
||||
.key(KEY)
|
||||
.key("explicit-off")
|
||||
.send()
|
||||
.await
|
||||
.expect("the default hold");
|
||||
.expect("an explicit OFF hold");
|
||||
assert_eq!(
|
||||
hold.legal_hold().and_then(|hold| hold.status()).map(|status| status.as_str()),
|
||||
Some("OFF")
|
||||
);
|
||||
|
||||
let deleted = client
|
||||
.delete_object()
|
||||
.bucket(&locked)
|
||||
.key(KEY)
|
||||
.send()
|
||||
.await
|
||||
.expect("create a delete marker");
|
||||
let marker = deleted.version_id().expect("delete marker version");
|
||||
for (version_id, code, status) in [(None, "NoSuchKey", 404), (Some(marker.to_owned()), "MethodNotAllowed", 405)] {
|
||||
let retention = client
|
||||
.get_object_retention()
|
||||
.bucket(&locked)
|
||||
.key(KEY)
|
||||
.set_version_id(version_id.clone())
|
||||
.send()
|
||||
.await
|
||||
.expect_err("a marker has no retention");
|
||||
let hold = client
|
||||
.get_object_legal_hold()
|
||||
.bucket(&locked)
|
||||
.key(KEY)
|
||||
.set_version_id(version_id)
|
||||
.send()
|
||||
.await
|
||||
.expect_err("a marker has no legal hold");
|
||||
let expected = (Some(code.to_owned()), Some(status));
|
||||
assert_eq!(refusal(&retention), expected);
|
||||
assert_eq!(refusal(&hold), expected);
|
||||
}
|
||||
|
||||
// Values outside the model's sets, as a replicated or migrated object may hold them.
|
||||
let stored = HashMap::from([
|
||||
("x-amz-object-lock-legal-hold".to_owned(), "on".to_owned()),
|
||||
@@ -328,6 +395,7 @@ async fn object_metadata_answers_as_stored(server: rustfs::embedded::RustFSServe
|
||||
.await
|
||||
.expect_err("retention for a missing version");
|
||||
assert_eq!(refusal(&missing_retention), (Some("NoSuchVersion".to_owned()), Some(404)));
|
||||
assert_eq!(missing_retention.message(), Some("The specified version does not exist."));
|
||||
|
||||
let missing_hold = client
|
||||
.get_object_legal_hold()
|
||||
@@ -338,6 +406,7 @@ async fn object_metadata_answers_as_stored(server: rustfs::embedded::RustFSServe
|
||||
.await
|
||||
.expect_err("legal hold for a missing version");
|
||||
assert_eq!(refusal(&missing_hold), (Some("NoSuchVersion".to_owned()), Some(404)));
|
||||
assert_eq!(missing_hold.message(), Some("The specified version does not exist."));
|
||||
|
||||
let missing = client
|
||||
.get_object_tagging()
|
||||
|
||||
@@ -36,11 +36,11 @@
|
||||
25|crates/ecstore/src/erasure/coding/erasure.rs
|
||||
3|crates/ecstore/src/layout/disks_layout.rs
|
||||
2|crates/ecstore/src/layout/endpoint.rs
|
||||
17|crates/ecstore/src/layout/endpoints.rs
|
||||
14|crates/ecstore/src/layout/endpoints.rs
|
||||
1|crates/ecstore/src/layout/format.rs
|
||||
1|crates/ecstore/src/layout/pool_space.rs
|
||||
1|crates/ecstore/src/layout/set_layout.rs
|
||||
19|crates/ecstore/src/object_api/readers.rs
|
||||
18|crates/ecstore/src/object_api/readers.rs
|
||||
1|crates/ecstore/src/object_api/types.rs
|
||||
3|crates/ecstore/src/runtime/sources.rs
|
||||
4|crates/ecstore/src/services/batch_processor.rs
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import subprocess
|
||||
@@ -19,11 +21,13 @@ SPEC.loader.exec_module(MODULE)
|
||||
HEADER = "thread\top\tn_objects\tbytes\tendpoint\terror\tstart\tend\tduration_ns\n"
|
||||
|
||||
|
||||
def row(thread: int, endpoint: str, start: int, end: int, error: str = "") -> str:
|
||||
def row(thread: int, endpoint: str, start: int, end: int, error: str = "", *, duration_ns: int | None = None) -> str:
|
||||
def stamp(second: int) -> str:
|
||||
return f"2026-01-01T00:00:{second:02d}Z"
|
||||
minute, second = divmod(second, 60)
|
||||
return f"2026-01-01T00:{minute:02d}:{second:02d}Z"
|
||||
|
||||
return f"{thread}\tPUT\t1\t100\t{endpoint}\t{error}\t{stamp(start)}\t{stamp(end)}\t{(end-start)*1_000_000_000}\n"
|
||||
duration = (end - start) * 1_000_000_000 if duration_ns is None else duration_ns
|
||||
return f"{thread}\tPUT\t1\t100\t{endpoint}\t{error}\t{stamp(start)}\t{stamp(end)}\t{duration}\n"
|
||||
|
||||
|
||||
class WarpRawQualityTest(unittest.TestCase):
|
||||
@@ -65,6 +69,8 @@ class WarpRawQualityTest(unittest.TestCase):
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(result["status"], "pass")
|
||||
self.assertEqual(result["steady"]["completed_objects"], 2)
|
||||
self.assertEqual(result["steady"]["completed_requests"], 2)
|
||||
self.assertEqual(result["steady"]["p99_ms"], 2000)
|
||||
self.assertEqual(result["steady"]["start_ns"], result["measure_start_ns"] + 1_000_000_000)
|
||||
self.assertEqual(result["steady"]["duration_secs"], 2)
|
||||
self.assertEqual(result["steady"]["completed_objects_per_second"], 1)
|
||||
@@ -81,8 +87,39 @@ class WarpRawQualityTest(unittest.TestCase):
|
||||
self.assertEqual(status, 1)
|
||||
self.assertEqual(result["reason"], "steady completion rate below minimum")
|
||||
self.assertEqual(result["steady"]["completed_objects"], 0)
|
||||
self.assertIsNone(result["steady"]["p99_ms"])
|
||||
self.assertEqual(result["reqps"], old_result["reqps"])
|
||||
|
||||
def test_steady_rate_upper_bound_rejects_overshoot_and_accepts_equality(self) -> None:
|
||||
source = self.fixture()
|
||||
flags = ("--steady-after-seconds", "1", "--min-steady-rps", "0.5", "--max-steady-rps")
|
||||
status, result = self.run_cli(source, *flags, "0.9")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertEqual(result["reason"], "steady completion rate above maximum")
|
||||
self.assertEqual(result["steady"]["completed_objects_per_second"], 1)
|
||||
self.assertEqual(result["steady"]["max_completed_objects_per_second"], 0.9)
|
||||
status, result = self.run_cli(source, *flags, "1")
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(result["status"], "pass")
|
||||
|
||||
def test_steady_p99_excludes_completions_at_right_edge(self) -> None:
|
||||
source = self.fixture()
|
||||
intervals = ((0, 0, 8), (0, 8, 10), (0, 10, 15), (0, 15, 35), (1, 0, 1), (1, 1, 2), (1, 2, 15), (1, 20, 40))
|
||||
source.write_text(HEADER + "".join(row(thread, "a", start, end) for thread, start, end in intervals))
|
||||
result = MODULE.parse(source, {"a"}, steady_after_seconds=2)
|
||||
self.assertEqual(result["steady"]["completed_requests"], 1)
|
||||
self.assertEqual(result["steady"]["p99_ms"], 2000)
|
||||
|
||||
def test_steady_p99_ranks_recorded_request_durations(self) -> None:
|
||||
source = self.fixture()
|
||||
# Use different wall-clock spans and recorded durations to verify both the
|
||||
# source of latency and the 99th (not the largest) of 100 observations.
|
||||
samples = (row(0, "a", i, i + 1, duration_ns=i * 1_000_000) for i in range(1, 101))
|
||||
source.write_text(HEADER + row(0, "a", 0, 1) + "".join(samples) + row(0, "a", 102, 103))
|
||||
result = MODULE.parse(source, {"a"}, steady_after_seconds=1)
|
||||
self.assertEqual(result["steady"]["completed_requests"], 100)
|
||||
self.assertEqual(result["steady"]["p99_ms"], 99)
|
||||
|
||||
def test_invalid_steady_gate_rejects_missing_empty_and_nonfinite_options(self) -> None:
|
||||
source = self.fixture()
|
||||
cases = (
|
||||
@@ -90,6 +127,9 @@ class WarpRawQualityTest(unittest.TestCase):
|
||||
("--steady-after-seconds", "3", "--min-steady-rps", "1"),
|
||||
("--steady-after-seconds", "-1", "--min-steady-rps", "1"),
|
||||
("--steady-after-seconds", "1", "--min-steady-rps", "nan"),
|
||||
("--max-steady-rps", "1"),
|
||||
("--steady-after-seconds", "1", "--min-steady-rps", "1", "--max-steady-rps", "0.9"),
|
||||
("--steady-after-seconds", "1", "--min-steady-rps", "1", "--max-steady-rps", "inf"),
|
||||
)
|
||||
for args in cases:
|
||||
with self.subTest(args=args):
|
||||
|
||||
@@ -87,7 +87,7 @@ def parse(path: Path, expected_hosts: set[str] | None, *, steady_after_seconds:
|
||||
host_counts[row["endpoint"]] += objects
|
||||
first_end[thread] = min(first_end.get(thread, end), end)
|
||||
last_start[thread] = max(last_start.get(thread, start), start)
|
||||
rows.append((start, end, objects, error))
|
||||
rows.append((start, end, objects, duration_ns))
|
||||
if not rows or raw_errors:
|
||||
raise ValueError("Warp raw input is empty or contains request errors")
|
||||
if expected_hosts is not None and set(host_counts) != expected_hosts:
|
||||
@@ -96,11 +96,11 @@ def parse(path: Path, expected_hosts: set[str] | None, *, steady_after_seconds:
|
||||
window_end = min(last_start.values())
|
||||
if window_end <= window_start:
|
||||
raise ValueError("Warp common active window is not positive")
|
||||
completed_objects = sum(objects for _, end, objects, error in rows if not error and window_start <= end < window_end)
|
||||
completed_requests = sum(1 for _, end, _, error in rows if not error and window_start <= end < window_end)
|
||||
completed_objects = sum(objects for _, end, objects, _ in rows if window_start <= end < window_end)
|
||||
completed_requests = sum(1 for _, end, _, _ in rows if window_start <= end < window_end)
|
||||
fractional_objects = 0.0
|
||||
for start, end, objects, error in rows:
|
||||
if error or end <= start:
|
||||
for start, end, objects, _ in rows:
|
||||
if end <= start:
|
||||
continue
|
||||
overlap = max(0, min(end, window_end) - max(start, window_start))
|
||||
fractional_objects += objects * overlap / (end - start)
|
||||
@@ -129,13 +129,24 @@ def parse(path: Path, expected_hosts: set[str] | None, *, steady_after_seconds:
|
||||
if steady_start >= window_end:
|
||||
raise ValueError("steady cutoff leaves no common active window")
|
||||
steady_duration = (window_end - steady_start) / 1_000_000_000
|
||||
steady_objects = sum(objects for _, end, objects, error in rows if not error and steady_start <= end < window_end)
|
||||
steady_objects = 0
|
||||
steady_latencies_ns = []
|
||||
for _, end, objects, duration_ns in rows:
|
||||
if steady_start <= end < window_end:
|
||||
steady_objects += objects
|
||||
steady_latencies_ns.append(duration_ns)
|
||||
steady_latencies_ns.sort()
|
||||
steady_requests = len(steady_latencies_ns)
|
||||
# Nearest-rank p99 over the same successful requests used for the completion rate.
|
||||
p99_ns = steady_latencies_ns[(99 * steady_requests + 99) // 100 - 1] if steady_requests else None
|
||||
result["steady"] = {
|
||||
"start_ns": steady_start,
|
||||
"end_exclusive_ns": window_end,
|
||||
"duration_secs": steady_duration,
|
||||
"completed_objects": steady_objects,
|
||||
"completed_objects_per_second": steady_objects / steady_duration,
|
||||
"completed_requests": steady_requests,
|
||||
"p99_ms": p99_ns / 1_000_000 if p99_ns is not None else None,
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
@@ -153,12 +164,17 @@ def main() -> int:
|
||||
parser.add_argument("--expected-host", action="append")
|
||||
parser.add_argument("--steady-after-seconds", type=int, help="Seconds to exclude from the start of the common active window")
|
||||
parser.add_argument("--min-steady-rps", type=float, help="Minimum successful object completions per second in the steady window")
|
||||
parser.add_argument("--max-steady-rps", type=float, help="Optional maximum steady completion rate, used with the minimum")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if (args.steady_after_seconds is None) != (args.min_steady_rps is None):
|
||||
raise ValueError("--steady-after-seconds and --min-steady-rps must be used together")
|
||||
if args.min_steady_rps is not None and (not math.isfinite(args.min_steady_rps) or args.min_steady_rps <= 0):
|
||||
raise ValueError("minimum steady rate must be finite and positive")
|
||||
if args.max_steady_rps is not None and (
|
||||
args.min_steady_rps is None or not math.isfinite(args.max_steady_rps) or args.max_steady_rps < args.min_steady_rps
|
||||
):
|
||||
raise ValueError("maximum steady rate must be finite and at least the configured minimum")
|
||||
result = parse(
|
||||
Path(args.input),
|
||||
set(args.expected_host) if args.expected_host else None,
|
||||
@@ -171,8 +187,12 @@ def main() -> int:
|
||||
if args.min_steady_rps is not None:
|
||||
steady = result["steady"]
|
||||
steady["min_completed_objects_per_second"] = args.min_steady_rps
|
||||
if args.max_steady_rps is not None:
|
||||
steady["max_completed_objects_per_second"] = args.max_steady_rps
|
||||
if steady["completed_objects_per_second"] < args.min_steady_rps:
|
||||
result.update(status="fail", reason="steady completion rate below minimum")
|
||||
elif args.max_steady_rps is not None and steady["completed_objects_per_second"] > args.max_steady_rps:
|
||||
result.update(status="fail", reason="steady completion rate above maximum")
|
||||
Path(args.output).write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
|
||||
return int(result["status"] == "fail")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user