Compare commits

...

4 Commits

Author SHA1 Message Date
Cursor Agent a0c63cea72 fix(scanner): walk directories with an explicit stack
Port the scanner folder walker from #9623 onto current main so nested
directory polls no longer grow the worker stack. Keep later main
behavior for object metadata, lifecycle, heal discovery, and child
errors.

Refs rustfs/backlog#3293

Co-authored-by: Chris An <overtrue@users.noreply.github.com>
2026-11-27 10:18:14 +00:00
Chris An def2fb7e47 fix(storage,obs): bound read memory, log disk growth, and part staging (#9668) 2026-11-27 16:41:58 +08:00
Ramakrishna Chilaka d838137c3a perf(ecstore): reuse multipart part-txn lock handles and pre-rename stamps (#9666) 2026-11-27 06:14:01 +00:00
Chris An 52377c1478 ci(security): pin cache-cargo-install-action v3.0.8 for sha pinning (#9662)
Update taiki-e/cache-cargo-install-action in .github/workflows/ci.yml to v3.0.8 (9ee83daaa7b96a6fab930949ecf1122bba04a389), which pins its nested actions/cache reference to commit SHA 55cc8345863c7cc4c66a329aec7e433d2d1c52a9 (v6.1.0).

This removes the sole unpinned nested composite action across all 39 unique third-party actions in the repository and unblocks enabling GitHub repository sha_pinning_required.

Refs: rustfs/backlog#1602
2026-11-27 01:51:12 +00:00
31 changed files with 4944 additions and 1898 deletions
+1 -1
View File
@@ -928,7 +928,7 @@ jobs:
run: sudo apt-get install -y build-essential cmake pkg-config
- name: Install s3s-e2e test tool
uses: taiki-e/cache-cargo-install-action@7447f04c51f2ba27ca35e7f1e28fab848c5b3ba7 # v2
uses: taiki-e/cache-cargo-install-action@9ee83daaa7b96a6fab930949ecf1122bba04a389 # v3.0.8
with:
tool: s3s-e2e
git: https://github.com/s3s-project/s3s.git
+22
View File
@@ -86,3 +86,25 @@ pub const ENV_OBJECT_MMAP_READ_MAX_LENGTH: &str = "RUSTFS_OBJECT_MMAP_READ_MAX_L
/// materialize up to `data_shards x cap` bytes; raising the cap raises that
/// per-request bound proportionally.
pub const DEFAULT_OBJECT_MMAP_READ_MAX_LENGTH: usize = 32 * 1024 * 1024;
/// Environment variable capping total process-wide in-flight bytes retained by
/// buffered local shard reads (both batch positioned reads and mmap-copy reads).
///
/// Bounding only individual shard length still allows many concurrent unread or
/// slow-consumed `GetObject` responses to accumulate unbounded in-memory shard
/// buffers. When this process-wide budget cannot admit a read, the read falls
/// back to the bounded streaming reader path; reserved bytes are released on
/// `Drop` (including reader cancellation).
///
/// - Purpose: Bound process-wide heap memory retained by in-memory shard reads
/// - Acceptable values: byte count as an unsigned integer; `0` disables
/// in-memory buffered shard reads so every read streams
/// - Example: `export RUSTFS_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES=268435456`
pub const ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES: &str = "RUSTFS_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES";
/// Default process-wide in-flight byte budget for buffered shard reads: 256 MiB.
///
/// Large enough to keep the fast in-memory path active for concurrent typical
/// reads (including multiple full 32 MiB/shard reads) while placing a strict
/// process-wide ceiling on unread in-memory shard allocations.
pub const DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES: usize = 256 * 1024 * 1024;
+30
View File
@@ -75,7 +75,26 @@ pub const ENV_OBS_LOG_SPAN_EVENTS: &str = "RUSTFS_OBS_LOG_SPAN_EVENTS";
/// Log cleanup related configurations
pub const ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES";
/// Dedicated byte budget for compressed log archives (`.gz` / `.zst`).
/// When unset, compressed archives share the remaining
/// `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` budget with surviving rolled logs.
/// Setting an explicit non-zero value enforces an independent archive budget;
/// `0` removes the byte cap on archives (retention days still apply).
pub const ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES";
pub const ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES: &str = "RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES";
/// Maximum number of rolled log files compressed in a single cleanup pass.
/// Bounds per-pass CPU spikes on large backlogs; `0` means unlimited.
/// Over-budget files beyond this cap are deleted directly without compression
/// so the disk budget still holds in one pass.
pub const ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS: &str = "RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS";
/// Maximum number of log events per second admitted to the file sink across all
/// callsites. `0` disables sink-side rate limiting.
pub const ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC: &str = "RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC";
/// Maximum number of log events per second admitted to the file sink from any
/// single callsite bucket so one noisy site cannot starve other log sites.
/// When unset, derived as `(sink_max_events_per_sec / 4).max(1)`; `0` disables
/// per-callsite isolation while keeping the global sink ceiling.
pub const ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC: &str = "RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC";
pub const ENV_OBS_LOG_COMPRESS_OLD_FILES: &str = "RUSTFS_OBS_LOG_COMPRESS_OLD_FILES";
pub const ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL: &str = "RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL";
pub const ENV_OBS_LOG_COMPRESSION_ALGORITHM: &str = "RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM";
@@ -100,6 +119,10 @@ pub const DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES: u64 = 0; // No per-file tr
/// the active file is bounded only by the rotation period, and the cleaner
/// never touches the active file. An explicit `0` keeps size rolling off.
pub const DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES: u64 = 256 * 1024 * 1024; // 256 MiB
/// Default maximum rolled log files compressed in a single cleanup pass.
pub const DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS: usize = 32;
/// Default global file-sink event rate ceiling (events/second).
pub const DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC: u64 = 10_000;
pub const DEFAULT_OBS_LOG_COMPRESS_OLD_FILES: bool = true;
pub const DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL: u32 = 6;
pub const DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM_GZIP: &str = "gzip";
@@ -184,7 +207,14 @@ mod tests {
assert_eq!(ENV_OBS_GET_STAGE_LOCAL_SUMMARY_FILE, "RUSTFS_OBS_GET_STAGE_LOCAL_SUMMARY_FILE");
// Test log cleanup related env keys
assert_eq!(ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, "RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES");
assert_eq!(ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, "RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS");
assert_eq!(ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC, "RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC");
assert_eq!(
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC,
"RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC"
);
assert_eq!(ENV_OBS_LOG_COMPRESS_OLD_FILES, "RUSTFS_OBS_LOG_COMPRESS_OLD_FILES");
assert_eq!(ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL, "RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL");
assert_eq!(ENV_OBS_LOG_COMPRESSION_ALGORITHM, "RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM");
+368 -88
View File
@@ -816,31 +816,46 @@ fn rename_in_same_dir_fd(
}
#[cfg(unix)]
fn part_txn_files_ready_with_stamp(
txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> Option<Option<multipart_source_state::FileStamp>> {
if let Some(d_fd) = txn_dir_fd {
use rustix::fs::{AtFlags, statat};
let pub_st = statat(d_fd, PART_TRANSACTION_PUBLISH_META, AtFlags::SYMLINK_NOFOLLOW)
.ok()
.filter(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG)?;
let new_ok = statat(d_fd, PART_TRANSACTION_NEW_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG && st.st_size as u64 == expected_len);
return new_ok.then(|| multipart_source_state::FileStamp::from_stat(&pub_st));
}
(publish_meta_path.is_file()
&& std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len))
.then_some(None)
}
#[cfg(not(unix))]
fn part_txn_files_ready_with_stamp(
_txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> Option<Option<multipart_source_state::FileStamp>> {
(publish_meta_path.is_file()
&& std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len))
.then_some(None)
}
#[cfg(test)]
fn part_txn_files_ready(
txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> bool {
if let Some(d_fd) = txn_dir_fd {
use rustix::fs::{AtFlags, statat};
let pub_ok = statat(d_fd, PART_TRANSACTION_PUBLISH_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG);
let new_ok = statat(d_fd, PART_TRANSACTION_NEW_META, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|st| (st.st_mode & libc::S_IFMT) == libc::S_IFREG && st.st_size as u64 == expected_len);
return pub_ok && new_ok;
}
publish_meta_path.is_file() && std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len)
}
#[cfg(not(unix))]
fn part_txn_files_ready(
_txn_dir_fd: Option<&std::fs::File>,
publish_meta_path: &Path,
transaction_meta_path: &Path,
expected_len: u64,
) -> bool {
publish_meta_path.is_file() && std::fs::metadata(transaction_meta_path).is_ok_and(|m| m.is_file() && m.len() == expected_len)
part_txn_files_ready_with_stamp(txn_dir_fd, publish_meta_path, transaction_meta_path, expected_len).is_some()
}
#[cfg(unix)]
@@ -913,9 +928,12 @@ struct PreparedPartTxnReceipt {
dst_meta_path: PathBuf,
transaction_path: PathBuf,
meta: Bytes,
part_info: ObjectPartInfo,
had_old_data: bool,
had_old_meta: bool,
admission: Option<multipart_staging::MultipartSourceAdmission>,
upload_lock: Option<multipart_staging::UploadLockHandle>,
txn_namespace_lock: os::NamespaceMutationLockHandle,
src_parent_fd: Option<Arc<std::fs::File>>,
txn_dir_fd: Option<Arc<std::fs::File>>,
txn_parent_fd: Option<Arc<std::fs::File>>,
@@ -928,6 +946,8 @@ struct PublishedPartTxnReceipt {
had_old_data: bool,
had_old_meta: bool,
admission: Option<multipart_staging::MultipartSourceAdmission>,
upload_lock: Option<multipart_staging::UploadLockHandle>,
txn_namespace_lock: os::NamespaceMutationLockHandle,
txn_dir_fd: Option<Arc<std::fs::File>>,
txn_parent_fd: Option<Arc<std::fs::File>>,
}
@@ -5025,7 +5045,7 @@ impl LazyLocalFileWriter {
let sync_on_close = self.sync_on_close;
let mark_dir_presynced = self.mark_dir_presynced;
let parent_exists = self.parent_exists;
let volume_dir_for_presync = self.volume_dir.clone();
let volume_dir_for_presync = (close_after && sync_on_close).then(|| self.volume_dir.clone());
self.last_integrity_digest = None;
let write_and_finish = move |mut file: std::fs::File, file_path: PathBuf| {
let digest = match integrity_spec {
@@ -5053,8 +5073,8 @@ impl LazyLocalFileWriter {
}
reclaim_std_file_cache(&file, reclaim_len, reclaim_on_shutdown);
drop(file);
if sync_on_close {
mark_presynced_after_lazy_write(&file_path, &volume_dir_for_presync, mark_dir_presynced);
if let Some(ref volume_dir) = volume_dir_for_presync {
mark_presynced_after_lazy_write(&file_path, volume_dir, mark_dir_presynced);
}
Ok((None, wire_len, digest))
} else {
@@ -14918,12 +14938,36 @@ const LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES: usize = 512 * 1024;
/// multi-disk topologies. When every window reaches
/// `LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES`, each shard gets its own dispatch so
/// copies and device reads proceed concurrently.
#[cfg(unix)]
///
/// Enforces the process-wide in-flight read memory budget before allocating
/// shard buffers and binds each permit to the returned [`Bytes`] lifetime.
#[cfg(all(unix, test))]
pub(crate) async fn batch_shard_pread(requests: Vec<(std::path::PathBuf, usize, usize)>) -> Vec<Result<Bytes>> {
let lengths: Vec<usize> = requests.iter().map(|(_, _, length)| *length).collect();
let Some(permits) = crate::set_disk::read_budget::global_in_flight_read_budget().try_reserve_batch(&lengths) else {
return (0..requests.len())
.map(|_| Err(crate::set_disk::read_budget::in_flight_read_budget_exhausted_error()))
.collect();
};
let permitted = requests
.into_iter()
.zip(permits)
.map(|((path, offset, length), permit)| (path, offset, length, permit))
.collect();
batch_shard_pread_with_permits(permitted).await
}
#[cfg(unix)]
pub(crate) type PermittedShardPreadRequest = (std::path::PathBuf, usize, usize, crate::set_disk::read_budget::ReadMemoryPermit);
/// Positioned reads for local EC shard files with pre-reserved in-flight byte
/// permits, returned in request order.
#[cfg(unix)]
pub(crate) async fn batch_shard_pread_with_permits(requests: Vec<PermittedShardPreadRequest>) -> Vec<Result<Bytes>> {
if requests.len() < 2
|| requests
.iter()
.any(|(_, _, length)| *length < LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES)
.any(|(_, _, length, _)| *length < LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES)
{
return batch_shard_pread_blocking(requests).await;
}
@@ -14936,7 +14980,7 @@ pub(crate) async fn batch_shard_pread(requests: Vec<(std::path::PathBuf, usize,
/// Read every request in turn inside one `spawn_blocking`.
#[cfg(unix)]
async fn batch_shard_pread_blocking(requests: Vec<(std::path::PathBuf, usize, usize)>) -> Vec<Result<Bytes>> {
async fn batch_shard_pread_blocking(requests: Vec<PermittedShardPreadRequest>) -> Vec<Result<Bytes>> {
let n = requests.len();
let metrics = rustfs_io_metrics::LocalBatchReadMetrics::capture();
let submitted = metrics.as_ref().map(|_| std::time::Instant::now());
@@ -14979,7 +15023,7 @@ async fn batch_shard_pread_blocking(requests: Vec<(std::path::PathBuf, usize, us
metrics.record_batch(n);
}
let mut results = Vec::with_capacity(n);
for (file_path, offset, length) in requests {
for (file_path, offset, length, permit) in requests {
#[cfg(feature = "diagnostic-local-batch")]
let _index = results.len();
let mut total = 0usize;
@@ -15060,7 +15104,7 @@ async fn batch_shard_pread_blocking(requests: Vec<(std::path::PathBuf, usize, us
}
))?;
}
Ok(Bytes::from(buf))
Ok(permit.wrap_vec(buf))
})();
#[cfg(feature = "diagnostic-local-batch")]
if let Some(sample) = &diagnostic {
@@ -15106,6 +15150,18 @@ fn measure_local_batch_stage<T>(
result
}
impl LocalDisk {
async fn check_deferred_org_volume(&self, org_volume: &str) -> Result<()> {
let org_volume_path = self.io_get_bucket_path(org_volume)?;
if !skip_access_checks(org_volume) {
cached_access(&org_volume_path)
.await
.map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?;
}
Ok(())
}
}
#[async_trait::async_trait]
impl DiskAPI for LocalDisk {
async fn list_multipart_index_roots(
@@ -15889,9 +15945,9 @@ impl DiskAPI for LocalDisk {
} else {
self.usage_watch_binding.owner(dst_volume, usage_owner)
};
let source_owner = self
.multipart_source_owner(dst_volume, dst_path, true, false, usage_owner)
.await?;
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = self.lookup_multipart_upload_lock(dst_volume, dst_path, true)?;
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
let (src_volume_dir, src_file_path) = self.io_get_bucket_and_object_path(src_volume, src_path)?;
let (dst_volume_dir, dst_file_path) = self.io_get_bucket_and_object_path(dst_volume, dst_path)?;
let admission = self.multipart_source_admission_after_validated_part_path(dst_volume, dst_path)?;
@@ -15910,7 +15966,7 @@ impl DiskAPI for LocalDisk {
let durability = effective_durability(dst_volume);
let part = ObjectPartInfo::unmarshal(&meta)?;
let integrity_prep = if let Some(integrity) = part.integrity {
let integrity_prep = if let Some(integrity) = part.integrity.clone() {
integrity.validate()?;
if usize::try_from(integrity.number).map_err(|_| DiskError::FileCorrupt)? != part.number
|| usize::try_from(integrity.size).map_err(|_| DiskError::FileCorrupt)? != part.size
@@ -15935,7 +15991,13 @@ impl DiskAPI for LocalDisk {
multipart_source_state::begin_active_multipart_part_transaction(source, part.number);
}
os::record_native_publication(&transaction_path);
let lease = os::acquire_namespace_mutation_lease_with_owner(&transaction_path, source_owner).await;
let txn_namespace_lock = os::lookup_namespace_mutation_lock(&transaction_path);
let lease = os::acquire_namespace_mutation_lease_with_lock_and_queue(
&txn_namespace_lock,
Arc::clone(&self.blocking_queue),
source_owner,
)
.await;
let res = os::run_blocking_namespace_operation_with_sync(
lease,
sync,
@@ -16261,9 +16323,12 @@ impl DiskAPI for LocalDisk {
dst_meta_path,
transaction_path,
meta,
part_info: part,
had_old_data,
had_old_meta,
admission,
upload_lock,
txn_namespace_lock,
src_parent_fd,
txn_dir_fd,
txn_parent_fd,
@@ -16289,10 +16354,21 @@ impl DiskAPI for LocalDisk {
#[tracing::instrument(level = "trace", skip_all)]
async fn settle_part_transaction(&self, volume: &str, path: &str, action: PartTransactionAction) -> Result<()> {
multipart_staging::reject_noncanonical_scope(&self.root, self.io_root(), volume, path)?;
let usage_owner = self.usage_watch_binding.owner(volume, None);
let source_owner = self.multipart_source_owner(volume, path, true, false, usage_owner).await?;
let txn_rel_path = crate::disk::part_transaction_path(path);
let txn_open_path = self.io_get_object_open_path(volume, &txn_rel_path).ok();
let cached_upload_lock = txn_open_path.as_deref().and_then(|txn_open| {
PUBLISHED_PART_TXN_RECEIPTS
.with_get(txn_open, |entry| entry.upload_lock.clone())
.or_else(|| PREPARED_PART_TXN_RECEIPTS.with_get(txn_open, |entry| entry.upload_lock.clone()))
});
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = match cached_upload_lock {
Some(lock) => lock,
None => self.lookup_multipart_upload_lock(volume, path, true)?,
};
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
let cached_published = txn_open_path.as_deref().and_then(take_published_part_txn_receipt);
if cached_published.is_none()
&& let Some(ref txn_open) = txn_open_path
@@ -16306,6 +16382,7 @@ impl DiskAPI for LocalDisk {
skip_obsolete_read_on_commit,
cached_old_flags,
admission,
cached_txn_namespace_lock,
mut txn_dir_fd,
mut txn_parent_fd,
) = match cached_published {
@@ -16316,6 +16393,7 @@ impl DiskAPI for LocalDisk {
!entry.had_old_meta,
Some((entry.had_old_data, entry.had_old_meta)),
entry.admission,
Some(entry.txn_namespace_lock),
entry.txn_dir_fd,
entry.txn_parent_fd,
),
@@ -16327,7 +16405,17 @@ impl DiskAPI for LocalDisk {
for candidate in [&current_data_path, &current_meta_path, &transaction_path] {
check_path_length(candidate.to_string_lossy().as_ref())?;
}
(current_data_path, current_meta_path, transaction_path, false, None, admission, None, None)
(
current_data_path,
current_meta_path,
transaction_path,
false,
None,
admission,
None,
None,
None,
)
}
};
let admission_source = admission.as_ref().map(|a| a.source().to_path_buf());
@@ -16338,7 +16426,16 @@ impl DiskAPI for LocalDisk {
.and_then(|name| name.to_str())
.and_then(|name| name.strip_prefix("part."))
.and_then(|num| num.parse::<usize>().ok());
let lease = os::acquire_namespace_mutation_lease_with_owner(&transaction_path, source_owner).await;
let lease = match cached_txn_namespace_lock {
Some(ref lock) => {
os::acquire_namespace_mutation_lease_with_lock_and_queue(lock, Arc::clone(&self.blocking_queue), source_owner)
.await
}
None => {
os::acquire_namespace_mutation_lease_with_queue(&transaction_path, Arc::clone(&self.blocking_queue), source_owner)
.await
}
};
os::record_native_publication(&current_data_path);
let res = os::run_blocking_namespace_operation_with_sync(lease, sync, move || -> std::io::Result<Result<bool>> {
@@ -16502,14 +16599,26 @@ impl DiskAPI for LocalDisk {
} else {
self.usage_watch_binding.owner(dst_volume, usage_owner)
};
let source_owner = self
.multipart_source_owner(dst_volume, dst_path, true, false, usage_owner)
.await?;
let src_is_dir = has_suffix(src_path, SLASH_SEPARATOR);
let dst_is_dir = has_suffix(dst_path, SLASH_SEPARATOR);
let txn_open_path = (!src_is_dir)
.then(|| {
let txn_rel = crate::disk::part_transaction_path(dst_path);
self.io_get_object_open_path(dst_volume, &txn_rel).ok()
})
.flatten();
let cached_upload_lock = txn_open_path
.as_deref()
.and_then(|txn_open| PREPARED_PART_TXN_RECEIPTS.with_get(txn_open, |entry| entry.upload_lock.clone()));
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
let upload_lock = match cached_upload_lock {
Some(lock) => lock,
None => self.lookup_multipart_upload_lock(dst_volume, dst_path, true)?,
};
let source_owner = Self::acquire_multipart_source_owner_with_handle(upload_lock.as_ref(), false, usage_owner).await;
multipart_staging::reject_reserved_anchor(dst_path)?;
pool_meta_native::reject_raw_path(&self.root, src_volume, src_path)?;
pool_meta_native::reject_raw_path(&self.root, dst_volume, dst_path)?;
let src_is_dir = has_suffix(src_path, SLASH_SEPARATOR);
let dst_is_dir = has_suffix(dst_path, SLASH_SEPARATOR);
if !src_is_dir && dst_is_dir || src_is_dir && !dst_is_dir {
warn!(
@@ -16524,20 +16633,15 @@ impl DiskAPI for LocalDisk {
return Err(DiskError::FileAccessDenied);
}
let cached_prepared = if !src_is_dir {
let txn_rel = crate::disk::part_transaction_path(dst_path);
self.io_get_object_open_path(dst_volume, &txn_rel)
.ok()
.and_then(|txn_open| take_prepared_part_txn_receipt(&txn_open))
.filter(|entry| {
entry.meta == meta
&& self
.io_get_object_open_path(src_volume, src_path)
.is_ok_and(|src_open| src_open == entry.src_file_path)
})
} else {
None
};
let cached_prepared = txn_open_path
.as_deref()
.and_then(take_prepared_part_txn_receipt)
.filter(|entry| {
entry.meta == meta
&& self
.io_get_object_open_path(src_volume, src_path)
.is_ok_and(|src_open| src_open == entry.src_file_path)
});
let (
src_volume_dir,
@@ -16548,6 +16652,8 @@ impl DiskAPI for LocalDisk {
transaction_path,
preverified_meta_and_old_flags,
admission,
cached_part_info,
cached_txn_namespace_lock,
mut src_parent_fd,
txn_dir_fd,
txn_parent_fd,
@@ -16561,6 +16667,8 @@ impl DiskAPI for LocalDisk {
Some(entry.transaction_path),
Some((entry.had_old_data, entry.had_old_meta)),
entry.admission,
Some(entry.part_info),
Some(entry.txn_namespace_lock),
entry.src_parent_fd,
entry.txn_dir_fd,
entry.txn_parent_fd,
@@ -16603,6 +16711,8 @@ impl DiskAPI for LocalDisk {
None,
None,
None,
None,
None,
)
}
};
@@ -16619,12 +16729,20 @@ impl DiskAPI for LocalDisk {
let src_file_for_cleanup = src_file_path.clone();
let src_volume_for_cleanup = src_volume_dir.clone();
let meta_for_legacy = meta.clone();
let lease = os::acquire_namespace_mutation_lease_with_owner(&dst_file_path, source_owner.clone()).await;
let lease = os::acquire_namespace_mutation_lease_with_queue(
&dst_file_path,
Arc::clone(&self.blocking_queue),
source_owner.clone(),
)
.await;
let published_transaction_meta = os::run_blocking_namespace_operation_with_sync(
lease,
sync,
move || -> std::io::Result<(bool, Option<(PathBuf, PublishedPartTxnReceipt)>)> {
type RenamePartOutcome = (
bool,
Option<multipart_source_state::FileStamp>,
Option<(PathBuf, PublishedPartTxnReceipt)>,
);
let published_transaction_meta =
os::run_blocking_namespace_operation_with_sync(lease, sync, move || -> std::io::Result<RenamePartOutcome> {
if let Some(check) = &admission {
check.validate().map_err(to_file_error)?;
}
@@ -16676,18 +16794,20 @@ impl DiskAPI for LocalDisk {
}
}
let mut precomputed_publish_stamp = None;
let transaction_publish_meta = if let Some(transaction_path) = transaction_path.as_ref() {
let transaction_meta_path = transaction_path.join(PART_TRANSACTION_NEW_META);
let publish_meta_path = transaction_path.join(PART_TRANSACTION_PUBLISH_META);
if !cfg!(test)
&& preverified_meta_and_old_flags.is_some()
&& part_txn_files_ready(
&& let Some(stamp) = part_txn_files_ready_with_stamp(
txn_dir_fd.as_deref(),
&publish_meta_path,
&transaction_meta_path,
meta.len() as u64,
)
{
precomputed_publish_stamp = stamp;
Some(publish_meta_path)
} else {
match std::fs::File::open(&transaction_meta_path) {
@@ -16845,6 +16965,7 @@ impl DiskAPI for LocalDisk {
let fast_meta_renamed = false;
if !fast_meta_renamed {
precomputed_publish_stamp = None;
os::rename_all_with_precondition_and_parent_sync_std(
&transaction_publish_meta,
dst_meta_path,
@@ -16876,6 +16997,8 @@ impl DiskAPI for LocalDisk {
let published_entry = if let (Some((had_old_data, had_old_meta)), Some(txn_path), Some(meta_path)) =
(preverified_meta_and_old_flags, transaction_path, dst_meta_path.as_path().into())
{
let txn_namespace_lock =
cached_txn_namespace_lock.unwrap_or_else(|| os::lookup_namespace_mutation_lock(&txn_path));
Some((
txn_path.clone(),
PublishedPartTxnReceipt {
@@ -16885,6 +17008,8 @@ impl DiskAPI for LocalDisk {
had_old_data,
had_old_meta,
admission,
upload_lock,
txn_namespace_lock,
txn_dir_fd,
txn_parent_fd,
},
@@ -16892,20 +17017,19 @@ impl DiskAPI for LocalDisk {
} else {
None
};
Ok((true, published_entry))
Ok((true, precomputed_publish_stamp, published_entry))
} else {
Ok((false, None))
Ok((false, None, None))
}
},
)
.await
.map_err(DiskError::from);
let published_transaction_meta = match published_transaction_meta {
Ok((published, maybe_entry)) => {
})
.await
.map_err(DiskError::from);
let (published_transaction_meta, precomputed_publish_stamp) = match published_transaction_meta {
Ok((published, stamp, maybe_entry)) => {
if let Some((txn_path, entry)) = maybe_entry {
put_published_part_txn_receipt(&txn_path, entry);
}
published
(published, stamp)
}
Err(err) => {
if let Some(ref source) = admission_source {
@@ -16933,9 +17057,13 @@ impl DiskAPI for LocalDisk {
}
if !src_is_dir
&& let Some(ref source) = admission_source
&& let Ok(part_info) = ObjectPartInfo::unmarshal(&meta_for_legacy)
&& let Some(part_info) = cached_part_info.or_else(|| ObjectPartInfo::unmarshal(&meta_for_legacy).ok())
{
multipart_source_state::record_active_multipart_part_committed(source, part_info);
multipart_source_state::record_active_multipart_part_committed(
source,
part_info,
published_transaction_meta.then_some(precomputed_publish_stamp).flatten(),
);
}
if src_is_dir {
@@ -17211,7 +17339,14 @@ impl DiskAPI for LocalDisk {
length: usize,
metrics: Option<MmapCopyStageMetrics>,
) -> Result<Bytes> {
self.io_backend.pread_bytes(volume, path, offset, length, metrics).await
if offset.checked_add(length).is_none() {
return self.io_backend.pread_bytes(volume, path, offset, length, metrics).await;
}
let in_flight_permit = crate::set_disk::read_budget::global_in_flight_read_budget()
.try_reserve(length)
.ok_or_else(crate::set_disk::read_budget::in_flight_read_budget_exhausted_error)?;
let bytes = self.io_backend.pread_bytes(volume, path, offset, length, metrics).await?;
Ok(in_flight_permit.wrap_bytes(bytes))
}
/// List a single directory. `count < 0` enumerates the *whole* directory in
@@ -17853,22 +17988,40 @@ impl DiskAPI for LocalDisk {
} else {
GET_OBJECT_PATH_LEGACY_DUPLEX
};
if !org_volume.is_empty() {
let org_volume_path = self.io_get_bucket_path(org_volume)?;
if !skip_access_checks(org_volume) {
cached_access(&org_volume_path)
.await
.map_err(|e| to_access_error(e, DiskError::VolumeAccessDenied))?;
}
#[cfg(target_os = "linux")]
let defer_org_volume_check = !org_volume.is_empty()
&& org_volume == volume
&& volume != RUSTFS_META_MULTIPART_BUCKET
&& is_clean_relative_segment(volume);
#[cfg(not(target_os = "linux"))]
let defer_org_volume_check = false;
if !org_volume.is_empty() && !defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
let path_resolve_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let (volume_dir, file_path) = self.io_get_bucket_and_object_open_path(volume, path)?;
let resolved_paths = self.io_get_bucket_and_object_open_path(volume, path);
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_PATH_RESOLVE, path_resolve_start);
let (volume_dir, file_path) = match resolved_paths {
Ok(paths) => paths,
Err(err) => {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(err);
}
};
let path_check_start = get_stage_timer_if_enabled(stage_metrics_enabled);
check_path_length(file_path.to_string_lossy().as_ref())?;
let len_check = check_path_length(file_path.to_string_lossy().as_ref());
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_PATH_CHECK, path_check_start);
if let Err(err) = len_check {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(err);
}
if volume == RUSTFS_META_MULTIPART_BUCKET
&& !opts.read_data
@@ -17884,13 +18037,19 @@ impl DiskAPI for LocalDisk {
let xlmeta_read_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let raw_read_result = self.read_raw(volume, &volume_dir, &file_path, read_data).await;
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READ_VERSION_XLMETA_READ, xlmeta_read_start);
let (data, _) = raw_read_result.map_err(|e| {
if e == DiskError::FileNotFound && !version_id.is_empty() {
DiskError::FileVersionNotFound
} else {
e
let (data, _) = match raw_read_result {
Ok(res) => res,
Err(e) => {
if defer_org_volume_check {
self.check_deferred_org_volume(org_volume).await?;
}
return Err(if e == DiskError::FileNotFound && !version_id.is_empty() {
DiskError::FileVersionNotFound
} else {
e
});
}
})?;
};
let decode_start = get_stage_timer_if_enabled(stage_metrics_enabled);
let file_info_result: Result<FileInfo> = (|| {
@@ -42375,7 +42534,7 @@ mod test {
let source_root = multipart_staging::upload_scope_root(mp_dst_path, true);
let mut upload = FileInfo::new(source_root, 2, 2);
upload.erasure.index = 1;
upload.data_dir = Some(Uuid::new_v4());
upload.data_dir = Some(Uuid::parse_str("58ba822c-06e4-4332-81cc-be2c9d921900").expect("valid part data_dir uuid"));
upload.mod_time = Some(time::OffsetDateTime::now_utc());
upload.fresh = true;
disk.write_metadata("", RUSTFS_META_MULTIPART_BUCKET, source_root, upload)
@@ -42397,6 +42556,14 @@ mod test {
.expect("stage multipart part");
let mp_dir = disk.io_root().join(RUSTFS_META_MULTIPART_BUCKET);
let mp_txn_open_path = disk
.io_get_object_open_path(RUSTFS_META_MULTIPART_BUCKET, &crate::disk::part_transaction_path(mp_dst_path))
.expect("multipart txn open path");
let expected_upload_lock = disk
.lookup_multipart_upload_lock(RUSTFS_META_MULTIPART_BUCKET, mp_dst_path, true)
.expect("lookup upload lock")
.expect("multipart upload lock present");
let expected_txn_ns_lock = os::lookup_namespace_mutation_lock(&mp_txn_open_path);
let jobs_before_mp = disk.blocking_queue.submitted_jobs_for_test();
let fsync_jobs_before_mp = disk.blocking_queue.submitted_fsync_jobs_for_test();
let mp_syncs_before = os::fsync_dir_recorder::count_under(&mp_dir);
@@ -42409,6 +42576,19 @@ mod test {
)
.await
.expect("prepare_part_transaction");
assert!(
PREPARED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |entry| {
entry.part_info.number == 1
&& entry
.upload_lock
.as_ref()
.is_some_and(|lock| lock.ptr_eq(&expected_upload_lock))
&& entry.txn_namespace_lock.ptr_eq(&expected_txn_ns_lock)
})
.unwrap_or(false),
"PreparedPartTxnReceipt must retain parsed part_info, UploadLockHandle, and NamespaceMutationLockHandle"
);
disk.rename_part(
RUSTFS_META_TMP_BUCKET,
"mp-stage/part.1",
@@ -42418,6 +42598,38 @@ mod test {
)
.await
.expect("rename_part");
assert!(
PUBLISHED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |entry| {
entry
.upload_lock
.as_ref()
.is_some_and(|lock| lock.ptr_eq(&expected_upload_lock))
&& entry.txn_namespace_lock.ptr_eq(&expected_txn_ns_lock)
})
.unwrap_or(false),
"PublishedPartTxnReceipt must carry UploadLockHandle and NamespaceMutationLockHandle into settle_part_transaction"
);
let alias_meta_path = format!("multipart/{mp_dst_path}");
assert_eq!(
disk.settle_part_transaction(RUSTFS_META_BUCKET, &alias_meta_path, PartTransactionAction::Commit)
.await
.expect_err("volume/path alias must be rejected before consuming PublishedPartTxnReceipt"),
DiskError::ConditionalDeleteConflict
);
let dot_segment_mp_path = mp_dst_path.replacen('/', "/./", 1);
assert_eq!(
disk.settle_part_transaction(RUSTFS_META_MULTIPART_BUCKET, &dot_segment_mp_path, PartTransactionAction::Commit)
.await
.expect_err("dot-segment path must be rejected before consuming PublishedPartTxnReceipt"),
DiskError::ConditionalDeleteConflict
);
assert!(
PUBLISHED_PART_TXN_RECEIPTS
.with_get(&mp_txn_open_path, |_| true)
.unwrap_or(false),
"rejected settle_part_transaction calls must not consume warm PublishedPartTxnReceipt"
);
disk.settle_part_transaction(RUSTFS_META_MULTIPART_BUCKET, mp_dst_path, PartTransactionAction::Commit)
.await
.expect("settle_part_transaction");
@@ -42443,10 +42655,78 @@ mod test {
.expect("read settled part"),
part_payload
);
let source_open_path = disk
.io_get_object_open_path(RUSTFS_META_MULTIPART_BUCKET, source_root)
.expect("source open path");
assert_eq!(
multipart_source_state::get_active_multipart_source_part_with_head(&source_open_path, 1, false)
.map(|part| (part.number, part.size)),
Some((1, part_payload.len())),
"ACTIVE_MULTIPART_SOURCE_HEADS must serve committed part metadata after rename_part + settle_part_transaction"
);
// 4. Deferred org_volume check in read_version must preserve VolumeNotFound precedence
// when org_volume == volume does not exist on disk, and FileVersionNotFound when
// org_volume == volume exists and version_id is non-empty.
let missing_bucket = "nonexistent-read-version-bucket";
assert_eq!(
disk.read_version(missing_bucket, missing_bucket, "missing-obj", "", &ReadOptions::default())
.await
.expect_err("missing org_volume == volume must fail"),
DiskError::VolumeNotFound,
"read_version must preserve VolumeNotFound when org_volume == volume does not exist"
);
assert_eq!(
disk.read_version(missing_bucket, missing_bucket, "../escape", "", &ReadOptions::default())
.await
.expect_err("missing org_volume with invalid path must still report VolumeNotFound first"),
DiskError::VolumeNotFound,
"read_version must preserve VolumeNotFound precedence over path-resolve errors when org_volume == volume is missing"
);
assert_eq!(
disk.read_version(
bucket,
bucket,
"missing-versioned-obj",
"00000000-0000-0000-0000-000000000001",
&ReadOptions::default(),
)
.await
.expect_err("existing bucket with missing object and non-empty version_id must return FileVersionNotFound"),
DiskError::FileVersionNotFound,
"read_version must preserve FileNotFound -> FileVersionNotFound mapping when org_volume == volume exists"
);
println!("HOTPATH_BUDGET_OK");
}
#[cfg(unix)]
#[test]
fn part_txn_files_ready_with_stamp_matches_post_rename_file_stamp() {
let dir = tempfile::tempdir().expect("tempdir");
let txn_dir = dir.path().join("part.1.part-txn");
std::fs::create_dir_all(&txn_dir).expect("create txn dir");
let publish_meta = txn_dir.join(PART_TRANSACTION_PUBLISH_META);
let new_meta = txn_dir.join(PART_TRANSACTION_NEW_META);
let payload = b"serialized-part-meta";
std::fs::write(&publish_meta, payload).expect("write publish.meta");
std::fs::write(&new_meta, payload).expect("write new.meta");
let txn_fd = std::fs::File::open(&txn_dir).expect("open txn_dir_fd");
let pre_rename_stamp = part_txn_files_ready_with_stamp(Some(&txn_fd), &publish_meta, &new_meta, payload.len() as u64)
.expect("part_txn_files_ready_with_stamp must report ready")
.expect("unix statat path must return precomputed FileStamp");
let committed_meta = dir.path().join("part.1.meta");
std::fs::rename(&publish_meta, &committed_meta).expect("rename publish.meta to part.1.meta");
let post_rename_stamp =
multipart_source_state::FileStamp::from_path(&committed_meta).expect("post-rename FileStamp::from_path");
assert_eq!(
pre_rename_stamp, post_rename_stamp,
"FileStamp::from_stat before rename must match FileStamp::from_path after rename"
);
}
#[test]
fn read_metadata_only_from_reader_handles_short_reads_large_envelopes_and_errors() {
struct ScriptedShortReader<'a> {
+2 -1
View File
@@ -1248,13 +1248,14 @@ impl LocalDisk {
}
#[cfg(test)]
run_owned_file_before_open(&backup_path);
if let Err(err) = os::stage_inline_rollback_backup_with_commit_guard_std(
if let Err(err) = os::stage_inline_rollback_backup_in_dir_with_commit_guard_std(
&dst_file_path_owned,
&backup_parent,
&backup_path,
old_file,
sync_recovery_protocol,
!should_fail_local_inline_rollback_hardlink(&dst_file_path_owned),
has_old_data_dir.is_some(),
&guard,
) {
drop(prepared_metadata_source);
@@ -261,8 +261,8 @@ pub(super) fn read_optional_in_pinned(
Err(error) => Err(error.into()),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct FileStamp {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct FileStamp {
len: u64,
modified: Option<std::time::SystemTime>,
#[cfg(unix)]
@@ -270,7 +270,7 @@ struct FileStamp {
}
impl FileStamp {
fn from_path(path: &Path) -> Option<Self> {
pub(super) fn from_path(path: &Path) -> Option<Self> {
let meta = std::fs::symlink_metadata(path).ok()?;
Some(Self {
len: meta.len(),
@@ -282,6 +282,22 @@ impl FileStamp {
},
})
}
#[cfg(unix)]
pub(super) fn from_stat(st: &rustix::fs::Stat) -> Option<Self> {
fn try_u64<T: TryInto<u64>>(v: T) -> Option<u64> {
v.try_into().ok()
}
fn try_u32<T: TryInto<u32>>(v: T) -> Option<u32> {
v.try_into().ok()
}
let len = try_u64(st.st_size)?;
let sec = try_u64(st.st_mtime)?;
let nsec = try_u32(st.st_mtime_nsec).filter(|&n| n < 1_000_000_000)?;
let ino = try_u64(st.st_ino)?;
let modified = Some(std::time::UNIX_EPOCH.checked_add(std::time::Duration::new(sec, nsec))?);
Some(Self { len, modified, ino })
}
}
#[derive(Clone)]
@@ -371,7 +387,19 @@ pub(super) fn begin_active_multipart_part_transaction(source: &Path, part_number
});
}
pub(super) fn record_active_multipart_part_committed(source: &Path, part: rustfs_filemeta::ObjectPartInfo) {
pub(super) fn record_active_multipart_part_committed(
source: &Path,
part: rustfs_filemeta::ObjectPartInfo,
precomputed_stamp: Option<FileStamp>,
) {
if let Some(part_stamp) = precomputed_stamp {
ACTIVE_MULTIPART_SOURCE_HEADS.with_get_mut(source, |entry| {
if entry.fi.data_dir.is_some_and(|dir| !dir.is_nil()) {
entry.parts.insert(part.number, (part_stamp, part));
}
});
return;
}
let Some(data_dir) = ACTIVE_MULTIPART_SOURCE_HEADS
.with_get(source, |entry| entry.fi.data_dir)
.flatten()
@@ -317,6 +317,16 @@ impl Drop for MultipartCommitStaging {
}
}
#[derive(Clone)]
pub(super) struct UploadLockHandle(Arc<UploadEntry>);
impl UploadLockHandle {
#[cfg(test)]
pub(super) fn ptr_eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl LocalDisk {
pub(crate) fn has_clean_active_multipart_source(&self, upload_or_part_path: &str, part_path: bool) -> bool {
let root = upload_scope_root(upload_or_part_path, part_path);
@@ -379,27 +389,37 @@ impl LocalDisk {
}))
}
pub(super) async fn multipart_source_owner(
pub(super) fn lookup_multipart_upload_lock(
&self,
volume: &str,
path: &str,
part_path: bool,
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Result<Option<Arc<dyn Send + Sync>>> {
) -> Result<Option<UploadLockHandle>> {
reject_noncanonical_scope(&self.root, self.io_root(), volume, path)?;
if volume != RUSTFS_META_MULTIPART_BUCKET {
return Ok(owner);
return Ok(None);
}
let root = upload_scope_root(path, part_path);
// Only the internal relative scope is folded: the configured disk root
// keeps its physical spelling. Case-sensitive filesystems may serialize
// two case-only upload IDs; insensitive filesystems must share one lock.
let key = self.root.join(RUSTFS_META_MULTIPART_BUCKET).join(root.to_ascii_lowercase());
let entry = UPLOAD_LOCKS.entry(key);
Ok(Some(UploadLockHandle(UPLOAD_LOCKS.entry(key))))
}
pub(super) async fn acquire_multipart_source_owner_with_handle(
handle: Option<&UploadLockHandle>,
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Option<Arc<dyn Send + Sync>> {
let Some(handle) = handle else {
return owner;
};
let entry = Arc::clone(&handle.0);
// Lock ordering: usage_owner -> UploadEntry.lock -> NamespaceMutationLock.
// Upload scope precedes the private attempt, object metadata and
// publication leases. Independent parts retain shared ownership.
Ok(Some(if exclusive {
Some(if exclusive {
Arc::new(UploadOwner {
_guard: Arc::clone(&entry.lock).write_owned().await,
_entry: entry,
@@ -411,7 +431,19 @@ impl LocalDisk {
_entry: entry,
_owner: owner,
})
}))
})
}
pub(super) async fn multipart_source_owner(
&self,
volume: &str,
path: &str,
part_path: bool,
exclusive: bool,
owner: Option<Arc<dyn Send + Sync>>,
) -> Result<Option<Arc<dyn Send + Sync>>> {
let handle = self.lookup_multipart_upload_lock(volume, path, part_path)?;
Ok(Self::acquire_multipart_source_owner_with_handle(handle.as_ref(), exclusive, owner).await)
}
pub(super) async fn prepare_multipart_commit_staging(
+1 -1
View File
@@ -5175,7 +5175,7 @@ pub(crate) fn read_destination_file_with_commit_guard(
}
}
#[cfg(target_os = "linux")]
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn stage_inline_rollback_backup_with_commit_guard_std(
dst_file_path: &Path,
backup_parent: &Path,
+107 -11
View File
@@ -432,18 +432,24 @@ async fn open_disk_reader(
// request the entire part span in one call. Over-cap reads (e.g. a huge
// single-part object, rustfs#5123) take the bounded streaming path below.
let use_mmap_copy = if use_mmap_read && disk.is_local() {
let mmap_read_cap = object_mmap_read_max_length();
let within_cap = length <= mmap_read_cap;
if !within_cap {
rustfs_io_metrics::record_zero_copy_fallback("read_length_exceeds_cap");
debug!(
length,
mmap_read_cap,
path = %path,
"zero_copy_read_skipped_over_cap"
);
let inflight_budget = crate::set_disk::read_budget::object_mmap_read_max_inflight_bytes();
if inflight_budget == 0 || length > inflight_budget {
rustfs_io_metrics::record_zero_copy_fallback("in_flight_read_budget_exceeded");
false
} else {
let mmap_read_cap = object_mmap_read_max_length();
let within_cap = length <= mmap_read_cap;
if !within_cap {
rustfs_io_metrics::record_zero_copy_fallback("read_length_exceeds_cap");
debug!(
length,
mmap_read_cap,
path = %path,
"zero_copy_read_skipped_over_cap"
);
}
within_cap
}
within_cap
} else {
false
};
@@ -524,6 +530,7 @@ async fn open_disk_reader(
let reader = instrument_raw_shard_reader(reader, disk.is_local());
Ok(wrap_first_read_metrics(reader, metrics_path))
}
Err(stream_err) if crate::set_disk::read_budget::is_in_flight_read_budget_exhausted(&err) => Err(stream_err),
Err(_) => Err(err),
};
}
@@ -1848,6 +1855,95 @@ mod tests {
.await;
}
#[tokio::test]
async fn open_disk_reader_preserves_disk_errors_and_streams_under_inflight_budget() {
use crate::set_disk::read_budget::global_in_flight_read_budget;
use rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES;
use tokio::io::AsyncReadExt;
let (disk, _dir) = local_test_disk().await;
let payload = vec![0x5Au8; 2048];
disk.make_volume("test-bucket").await.expect("volume should be created");
disk.write_all("test-bucket", "obj/part.1", Bytes::from(payload.clone()))
.await
.expect("shard file should be written");
// 1. Exhausted non-zero budget: existing shard falls back to streaming,
// missing shard preserves DiskError::FileNotFound instead of WouldBlock.
temp_env::async_with_vars([(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("2048"))], async {
let held_permit = global_in_flight_read_budget()
.try_reserve(2048)
.expect("initial permit should reserve full test budget");
let existing = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("existing shard must fall back to streaming when budget is exhausted");
assert!(
matches!(existing, ShardReader::Stream(_)),
"budget exhaustion must route open_disk_reader to ShardReader::Stream"
);
let mut existing = existing;
let mut streamed = Vec::new();
existing
.read_to_end(&mut streamed)
.await
.expect("streamed fallback read should succeed");
assert_eq!(streamed, payload);
let missing_err = open_disk_reader(&disk, "test-bucket", "obj/missing.1", 0, payload.len(), true, None)
.await
.err()
.expect("missing shard must return an error");
assert!(
matches!(missing_err, DiskError::FileNotFound),
"budget exhaustion must preserve DiskError::FileNotFound on missing shard, got: {missing_err:?}"
);
// Releasing the held permit restores the in-memory fast path and reclaims on drop.
drop(held_permit);
let fast = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("read under reclaimed budget should succeed");
assert!(
matches!(fast, ShardReader::InMemory(_)),
"read after permit reclamation must resume InMemory fast path"
);
assert_eq!(global_in_flight_read_budget().in_flight_bytes(), payload.len());
drop(fast);
assert_eq!(global_in_flight_read_budget().in_flight_bytes(), 0);
})
.await;
// 2. Zero budget disables mmap-copy upfront: existing shard streams and
// missing shard preserves DiskError::FileNotFound.
temp_env::async_with_vars([(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("0"))], async {
let existing = open_disk_reader(&disk, "test-bucket", "obj/part.1", 0, payload.len(), true, None)
.await
.expect("existing shard with zero budget must stream");
assert!(
matches!(existing, ShardReader::Stream(_)),
"zero budget must route existing shard to ShardReader::Stream"
);
let mut existing = existing;
let mut streamed = Vec::new();
existing
.read_to_end(&mut streamed)
.await
.expect("streamed read with zero budget should succeed");
assert_eq!(streamed, payload);
let missing_err = open_disk_reader(&disk, "test-bucket", "obj/missing.1", 0, payload.len(), true, None)
.await
.err()
.expect("missing shard with zero budget must return an error");
assert!(
matches!(missing_err, DiskError::FileNotFound),
"zero budget must preserve DiskError::FileNotFound on missing shard, got: {missing_err:?}"
);
})
.await;
}
#[tokio::test]
async fn disk_bitrot_reader_and_writer_preserve_full_shard_body() {
let (disk, _dir) = local_test_disk().await;
+389 -70
View File
@@ -1307,12 +1307,21 @@ pub(in crate::set_disk) fn record_bitrot_reader_setup_strategy(
}
}
#[cfg(unix)]
enum BatchPreadOutcome {
Selected(Box<BitrotReaderSetup>),
BudgetExhausted,
NotEligible,
}
/// When all online shards are local and mmap-read is enabled, materialize
/// shard bytes through `batch_shard_pread` instead of the per-shard
/// `open_disk_reader` path. Demand-bound reads add parity batches only as needed.
/// shard bytes through `batch_shard_pread_with_permits` instead of the
/// per-shard `open_disk_reader` path. Demand-bound reads add parity batches
/// only as needed, and every batch reserves its full in-flight byte budget
/// before allocating buffers.
#[cfg(unix)]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
async fn try_create_bitrot_readers_via_batch_pread_with_outcome(
files: &[FileInfo],
disks: &[Option<DiskStore>],
bucket: &str,
@@ -1328,15 +1337,16 @@ async fn try_create_bitrot_readers_via_batch_pread(
parity_shards: usize,
mode: BitrotReaderSetupMode,
strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
use crate::disk::local::batch_shard_pread;
) -> BatchPreadOutcome {
use crate::disk::local::batch_shard_pread_with_permits;
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
use rustfs_io_metrics::{LocalBatchReadDecision, record_local_batch_read_decision};
use std::io::Cursor;
// Scoped q reads retain the normal source's disk admission and memory
// receipts; the foreground batch worker does not carry resource units.
if frame_size != shard_size && crate::disk::has_resource_io_scope() {
return None;
return BatchPreadOutcome::NotEligible;
}
let prepare_started = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now);
@@ -1347,14 +1357,14 @@ async fn try_create_bitrot_readers_via_batch_pread(
bitrot_encoded_range_with_frame_size(read_offset, read_length, shard_size, frame_size, checksum_algo.clone());
if adj_len > object_mmap_read_max_length() {
record_decision(LocalBatchReadDecision::ReadCapExceeded);
return None;
return BatchPreadOutcome::NotEligible;
}
let mut batch_items: Vec<(usize, std::path::PathBuf, usize, usize)> = Vec::new();
for (idx, disk_op) in disks.iter().enumerate() {
if files.get(idx).is_some_and(|fi| fi.data.is_some()) {
record_decision(LocalBatchReadDecision::InlineData);
return None;
return BatchPreadOutcome::NotEligible;
}
if let Some(disk) = disk_op.as_ref() {
let data_dir = files[idx].data_dir.unwrap_or_default();
@@ -1363,11 +1373,11 @@ async fn try_create_bitrot_readers_via_batch_pread(
Some(Ok(p)) => batch_items.push((idx, p, adj_off, adj_len)),
Some(Err(_)) => {
record_decision(LocalBatchReadDecision::InvalidPath);
return None;
return BatchPreadOutcome::NotEligible;
}
None => {
record_decision(LocalBatchReadDecision::NonLocalShard);
return None;
return BatchPreadOutcome::NotEligible;
}
}
}
@@ -1375,7 +1385,7 @@ async fn try_create_bitrot_readers_via_batch_pread(
if batch_items.is_empty() {
record_decision(LocalBatchReadDecision::NoLocalShards);
return None;
return BatchPreadOutcome::NotEligible;
}
// Legacy lockstep consumes every shard, so retain its coalesced batch for
@@ -1398,22 +1408,38 @@ async fn try_create_bitrot_readers_via_batch_pread(
batch_items.len()
};
let mut pending = batch_items.into_iter();
record_decision(LocalBatchReadDecision::Selected);
let mut selected_recorded = false;
loop {
let mut indices = Vec::with_capacity(batch_size.min(pending.len()));
let requests: Vec<_> = pending
.by_ref()
.take(batch_size)
.map(|(idx, path, offset, length)| {
setup.mark_scheduled(idx);
indices.push(idx);
#[cfg(test)]
disk_call_counters::record(object, disk_call_counters::KIND_DISK_SHARD_OPEN, idx);
(path, offset, length)
})
.collect();
if !requests.is_empty() {
for (idx, result) in indices.into_iter().zip(batch_shard_pread(requests).await) {
let batch_slice: Vec<_> = pending.by_ref().take(batch_size).collect();
if !batch_slice.is_empty() {
let lengths: Vec<usize> = batch_slice.iter().map(|(_, _, _, length)| *length).collect();
let Some(permits) = global_in_flight_read_budget().try_reserve_batch(&lengths) else {
// Drop any shard readers materialized in earlier loop rounds so
// their permits return to the global budget before falling back
// to the streaming path.
drop(setup);
if !selected_recorded {
record_decision(LocalBatchReadDecision::ReadCapExceeded);
}
return BatchPreadOutcome::BudgetExhausted;
};
if !selected_recorded {
record_decision(LocalBatchReadDecision::Selected);
selected_recorded = true;
}
let mut indices = Vec::with_capacity(batch_slice.len());
let requests: Vec<_> = batch_slice
.into_iter()
.zip(permits)
.map(|((idx, path, offset, length), permit)| {
setup.mark_scheduled(idx);
indices.push(idx);
#[cfg(test)]
disk_call_counters::record(object, disk_call_counters::KIND_DISK_SHARD_OPEN, idx);
(path, offset, length, permit)
})
.collect();
for (idx, result) in indices.into_iter().zip(batch_shard_pread_with_permits(requests).await) {
let result = result.map(|bytes| {
Some(BitrotReader::new_with_frame_size(
ShardReader::InMemory(Cursor::new(bytes)),
@@ -1437,11 +1463,20 @@ async fn try_create_bitrot_readers_via_batch_pread(
.saturating_sub(setup.available_shards());
}
Some(setup)
if !selected_recorded {
record_decision(LocalBatchReadDecision::Selected);
}
BatchPreadOutcome::Selected(Box::new(setup))
}
#[cfg(not(unix))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread_unsupported() {
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::UnsupportedPlatform, None);
}
#[cfg(all(test, not(unix)))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
_files: &[FileInfo],
_disks: &[Option<DiskStore>],
@@ -1459,10 +1494,53 @@ async fn try_create_bitrot_readers_via_batch_pread(
_mode: BitrotReaderSetupMode,
_strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
rustfs_io_metrics::record_local_batch_read_decision(rustfs_io_metrics::LocalBatchReadDecision::UnsupportedPlatform, None);
try_create_bitrot_readers_via_batch_pread_unsupported().await;
None
}
#[cfg(all(test, unix))]
#[allow(clippy::too_many_arguments)]
async fn try_create_bitrot_readers_via_batch_pread(
files: &[FileInfo],
disks: &[Option<DiskStore>],
bucket: &str,
object: &str,
part_number: usize,
read_offset: usize,
read_length: usize,
shard_size: usize,
frame_size: usize,
checksum_algo: HashAlgorithm,
skip_verify_bitrot: bool,
data_shards: usize,
parity_shards: usize,
mode: BitrotReaderSetupMode,
strategy: BitrotReaderSetupStrategy,
) -> Option<BitrotReaderSetup> {
match try_create_bitrot_readers_via_batch_pread_with_outcome(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
BatchPreadOutcome::Selected(setup) => Some(*setup),
BatchPreadOutcome::BudgetExhausted | BatchPreadOutcome::NotEligible => None,
}
}
#[allow(dead_code, reason = "compatibility wrapper for the legacy shard geometry")]
#[allow(clippy::too_many_arguments)]
pub(in crate::set_disk) async fn create_bitrot_readers_until_quorum_all_shards(
@@ -1726,48 +1804,67 @@ pub(in crate::set_disk) async fn create_bitrot_readers_until_quorum_with_prefere
} else {
true
};
if batch_read_enabled
&& let Some(mut setup) = try_create_bitrot_readers_via_batch_pread(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo.clone(),
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
record_bitrot_reader_setup_strategy(strategy, mode, attribution);
fill_deferred_bitrot_readers_with_frame_size(
&mut setup,
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
use_mmap_read,
data_shards,
parity_shards,
mode,
);
record_bitrot_reader_setup_fanout(strategy, mode, &setup, attribution);
return setup;
}
let use_mmap_read = if batch_read_enabled {
#[cfg(unix)]
{
match try_create_bitrot_readers_via_batch_pread_with_outcome(
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo.clone(),
skip_verify_bitrot,
data_shards,
parity_shards,
mode,
strategy,
)
.await
{
BatchPreadOutcome::Selected(mut setup) => {
record_bitrot_reader_setup_strategy(strategy, mode, attribution);
fill_deferred_bitrot_readers_with_frame_size(
&mut setup,
files,
disks,
bucket,
object,
part_number,
read_offset,
read_length,
shard_size,
frame_size,
checksum_algo,
skip_verify_bitrot,
use_mmap_read,
data_shards,
parity_shards,
mode,
);
record_bitrot_reader_setup_fanout(strategy, mode, &setup, attribution);
return *setup;
}
BatchPreadOutcome::BudgetExhausted => {
// Fall straight through to the bounded streaming reader path
// instead of re-attempting per-shard in-memory mmap copies.
false
}
BatchPreadOutcome::NotEligible => use_mmap_read,
}
}
#[cfg(not(unix))]
{
try_create_bitrot_readers_via_batch_pread_unsupported().await;
use_mmap_read
}
} else {
use_mmap_read
};
if strategy == BitrotReaderSetupStrategy::AllShards {
return create_bitrot_readers_until_quorum_all_shards_with_frame_size(
@@ -10023,6 +10120,228 @@ mod tests {
assert_eq!(recorder.histogram_sample_count("rustfs_io_get_object_local_batch_prepare_seconds"), 8);
}
#[cfg(unix)]
#[test]
#[serial_test::serial]
fn in_flight_read_budget_falls_back_to_streaming_and_reclaims_on_drop() {
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("in-flight read budget test runtime");
runtime.block_on(temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_LENGTH, Some("65536")),
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("4096")),
(rustfs_config::ENV_INTERNODE_PREWARM, Some("false")),
],
async {
let budget = global_in_flight_read_budget();
assert_eq!(budget.in_flight_bytes(), 0, "budget must start clean");
let bucket = "in-flight-read-budget";
let object = "object";
let (_dirs, disks) = call_counter_local_disks(bucket, 2).await;
let data_dir = Uuid::new_v4();
let payload = vec![0x5a_u8; 4096];
let mut files = vec![FileInfo::new(object, 1, 1); 2];
for (file, disk) in files.iter_mut().zip(&disks) {
file.data_dir = Some(data_dir);
disk.as_ref()
.expect("local disk")
.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from(payload.clone()))
.await
.expect("write shard fixture");
}
// First read consumes the 4096-byte data shard via batch pread
// (parity shard stays deferred), filling the exact 4096-byte budget.
let first = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert!(
matches!(
first.readers[0].as_ref().expect("data shard reader").inner_ref(),
ShardReader::InMemory(_)
),
"first read under budget must keep the batch pread InMemory fast path"
);
assert_eq!(
budget.in_flight_bytes(),
4096,
"unread in-memory shard reader must charge the process-wide budget"
);
// Second concurrent unread read exceeds budget -> must fall back to streaming
// without overshooting the budget and still return intact shard bytes.
let mut second = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert_eq!(budget.in_flight_bytes(), 4096, "exhausted budget must never overshoot");
assert!(
second
.readers
.iter()
.flatten()
.all(|reader| !matches!(reader.inner_ref(), ShardReader::InMemory(_))),
"concurrent read when budget is exhausted must fall back to streaming readers"
);
let mut streamed = vec![0u8; payload.len()];
let read_n = second.readers[0]
.as_mut()
.expect("streaming reader must be present")
.read(&mut streamed)
.await
.expect("fallback streaming reader must serve exact bytes");
assert_eq!(read_n, payload.len());
assert_eq!(streamed, payload);
drop(second);
// Dropping/cancelling the unread first reader must immediately reclaim all bytes.
drop(first);
assert_eq!(
budget.in_flight_bytes(),
0,
"dropping unread readers must immediately release reserved budget"
);
// After reclamation, subsequent reads resume the InMemory batch fast path.
let third = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
payload.len(),
payload.len(),
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert!(
matches!(
third.readers[0].as_ref().expect("data shard reader").inner_ref(),
ShardReader::InMemory(_)
),
"after drop reclamation, batch pread fast path must be re-admitted"
);
assert_eq!(budget.in_flight_bytes(), 4096);
drop(third);
assert_eq!(budget.in_flight_bytes(), 0);
},
));
}
#[cfg(unix)]
#[test]
#[serial_test::serial]
fn zero_in_flight_read_budget_forces_streaming_fallback() {
use crate::set_disk::core::read_budget::global_in_flight_read_budget;
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("zero budget test runtime");
runtime.block_on(temp_env::async_with_vars(
[
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_LENGTH, Some("65536")),
(rustfs_config::ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, Some("0")),
(rustfs_config::ENV_INTERNODE_PREWARM, Some("false")),
],
async {
let budget = global_in_flight_read_budget();
let bucket = "zero-in-flight-budget";
let object = "object";
let (_dirs, disks) = call_counter_local_disks(bucket, 2).await;
let data_dir = Uuid::new_v4();
let mut files = vec![FileInfo::new(object, 1, 1); 2];
for (file, disk) in files.iter_mut().zip(&disks) {
file.data_dir = Some(data_dir);
disk.as_ref()
.expect("local disk")
.write_all(bucket, &format!("{object}/{data_dir}/part.1"), Bytes::from_static(b"abcd"))
.await
.expect("write shard fixture");
}
let setup = create_bitrot_readers_until_quorum_with_preference(
&files,
&disks,
bucket,
object,
1,
0,
4,
4,
HashAlgorithm::None,
false,
true,
1,
1,
BitrotReaderSetupMode::ReadQuorum,
false,
None,
None,
)
.await;
assert_eq!(budget.in_flight_bytes(), 0);
assert!(
setup
.readers
.iter()
.flatten()
.all(|reader| !matches!(reader.inner_ref(), ShardReader::InMemory(_))),
"zero in-flight budget must force streaming readers"
);
},
));
}
async fn reopen_local_disk(dir: &TempDir) -> DiskStore {
let endpoint =
Endpoint::try_from(dir.path().to_str().expect("tempdir path should be utf8")).expect("endpoint should parse");
+1
View File
@@ -21,3 +21,4 @@ pub(crate) mod io_primitives;
pub(in crate::set_disk) mod metadata_quorum;
pub(in crate::set_disk) mod metadata_read;
pub(in crate::set_disk) mod multipart_source;
pub(crate) mod read_budget;
@@ -0,0 +1,380 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Process-wide RAII byte budget for buffered local shard reads.
//!
//! Local batch positioned reads (`batch_shard_pread`) and mmap-copy shard reads
//! materialize full shard ranges in memory before returning a `ShardReader`.
//! Without a process-wide ceiling, concurrent unread or slow-consumed
//! `GetObject` responses can pin unbounded heap memory across requests.
//!
//! Callers reserve bytes *before* allocating shard buffers and bind the
//! resulting [`ReadMemoryPermit`] to the returned [`Bytes`] via
//! [`Bytes::from_owner`]. Dropping or cancelling the reader (and its last slice)
//! frees the buffer first and immediately returns the reserved bytes to the
//! budget. When the budget cannot admit a request, callers fall back to the
//! streaming reader path.
use bytes::Bytes;
use rustfs_config::{DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};
/// Process-wide in-flight byte budget shared by buffered local shard reads.
static GLOBAL_IN_FLIGHT_READ_BUDGET: OnceLock<Arc<InFlightReadBudget>> = OnceLock::new();
const IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG: &str = "in-flight read memory budget exhausted";
/// Sentinel error returned by `LocalDisk::read_file_mmap_copy_with_metrics`
/// when the process-wide in-flight read memory budget cannot admit a read.
pub(crate) fn in_flight_read_budget_exhausted_error() -> crate::disk::error::DiskError {
crate::disk::error::DiskError::Io(std::io::Error::new(std::io::ErrorKind::WouldBlock, IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG))
}
/// Returns `true` when `err` is the in-flight read memory budget exhaustion
/// sentinel produced by [`in_flight_read_budget_exhausted_error`].
pub(crate) fn is_in_flight_read_budget_exhausted(err: &crate::disk::error::DiskError) -> bool {
matches!(
err,
crate::disk::error::DiskError::Io(io_err)
if io_err.kind() == std::io::ErrorKind::WouldBlock
&& io_err.to_string() == IN_FLIGHT_READ_BUDGET_EXHAUSTED_MSG
)
}
/// Configured process-wide in-flight read byte limit.
///
/// Cached via `OnceLock` in non-test builds to keep the hot read path free of
/// process-global environment locks; read directly in test builds so `temp_env`
/// overrides take effect immediately.
pub(crate) fn object_mmap_read_max_inflight_bytes() -> usize {
#[cfg(test)]
{
rustfs_utils::get_env_usize(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES)
}
#[cfg(not(test))]
{
static CACHED: OnceLock<usize> = OnceLock::new();
*CACHED.get_or_init(|| {
rustfs_utils::get_env_usize(ENV_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES, DEFAULT_OBJECT_MMAP_READ_MAX_INFLIGHT_BYTES)
})
}
}
/// Returns the process-wide in-flight read memory budget.
pub(crate) fn global_in_flight_read_budget() -> &'static Arc<InFlightReadBudget> {
GLOBAL_IN_FLIGHT_READ_BUDGET.get_or_init(|| Arc::new(InFlightReadBudget::new_global()))
}
/// Lock-free byte budget tracking in-flight buffered shard allocations.
#[derive(Debug)]
pub(crate) struct InFlightReadBudget {
in_flight_bytes: AtomicUsize,
limit_override: Option<usize>,
}
impl InFlightReadBudget {
fn new_global() -> Self {
Self {
in_flight_bytes: AtomicUsize::new(0),
limit_override: None,
}
}
/// Create an isolated budget with an explicit fixed limit (used by unit tests).
#[cfg(test)]
pub(crate) fn with_limit(limit: usize) -> Arc<Self> {
Arc::new(Self {
in_flight_bytes: AtomicUsize::new(0),
limit_override: Some(limit),
})
}
/// Current configured byte ceiling.
pub(crate) fn limit(&self) -> usize {
self.limit_override.unwrap_or_else(object_mmap_read_max_inflight_bytes)
}
/// Currently reserved in-flight bytes.
#[cfg(test)]
pub(crate) fn in_flight_bytes(&self) -> usize {
self.in_flight_bytes.load(Ordering::Acquire)
}
/// Attempt to reserve `bytes` from this budget without blocking.
///
/// Returns `None` when the configured limit is `0` (buffered reads disabled)
/// or when admitting `bytes` would overflow or exceed the current limit.
pub(crate) fn try_reserve(self: &Arc<Self>, bytes: usize) -> Option<ReadMemoryPermit> {
let limit = self.limit();
if limit == 0 || bytes > limit {
return None;
}
if bytes == 0 {
return Some(ReadMemoryPermit {
budget: Arc::clone(self),
bytes: 0,
});
}
let mut current = self.in_flight_bytes.load(Ordering::Acquire);
loop {
let next = current.checked_add(bytes)?;
if next > limit {
return None;
}
match self
.in_flight_bytes
.compare_exchange_weak(current, next, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => {
return Some(ReadMemoryPermit {
budget: Arc::clone(self),
bytes,
});
}
Err(observed) => current = observed,
}
}
}
/// Atomically reserve every shard length in `sizes` as an all-or-nothing
/// batch, returning one independently droppable permit per entry.
pub(crate) fn try_reserve_batch(self: &Arc<Self>, sizes: &[usize]) -> Option<Vec<ReadMemoryPermit>> {
let total = sizes.iter().try_fold(0usize, |acc, &size| acc.checked_add(size))?;
let mut batch_permit = self.try_reserve(total)?;
let mut permits = Vec::with_capacity(sizes.len());
for &size in sizes {
permits.push(batch_permit.split(size)?);
}
debug_assert_eq!(batch_permit.bytes, 0, "batch permit must be fully partitioned");
Some(permits)
}
}
/// RAII reservation of in-flight shard read bytes.
///
/// Dropping this permit immediately returns its reserved bytes to the owning
/// [`InFlightReadBudget`].
#[derive(Debug)]
pub(crate) struct ReadMemoryPermit {
budget: Arc<InFlightReadBudget>,
bytes: usize,
}
impl ReadMemoryPermit {
/// Bytes reserved by this permit.
#[cfg(test)]
pub(crate) fn bytes(&self) -> usize {
self.bytes
}
/// Carve `amount` bytes off this permit into a child permit while conserving
/// the total reserved byte count across parent and child.
fn split(&mut self, amount: usize) -> Option<Self> {
let remaining = self.bytes.checked_sub(amount)?;
self.bytes = remaining;
Some(Self {
budget: Arc::clone(&self.budget),
bytes: amount,
})
}
/// Bind this permit to an owned `Vec<u8>` buffer via [`Bytes::from_owner`].
///
/// If the buffer is empty, the permit is released immediately and an empty
/// `Bytes` is returned. Otherwise the permit remains held until the last
/// `Bytes` slice referencing the allocation is dropped, freeing the backing
/// buffer before refunding the budget.
pub(crate) fn wrap_vec(self, data: Vec<u8>) -> Bytes {
if data.is_empty() {
drop(data);
drop(self);
return Bytes::new();
}
Bytes::from_owner(BudgetedOwner { data, _permit: self })
}
/// Bind this permit to an already-constructed [`Bytes`] via
/// [`Bytes::from_owner`].
pub(crate) fn wrap_bytes(self, data: Bytes) -> Bytes {
if data.is_empty() {
drop(data);
drop(self);
return Bytes::new();
}
Bytes::from_owner(BudgetedOwner { data, _permit: self })
}
}
impl Drop for ReadMemoryPermit {
fn drop(&mut self) {
if self.bytes > 0 {
let prev = self.budget.in_flight_bytes.fetch_sub(self.bytes, Ordering::AcqRel);
debug_assert!(prev >= self.bytes, "in-flight read budget underflow");
}
}
}
/// Owner wrapper passed to [`Bytes::from_owner`].
///
/// Field declaration order is significant: `data` is dropped first so heap
/// memory is released before `_permit` refunds the global budget.
struct BudgetedOwner<T> {
data: T,
_permit: ReadMemoryPermit,
}
impl<T: AsRef<[u8]>> AsRef<[u8]> for BudgetedOwner<T> {
fn as_ref(&self) -> &[u8] {
self.data.as_ref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Barrier;
#[test]
fn budget_reserves_enforces_cap_and_reclaims_on_drop() {
let budget = InFlightReadBudget::with_limit(1024);
assert_eq!(budget.in_flight_bytes(), 0);
let p1 = budget.try_reserve(600).expect("first reservation under cap");
assert_eq!(p1.bytes(), 600);
assert_eq!(budget.in_flight_bytes(), 600);
assert!(
budget.try_reserve(500).is_none(),
"reservation exceeding remaining capacity must fail without overshoot"
);
assert_eq!(budget.in_flight_bytes(), 600);
let p2 = budget.try_reserve(424).expect("exact remaining capacity must succeed");
assert_eq!(budget.in_flight_bytes(), 1024);
assert!(budget.try_reserve(1).is_none());
drop(p1);
assert_eq!(budget.in_flight_bytes(), 424);
drop(p2);
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn zero_limit_disables_all_reservations_including_empty() {
let budget = InFlightReadBudget::with_limit(0);
assert!(budget.try_reserve(0).is_none());
assert!(budget.try_reserve(1).is_none());
assert!(budget.try_reserve_batch(&[0, 0]).is_none());
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn batch_reservation_is_atomic_and_splits_independently() {
let budget = InFlightReadBudget::with_limit(100);
assert!(
budget.try_reserve_batch(&[40, 40, 40]).is_none(),
"all-or-nothing batch over limit must leave budget untouched"
);
assert_eq!(budget.in_flight_bytes(), 0);
assert!(
budget.try_reserve_batch(&[usize::MAX, 1]).is_none(),
"overflowing batch sum must be rejected safely"
);
assert_eq!(budget.in_flight_bytes(), 0);
let mut permits = budget.try_reserve_batch(&[30, 50, 20]).expect("exact batch fits");
assert_eq!(budget.in_flight_bytes(), 100);
assert_eq!(permits.len(), 3);
let last = permits.pop().expect("third permit");
drop(last);
assert_eq!(budget.in_flight_bytes(), 80);
drop(permits);
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn bytes_owner_holds_permit_across_slices_and_releases_on_last_drop() {
let budget = InFlightReadBudget::with_limit(64);
let permit = budget.try_reserve(64).expect("reserve 64 bytes");
let bytes = permit.wrap_vec(vec![0xAB; 64]);
assert_eq!(budget.in_flight_bytes(), 64);
let slice = bytes.slice(8..16);
drop(bytes);
assert_eq!(
budget.in_flight_bytes(),
64,
"permit must stay held while a non-empty slice pins the backing allocation"
);
assert_eq!(slice.as_ref(), &[0xAB; 8]);
drop(slice);
assert_eq!(
budget.in_flight_bytes(),
0,
"dropping the final slice must release the full reservation immediately"
);
}
#[test]
fn empty_buffer_releases_permit_immediately() {
let budget = InFlightReadBudget::with_limit(64);
let permit = budget.try_reserve(16).expect("reserve");
let bytes = permit.wrap_vec(Vec::new());
assert!(bytes.is_empty());
assert_eq!(budget.in_flight_bytes(), 0);
}
#[test]
fn concurrent_reservations_never_exceed_limit_or_leak() {
const LIMIT: usize = 4096;
const THREADS: usize = 8;
const CHUNK: usize = 256;
let budget = InFlightReadBudget::with_limit(LIMIT);
let barrier = Arc::new(Barrier::new(THREADS));
let mut handles = Vec::with_capacity(THREADS);
for _ in 0..THREADS {
let budget = Arc::clone(&budget);
let barrier = Arc::clone(&barrier);
handles.push(std::thread::spawn(move || {
barrier.wait();
let mut held = Vec::new();
for _ in 0..200 {
if let Some(permit) = budget.try_reserve(CHUNK) {
assert!(
budget.in_flight_bytes() <= LIMIT,
"in-flight bytes must never overshoot the configured limit"
);
held.push(permit.wrap_vec(vec![1u8; CHUNK]));
} else {
held.pop();
}
}
drop(held);
}));
}
for handle in handles {
handle.join().expect("worker thread must not panic");
}
assert_eq!(budget.in_flight_bytes(), 0, "all reservations must be reclaimed");
}
}
+1
View File
@@ -917,6 +917,7 @@ mod core;
pub(crate) use core::io_primitives::disk_call_counters;
#[cfg(test)]
pub(crate) use core::io_primitives::{ENV_RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE, rename_fanout_barrier};
pub(crate) use core::read_budget;
mod ctx;
mod metadata;
mod ops;
+262 -5
View File
@@ -580,6 +580,67 @@ impl Drop for CappedMultipartStagingGuard {
}
}
/// Interim local pre-commit RAII cleanup owner for staged multipart part
/// artifacts under `.rustfs.sys/tmp/<tmp_part>`.
///
/// Armed right before opening part writers and transferred/disarmed once commit
/// takes ownership. If a `put_object_part` future is dropped or cancelled
/// before commit handoff (for example on client disconnect), `Drop` runs after
/// the inner future's writers have already dropped (LIFO order) and schedules
/// prompt cleanup of `.rustfs.sys/tmp/<tmp_part>` instead of leaving orphans
/// until the 24h stale-tmp sweep.
struct PreCommitPartStagingCleanupGuard {
state: Option<(SetDisks, String)>,
}
impl PreCommitPartStagingCleanupGuard {
fn disarmed() -> Self {
Self { state: None }
}
fn arm(&mut self, set: SetDisks, tmp_part: String) {
self.state = Some((set, tmp_part));
}
fn disarm(&mut self) {
self.state = None;
}
fn take_for_transfer(&mut self) -> Option<(SetDisks, String)> {
self.state.take()
}
fn armed_target(&self) -> Option<(&SetDisks, &str)> {
self.state.as_ref().map(|(set, tmp)| (set, tmp.as_str()))
}
}
impl Drop for PreCommitPartStagingCleanupGuard {
fn drop(&mut self) {
let Some((set, tmp_part)) = self.state.take() else {
return;
};
if let Ok(handle) = tokio::runtime::Handle::try_current() {
handle.spawn(async move {
// Yield once so any just-dropped local file writer handles finish
// unwinding before recursive staging deletion runs.
tokio::task::yield_now().await;
if let Err(err) = set.delete_all(RUSTFS_META_TMP_BUCKET, &tmp_part).await {
warn!(
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "drop_cleanup_failed",
tmp_part = %tmp_part,
error = ?err,
"Set disk multipart staging drop cleanup failed"
);
}
});
}
}
}
fn capped_multipart_staging_semaphore(upload_id_path: &str) -> Arc<tokio::sync::Semaphore> {
CAPPED_MULTIPART_STAGING
.get_or_init(|| Mutex::new(HashMap::new()))
@@ -3383,6 +3444,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
let mut commit_owns_cleanup = false;
// Declared before the inner async block so LIFO drop order closes all
// opened part writers first before `Drop` schedules tmp reclamation.
let mut staging_cleanup = PreCommitPartStagingCleanupGuard::disarmed();
let result: Result<PartInfo> = async {
let erasure =
Arc::new(coding::Erasure::try_new(fi.erasure.data_blocks, fi.erasure.parity_blocks, fi.erasure.block_size)
@@ -3397,6 +3461,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
.unwrap_or_else(|| erasure.shard_size());
let writer_setup_stage_start = rustfs_io_metrics::put_stage_metrics_enabled().then(Instant::now);
staging_cleanup.arm(self.clone(), tmp_part.clone());
let (mut writers, errors) = create_part_writers(
&shuffle_disks,
&tmp_part_path,
@@ -3635,6 +3700,21 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
let commit_opts = opts.clone();
let commit_staged_quota_reservation = staged_quota_reservation.take();
commit_owns_cleanup = true;
// Transfer pre-commit cleanup ownership exactly once at commit handoff:
// - Detached commit runs to completion and owns tmp cleanup exclusively.
// - Inline commit (`!detach_commit_owner`) retains the guard only until
// `rename_part` begins so pre-rename cancellation still cleans tmp
// while post-rename/committed artifacts can never be touched.
let mut commit_staging_cleanup = if detach_commit_owner {
staging_cleanup.disarm();
PreCommitPartStagingCleanupGuard::disarmed()
} else {
let mut transferred = PreCommitPartStagingCleanupGuard::disarmed();
if let Some((set, tmp)) = staging_cleanup.take_for_transfer() {
transferred.arm(set, tmp);
}
transferred
};
// The body is already staged. Keep every commit guard through the
// prepare, publish, settlement/rollback and temporary cleanup I/O,
// even when the HTTP request stops awaiting this task.
@@ -3743,6 +3823,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
achieved: 0,
});
}
// Disarm before rename_part so a Drop guard can never race
// with rename or touch committed multipart staging.
commit_staging_cleanup.disarm();
let rename_started = rustfs_io_metrics::put_stage_timer();
let rename_result = commit_set
.rename_part(
@@ -3801,6 +3884,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
"failed to clean multipart commit staging"
);
}
// Disarm only after inline error cleanup completes so dropping
// mid-cleanup still triggers Drop-backed reclamation.
commit_staging_cleanup.disarm();
result
};
if detach_commit_owner {
@@ -3813,11 +3899,21 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
}
.await;
if !commit_owns_cleanup
&& result.is_err()
&& let Err(err) = self.delete_all(RUSTFS_META_TMP_BUCKET, &tmp_part).await
{
warn!(tmp_part = %tmp_part, error = ?err, "failed to cleanup multipart temporary data");
if !commit_owns_cleanup && result.is_err() {
if let Some((set, tmp)) = staging_cleanup.armed_target()
&& let Err(err) = set.delete_all(RUSTFS_META_TMP_BUCKET, tmp).await
{
warn!(
event = EVENT_SET_DISK_MULTIPART,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_SET_DISK,
result = "cleanup_failed",
tmp_part = %tmp,
error = ?err,
"failed to cleanup multipart temporary data"
);
}
staging_cleanup.disarm();
}
result
@@ -9959,6 +10055,167 @@ mod tests {
);
}
#[tokio::test]
async fn cancelled_put_object_part_mid_upload_cleans_tmp_staging_via_drop_guard() {
let (temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cancel-mid-upload-bucket";
let object = "object";
make_bucket_on_all(&disk_stores, bucket).await;
let upload = set_disks
.new_multipart_upload(bucket, object, &ObjectOptions::default())
.await
.expect("multipart upload should be created");
// Exceed the 1 MiB erasure block size so the streaming encoder writes
// the first full block to staged tmp shard files before stalling on the
// remaining body bytes.
let declared_size = 2 * 1024 * 1024;
let stalled_entered = Arc::new(tokio::sync::Notify::new());
let stalled_entered_clone = Arc::clone(&stalled_entered);
let stream = futures::stream::unfold(0u8, move |step| {
let stalled_entered = Arc::clone(&stalled_entered_clone);
async move {
match step {
0 => Some((Ok::<Bytes, std::io::Error>(Bytes::from(vec![0x33; 1024 * 1024])), 1)),
_ => {
stalled_entered.notify_one();
std::future::pending::<()>().await;
None
}
}
}
});
let input = tokio_util::io::StreamReader::new(Box::pin(stream));
let mut reader = PutObjReader::new(
HashReader::from_stream(input, declared_size, declared_size, None, None, false)
.expect("hash reader should be constructed"),
);
let put_store = set_disks.clone();
let put_upload_id = upload.upload_id.clone();
let put = tokio::spawn(async move {
put_store
.put_object_part(bucket, object, &put_upload_id, 1, &mut reader, &ObjectOptions::default())
.await
});
tokio::time::timeout(Duration::from_secs(10), stalled_entered.notified())
.await
.expect("upload should open part writers and stall mid-stream");
tokio::time::timeout(Duration::from_secs(10), async {
while non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("in-flight upload must have created staged tmp artifacts before cancellation");
put.abort();
assert!(
put.await
.expect_err("aborted put_object_part task should be cancelled")
.is_cancelled()
);
tokio::time::timeout(Duration::from_secs(10), async {
while !non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("pre-commit Drop guard must promptly reclaim staged tmp artifacts on cancellation");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn cancelled_put_object_part_before_commit_cleans_tmp_and_committed_part_survives() {
use tokio::io::AsyncReadExt as _;
let (temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
let bucket = "multipart-cancel-precommit-and-committed-bucket";
let object = "object";
make_bucket_on_all(&disk_stores, bucket).await;
let upload = set_disks
.new_multipart_upload(bucket, object, &ObjectOptions::default())
.await
.expect("multipart upload should be created");
// 1. Cancel after full encode/writer-close but BEFORE commit_owns_cleanup handoff.
let precommit_barrier = MultipartCommitBarrier::install(bucket, object, MultipartCommitPause::PutPartBeforeLockAcquire);
let put_store = set_disks.clone();
let put_upload_id = upload.upload_id.clone();
let cancelled_put = tokio::spawn(async move {
let mut reader = PutObjReader::from_vec(vec![0x61; 8192]);
put_store
.put_object_part(bucket, object, &put_upload_id, 1, &mut reader, &ObjectOptions::default())
.await
});
precommit_barrier.wait_until_paused().await;
assert!(
!non_trash_tmp_entries(&temp_dirs).await.is_empty(),
"staged tmp part must exist while paused before commit lock"
);
cancelled_put.abort();
assert!(
cancelled_put
.await
.expect_err("cancelled pre-commit put should be aborted")
.is_cancelled()
);
drop(precommit_barrier);
tokio::time::timeout(Duration::from_secs(10), async {
while !non_trash_tmp_entries(&temp_dirs).await.is_empty() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("Drop guard must reclaim tmp staging cancelled before commit lock");
// 2. Upload part 1 to completion and verify Drop guard does NOT delete committed data.
let payload = vec![0x77; 8192];
let mut reader = PutObjReader::from_vec(payload.clone());
let part = set_disks
.put_object_part(bucket, object, &upload.upload_id, 1, &mut reader, &ObjectOptions::default())
.await
.expect("committed part upload should succeed");
assert!(
non_trash_tmp_entries(&temp_dirs).await.is_empty(),
"successful commit must leave no tmp entries"
);
set_disks
.clone()
.complete_multipart_upload(
bucket,
object,
&upload.upload_id,
vec![CompletePart {
part_num: part.part_num,
etag: part.etag,
..Default::default()
}],
&ObjectOptions::default(),
)
.await
.expect("completing multipart upload with committed part must succeed");
let mut object_reader = set_disks
.get_object_reader(bucket, object, None, HeaderMap::new(), &ObjectOptions::default())
.await
.expect("completed object must remain readable");
let mut restored = Vec::new();
object_reader
.stream
.read_to_end(&mut restored)
.await
.expect("completed object must read intact");
assert_eq!(restored, payload, "Drop guard must never delete committed part data");
}
#[tokio::test]
async fn capped_staging_queue_does_not_poll_the_part_reader() {
use futures::StreamExt;
+9 -3
View File
@@ -157,8 +157,12 @@ With OTLP → Collector → Prometheus, the time from a failure to an alert also
| Variable | Default | Description |
|-------------------------------------------------|--------------|-------------------------------------------------------------|
| `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` | `2147483648` | Byte budget (2 GiB), applied to rolled logs and to compressed archives separately; `0` = no budget. See [Disk usage bound](#disk-usage-bound) |
| `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` | `2147483648` | Byte budget (2 GiB) shared across rolled logs and compressed archives when `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` is unset; `0` = no budget. See [Disk usage bound](#disk-usage-bound) |
| `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` | unset | Optional dedicated byte budget for compressed archives (`.gz`/`.zst`). Unset = share remaining `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` after rolled logs; `0` = unlimited archive bytes (retention days still apply) |
| `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES` | unset | Unset or unparsable: the active file rolls at 256 MiB, or at a quarter of the byte budget when that is smaller (at least 1 MiB). A value: the active file rolls at that size and the cleaner also processes rolled files above it. `0` = no size roll |
| `RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS` | `32` | Maximum rolled files compressed per cleanup pass (`0` = unlimited); over-budget files beyond this cap are deleted directly without compression |
| `RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC` | `10000` | Global file-sink event rate limit (events/sec); `0` disables sink-side rate limiting |
| `RUSTFS_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC` | unset | Per-callsite file-sink event rate limit (events/sec) so one noisy site cannot starve others; unset = `(sink_max / 4).max(1)`, `0` = disabled |
| `RUSTFS_OBS_LOG_COMPRESS_OLD_FILES` | `true` | Compress files before deleting |
| `RUSTFS_OBS_LOG_GZIP_COMPRESSION_LEVEL` | `6` | Gzip level `1` (fastest) – `9` (best) |
| `RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM` | `zstd` | Compression codec: `zstd` or `gzip` |
@@ -176,9 +180,9 @@ With OTLP → Collector → Prometheus, the time from a failure to an alert also
### Disk usage bound
With the defaults the log directory holds at most the byte budget of rolled logs, the same budget of compressed archives, and one active file of up to 256 MiB. The active file is rolled by size as well as by time, and the cleaner runs a pass after every roll in addition to its interval, so the budget is enforced when a file is rolled. While the rolled logs exceed the budget the cleaner processes the oldest ones, as many as the budget requires, even if they are younger than `RUSTFS_OBS_LOG_MIN_FILE_AGE_SECONDS`; `RUSTFS_OBS_LOG_KEEP_FILES` still applies only to files past that age.
With the defaults the log directory holds at most the shared `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES` budget across rolled logs and compressed archives combined (or independent rolled and archive budgets when `RUSTFS_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES` is set), plus one active file of up to 256 MiB. The active file is rolled by size as well as by time, and the cleaner runs a pass after every roll in addition to its interval, so the budget is enforced when a file is rolled and newly created archives are accounted for in the same pass. While the rolled logs exceed the budget the cleaner processes the oldest ones, as many as the budget requires, even if they are younger than `RUSTFS_OBS_LOG_MIN_FILE_AGE_SECONDS`; `RUSTFS_OBS_LOG_KEEP_FILES` still applies only to files past that age.
The bound is not instantaneous: the directory can exceed it by what is written while one cleanup pass runs, archives created by a pass are trimmed by the next one, and a cleaner that compresses more slowly than logs are produced falls behind. Setting `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES=0` removes the budget and `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES=0` turns size rolling off, which leaves the active file bounded only by the rotation period. Neither setting limits how fast logs are produced.
To stay bounded under sustained failures or log storms: the file layer attaches a sink-side rate-limiting filter (`RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC` with per-callsite fairness isolation); each cleanup pass compresses at most `RUSTFS_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS` files and directly deletes older mandatory over-budget excess without compression; and if rotation continuously fails, `RollingAppender` sheds active-file writes past a bounded ceiling (2x roll size on transient failures, tightened to 1x after 3 consecutive failures) until rotation recovers. The bound is still not instantaneous (bytes written while a cleanup pass runs can transiently exceed it). Setting `RUSTFS_OBS_LOG_MAX_TOTAL_SIZE_BYTES=0` removes the budget, `RUSTFS_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES=0` turns size rolling off, and `RUSTFS_OBS_LOG_SINK_MAX_EVENTS_PER_SEC=0` disables sink-side rate limiting.
The cleaner recognizes only its own process's active file. Do not let two processes write log files that match the same pattern in one directory: a file another process is still writing looks like a rolled log, and the minimum file age no longer shields it once the budget is exceeded.
@@ -200,6 +204,8 @@ The log rotation and cleanup pipeline emits these metrics (via the `metrics` fac
| `rustfs_log_cleaner_rotation_failures_total` | counter | Failed file rotations |
| `rustfs_log_cleaner_rotation_duration_seconds` | histogram | Rotation latency |
| `rustfs_log_cleaner_active_file_size_bytes` | gauge | Current active log file size |
| `rustfs_log_cleaner_rotation_dropped_bytes_total` | counter | Bytes shed by the rolling appender when continuous rotation failure hits the active-file cap |
| `rustfs_log_cleaner_sink_dropped_events_total` | counter | File-sink log events shed by the sink-side rate limiter |
These metrics cover compression, cleanup, and file rotation end-to-end.
+216 -45
View File
@@ -31,6 +31,7 @@ use crossbeam_deque::{Injector, Steal, Stealer, Worker};
use crossbeam_utils::{Backoff, thread};
use metrics::{counter, gauge, histogram};
use rustfs_config::DEFAULT_LOG_KEEP_FILES;
use rustfs_config::observability::DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
@@ -56,10 +57,20 @@ fn compressed_file_retention_window(days: u64) -> Duration {
struct CompressionTaskResult {
/// Original file metadata so successful workers can be deleted later.
file: FileInfo,
/// Archive created on disk (absent in dry-run mode or on compression error).
archive: Option<FileInfo>,
/// Whether compression completed successfully for this file.
compressed: bool,
}
#[derive(Debug, Default)]
struct BatchProcessOutcome {
deleted_files: usize,
freed_bytes: u64,
deleted_source_bytes: u64,
created_archives: Vec<FileInfo>,
}
/// Log-file lifecycle manager.
///
/// A cleaner instance is immutable after construction and therefore safe to
@@ -76,10 +87,19 @@ pub struct LogCleaner {
pub(super) match_mode: FileMatchMode,
/// Maximum number of newest regular log files to keep.
pub(super) keep_files: usize,
/// Optional cap for the cumulative size of regular logs.
/// Optional cap for the cumulative size of regular logs (and shared with
/// compressed archives when `max_archive_size_bytes` is `None`).
pub(super) max_total_size_bytes: u64,
/// Optional dedicated byte budget for compressed archives.
/// - `None`: archives share the remaining `max_total_size_bytes` budget
/// after surviving rolled logs are accounted for.
/// - `Some(0)`: unlimited archive bytes (retention days still apply).
/// - `Some(cap)`: independent archive byte budget `cap`.
pub(super) max_archive_size_bytes: Option<u64>,
/// Optional cap for an individual regular log file.
pub(super) max_single_file_size_bytes: u64,
/// Maximum regular logs compressed in a single cleanup pass (`0` = unlimited).
pub(super) max_compress_files_per_pass: usize,
/// Whether selected regular logs should be compressed before deletion.
pub(super) compress_old_files: bool,
/// Gzip compression level used when gzip is selected or used as fallback.
@@ -163,24 +183,26 @@ impl LogCleaner {
)?;
logs.sort_by_key(|f| f.modified);
let aged_rolled_bytes: u64 = logs.iter().fold(0u64, |acc, f| acc.saturating_add(f.size));
let recent_rolled_bytes: u64 = recent_logs.iter().fold(0u64, |acc, f| acc.saturating_add(f.size));
let all_rolled_bytes = aged_rolled_bytes.saturating_add(recent_rolled_bytes);
let mut to_delete = Vec::new();
if !logs.is_empty() {
let total_size: u64 = logs.iter().map(|f| f.size).sum();
info!(
event = EVENT_LOG_CLEANER_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
state = "scan_completed",
regular_log_files = logs.len(),
total_bytes = total_size,
total_megabytes = total_size as f64 / 1024.0 / 1024.0,
total_bytes = aged_rolled_bytes,
total_megabytes = aged_rolled_bytes as f64 / 1024.0 / 1024.0,
"log cleaner state changed"
);
// Select the oldest files first, then additionally trim any files
// that still violate configured size constraints.
to_delete = self.select_files_to_process(&logs, total_size);
to_delete = self.select_files_to_process(&logs, aged_rolled_bytes);
}
// `min_file_age_seconds` keeps freshly rolled files readable for a
@@ -201,20 +223,57 @@ impl LogCleaner {
to_delete.extend(over_budget);
}
let mut deleted_source_bytes = 0u64;
if !to_delete.is_empty() {
let (deleted, freed) = if self.parallel_compress && self.compress_old_files {
self.parallel_stealing_compress(&to_delete)?
} else {
self.serial_compress_and_delete(&to_delete)?
};
total_deleted += deleted;
total_freed += freed;
// Sort oldest-first so per-pass compression capping and direct
// over-budget eviction stay deterministic.
to_delete.sort_by_key(|f| f.modified);
let (to_compress, to_direct_delete) = self.partition_files_for_pass(&to_delete, all_rolled_bytes);
if !to_direct_delete.is_empty() {
warn!(
event = EVENT_LOG_CLEANER_STATE,
component = LOG_COMPONENT_OBS,
subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
result = "compression_cap_bypassed_over_budget",
compressed_files = to_compress.len(),
direct_deleted_files = to_direct_delete.len(),
max_compress_files_per_pass = self.max_compress_files_per_pass,
max_total_size_bytes = self.max_total_size_bytes,
"log cleaner state changed"
);
let (deleted, freed, source_bytes) = self.delete_files_with_source_bytes(&to_direct_delete)?;
total_deleted += deleted;
total_freed += freed;
deleted_source_bytes = deleted_source_bytes.saturating_add(source_bytes);
}
if !to_compress.is_empty() {
let outcome = if self.parallel_compress && self.compress_old_files {
self.parallel_stealing_compress(&to_compress)?
} else {
self.serial_compress_and_delete(&to_compress)?
};
total_deleted += outcome.deleted_files;
total_freed += outcome.freed_bytes;
deleted_source_bytes = deleted_source_bytes.saturating_add(outcome.deleted_source_bytes);
for archive in outcome.created_archives {
if let Some(existing) = compressed_archives.iter_mut().find(|entry| entry.path == archive.path) {
*existing = archive;
} else {
compressed_archives.push(archive);
}
}
}
}
let surviving_rolled_bytes = all_rolled_bytes.saturating_sub(deleted_source_bytes);
let effective_archive_budget = self.effective_archive_budget(surviving_rolled_bytes);
if !compressed_archives.is_empty() {
let to_delete = self.select_archives_to_delete(&mut compressed_archives);
let to_delete = self.select_archives_to_delete(&mut compressed_archives, effective_archive_budget);
if !to_delete.is_empty() {
let (d, f) = self.delete_files(&to_delete)?;
let (d, f, _) = self.delete_files_with_source_bytes(&to_delete)?;
total_deleted += d;
total_freed += f;
}
@@ -309,16 +368,73 @@ impl LogCleaner {
to_delete
}
/// Partition selected regular logs into `(compress_and_delete, direct_delete)`
/// while enforcing `max_compress_files_per_pass` when compression is active.
///
/// - Under the byte budget: compresses at most `max_compress_files_per_pass`
/// files and defers the rest to subsequent cleanup passes so CPU spikes
/// are amortized across ticks.
/// - Over the byte budget: compresses the newest `max_compress_files_per_pass`
/// mandatory files and directly deletes older mandatory excess files
/// without compression so the disk budget is enforced in a single pass.
fn partition_files_for_pass(&self, sorted_candidates: &[FileInfo], all_rolled_bytes: u64) -> (Vec<FileInfo>, Vec<FileInfo>) {
if !self.compress_old_files
|| self.max_compress_files_per_pass == 0
|| sorted_candidates.len() <= self.max_compress_files_per_pass
{
return (sorted_candidates.to_vec(), Vec::new());
}
let cap = self.max_compress_files_per_pass;
if self.max_total_size_bytes == 0 {
return (sorted_candidates[..cap].to_vec(), Vec::new());
}
// Compute how many oldest candidates must be evicted right now to bring
// rolled logs back under `max_total_size_bytes`.
let mut remaining = all_rolled_bytes;
let mut mandatory_count = 0usize;
for file in sorted_candidates {
if remaining <= self.max_total_size_bytes {
break;
}
remaining = remaining.saturating_sub(file.size);
mandatory_count += 1;
}
if mandatory_count <= cap {
// Compressing `cap` files already satisfies the byte budget; defer
// any additional keep_files/single-file candidates to later passes.
(sorted_candidates[..cap].to_vec(), Vec::new())
} else {
let direct_count = mandatory_count - cap;
let direct = sorted_candidates[..direct_count].to_vec();
let compress = sorted_candidates[direct_count..mandatory_count].to_vec();
(compress, direct)
}
}
/// Compute the effective byte budget applied to compressed archives.
///
/// - Explicit `Some(0)`: unlimited archive bytes (retention days still apply).
/// - Explicit `Some(cap)`: dedicated archive byte cap independent of rolled logs.
/// - Unset (`None`) with `max_total_size_bytes > 0`: shares the remaining
/// `max_total_size_bytes` budget after `surviving_rolled_bytes` so rolled
/// logs + archives stay within the single configured total budget.
/// - Unset (`None`) with `max_total_size_bytes == 0`: unlimited.
fn effective_archive_budget(&self, surviving_rolled_bytes: u64) -> Option<u64> {
match self.max_archive_size_bytes {
Some(0) => None,
Some(cap) => Some(cap),
None if self.max_total_size_bytes > 0 => Some(self.max_total_size_bytes.saturating_sub(surviving_rolled_bytes)),
None => None,
}
}
/// Select compressed archives to delete: those older than the retention
/// window, plus — regardless of retention — the oldest archives needed to
/// bring the archive set back under `max_total_size_bytes`.
///
/// The byte cap is the crucial part: with `compressed_file_retention_days`
/// set to 0 (retention disabled) and compression enabled, age-based expiry
/// never fires, so without this cap archives would grow without bound (the
/// cap on regular logs does not cover them). Bounding the archive set by the
/// same byte budget keeps disk usage finite even when retention is off.
fn select_archives_to_delete(&self, files: &mut [FileInfo]) -> Vec<FileInfo> {
/// bring the archive set back under `effective_archive_budget`.
fn select_archives_to_delete(&self, files: &mut [FileInfo], effective_archive_budget: Option<u64>) -> Vec<FileInfo> {
if self.compressed_file_retention_days > MAX_RETENTION_DAYS_BEFORE_SATURATION {
warn!(
event = EVENT_LOG_CLEANER_STATE,
@@ -352,8 +468,8 @@ impl LogCleaner {
}
// 2. Byte-cap trim: drop the oldest surviving archives until the set
// fits under the configured total. 0 means "no cap".
if self.max_total_size_bytes > 0 {
// fits under `effective_archive_budget`. `None` means "no byte cap".
if let Some(archive_budget) = effective_archive_budget {
let mut remaining: u64 = files
.iter()
.enumerate()
@@ -361,7 +477,7 @@ impl LogCleaner {
.map(|(_, file)| file.size)
.sum();
for (idx, file) in files.iter().enumerate() {
if remaining <= self.max_total_size_bytes {
if remaining <= archive_budget {
break;
}
if selected[idx] {
@@ -387,7 +503,7 @@ impl LogCleaner {
/// Compression workers only decide whether an archive was created; the main
/// thread remains responsible for actual source removal so deletion policy
/// and error reporting stay deterministic.
fn parallel_stealing_compress(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
fn parallel_stealing_compress(&self, files: &[FileInfo]) -> Result<BatchProcessOutcome, std::io::Error> {
if files.len() <= 1 {
return self.serial_compress_and_delete(files);
}
@@ -484,7 +600,7 @@ impl LogCleaner {
// starts from a cheap spin again.
backoff.reset();
let mut file = file;
let compressed = match compress_file(&file.path, &options) {
let (compressed, archive) = match compress_file(&file.path, &options) {
Ok(output) => {
debug!(
event = EVENT_LOG_CLEANER_STATE,
@@ -499,15 +615,21 @@ impl LogCleaner {
"log cleaner state changed"
);
file.projected_freed_bytes = output.input_bytes.saturating_sub(output.output_bytes);
true
let archive = (!options.dry_run).then(|| FileInfo {
path: output.archive_path,
size: output.output_bytes,
projected_freed_bytes: output.output_bytes,
modified: SystemTime::now(),
});
(true, archive)
}
Err(err) => {
warn!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?file.path, error = %err, result = "parallel_compression_failed", "log cleaner state changed");
false
(false, None)
}
};
if tx.send(CompressionTaskResult { file, compressed }).is_err() {
if tx.send(CompressionTaskResult { file, archive, compressed }).is_err() {
break;
}
}
@@ -516,18 +638,22 @@ impl LogCleaner {
drop(tx);
let mut deletable = Vec::with_capacity(files.len());
let mut created_archives = Vec::new();
for result in rx {
if result.compressed {
deletable.push(result.file);
if let Some(archive) = result.archive {
created_archives.push(archive);
}
}
}
deletable
(deletable, created_archives)
});
// Any worker panic triggers deterministic fallback behavior.
let deletable = match scope_result {
Ok(deletable) => deletable,
let (deletable, created_archives) = match scope_result {
Ok(outcome) => outcome,
Err(_) => {
warn!(
event = EVENT_LOG_CLEANER_STATE,
@@ -541,7 +667,7 @@ impl LogCleaner {
}
};
let (deleted, freed) = self.delete_files(&deletable)?;
let (deleted, freed, deleted_source_bytes) = self.delete_files_with_source_bytes(&deletable)?;
let elapsed = started_at.elapsed().as_secs_f64();
// NOTE on metric scope: attempts/successes count only *victim* steals
// (not the injector `steal_batch_and_pop`), and a multi-task stolen
@@ -576,7 +702,12 @@ impl LogCleaner {
"log cleaner state changed"
);
Ok((deleted, freed))
Ok(BatchProcessOutcome {
deleted_files: deleted,
freed_bytes: freed,
deleted_source_bytes,
created_archives,
})
}
/// Attempt to steal a task from peer workers using randomized victim order.
@@ -620,9 +751,10 @@ impl LogCleaner {
///
/// This path is also used whenever the task set is too small to benefit
/// from worker orchestration.
fn serial_compress_and_delete(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
fn serial_compress_and_delete(&self, files: &[FileInfo]) -> Result<BatchProcessOutcome, std::io::Error> {
let started_at = Instant::now();
let mut deletable = Vec::with_capacity(files.len());
let mut created_archives = Vec::new();
if self.compress_old_files {
let options = self.compression_options();
@@ -644,6 +776,14 @@ impl LogCleaner {
let mut file = file.clone();
file.projected_freed_bytes = output.input_bytes.saturating_sub(output.output_bytes);
deletable.push(file);
if !options.dry_run {
created_archives.push(FileInfo {
path: output.archive_path,
size: output.output_bytes,
projected_freed_bytes: output.output_bytes,
modified: SystemTime::now(),
});
}
}
Err(err) => {
warn!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?file.path, error = %err, result = "serial_compression_failed", "log cleaner state changed");
@@ -654,10 +794,15 @@ impl LogCleaner {
deletable.extend(files.iter().cloned());
}
let (deleted, freed) = self.delete_files(&deletable)?;
let (deleted, freed, deleted_source_bytes) = self.delete_files_with_source_bytes(&deletable)?;
histogram!(METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS).record(started_at.elapsed().as_secs_f64());
Ok((deleted, freed))
Ok(BatchProcessOutcome {
deleted_files: deleted,
freed_bytes: freed,
deleted_source_bytes,
created_archives,
})
}
/// Snapshot compression-related configuration for a single cleanup pass.
@@ -708,26 +853,30 @@ impl LogCleaner {
}
}
/// Delete the supplied files and return `(deleted_count, freed_bytes)`.
/// Delete the supplied files and return
/// `(deleted_count, freed_bytes, deleted_source_bytes)`.
///
/// In dry-run mode the returned counters still reflect the projected work
/// so callers and metrics can report what would have happened.
pub(super) fn delete_files(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
fn delete_files_with_source_bytes(&self, files: &[FileInfo]) -> Result<(usize, u64, u64), std::io::Error> {
let mut deleted = 0usize;
let mut freed = 0u64;
let mut source_bytes = 0u64;
for f in files {
if self.dry_run {
info!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "dry_run_delete", file = ?f.path, bytes = f.size, "log cleaner state changed");
deleted += 1;
freed += f.projected_freed_bytes;
freed = freed.saturating_add(f.projected_freed_bytes);
source_bytes = source_bytes.saturating_add(f.size);
continue;
}
match self.secure_delete(&f.path) {
Ok(()) => {
deleted += 1;
freed += f.projected_freed_bytes;
freed = freed.saturating_add(f.projected_freed_bytes);
source_bytes = source_bytes.saturating_add(f.size);
debug!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "deleted", file = ?f.path, bytes = f.size, projected_freed_bytes = f.projected_freed_bytes, "log cleaner state changed");
}
Err(e) => {
@@ -746,7 +895,7 @@ impl LogCleaner {
let _ = dir.sync_all();
}
Ok((deleted, freed))
Ok((deleted, freed, source_bytes))
}
}
@@ -761,7 +910,9 @@ pub struct LogCleanerBuilder {
match_mode: FileMatchMode,
keep_files: usize,
max_total_size_bytes: u64,
max_archive_size_bytes: Option<u64>,
max_single_file_size_bytes: u64,
max_compress_files_per_pass: usize,
compress_old_files: bool,
gzip_compression_level: u32,
compressed_file_retention_days: u64,
@@ -787,7 +938,9 @@ impl LogCleanerBuilder {
match_mode: FileMatchMode::Prefix,
keep_files: DEFAULT_LOG_KEEP_FILES,
max_total_size_bytes: 0,
max_archive_size_bytes: None,
max_single_file_size_bytes: 0,
max_compress_files_per_pass: DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
compress_old_files: false,
gzip_compression_level: 6,
compressed_file_retention_days: 0,
@@ -816,18 +969,34 @@ impl LogCleanerBuilder {
self
}
/// Cap the aggregate size of retained regular log files.
/// Cap the aggregate size of retained regular log files (and compressed
/// archives when `max_archive_size_bytes` is unset).
pub fn max_total_size_bytes(mut self, max_total_size_bytes: u64) -> Self {
self.max_total_size_bytes = max_total_size_bytes;
self
}
/// Set a dedicated byte budget for compressed archives independent of
/// `max_total_size_bytes`. Pass `None` to share `max_total_size_bytes`,
/// `Some(0)` for unlimited archive bytes, or `Some(cap)` for a separate cap.
pub fn max_archive_size_bytes(mut self, max_archive_size_bytes: Option<u64>) -> Self {
self.max_archive_size_bytes = max_archive_size_bytes;
self
}
/// Cap the size of any individual regular log file.
pub fn max_single_file_size_bytes(mut self, max_single_file_size_bytes: u64) -> Self {
self.max_single_file_size_bytes = max_single_file_size_bytes;
self
}
/// Cap how many rolled log files may be compressed in a single cleanup pass
/// (`0` = unlimited).
pub fn max_compress_files_per_pass(mut self, max_compress_files_per_pass: usize) -> Self {
self.max_compress_files_per_pass = max_compress_files_per_pass;
self
}
/// Enable archival compression before deleting selected source logs.
pub fn compress_old_files(mut self, compress_old_files: bool) -> Self {
self.compress_old_files = compress_old_files;
@@ -959,7 +1128,9 @@ impl LogCleanerBuilder {
match_mode: self.match_mode,
keep_files: self.keep_files,
max_total_size_bytes: self.max_total_size_bytes,
max_archive_size_bytes: self.max_archive_size_bytes,
max_single_file_size_bytes: self.max_single_file_size_bytes,
max_compress_files_per_pass: self.max_compress_files_per_pass,
compress_old_files: self.compress_old_files,
// gzip level 0 is a valid "store" (no compression) mode, so keep the
// lower bound at 0 rather than silently bumping it to 1.
+186
View File
@@ -743,4 +743,190 @@ mod tests {
assert_eq!(std::fs::metadata(&gz)?.len(), archive_len, "existing valid archive unchanged");
Ok(())
}
/// P2-6: under the byte budget, a single cleanup pass compresses at most
/// `max_compress_files_per_pass` rolled files and defers the remaining
/// backlog to subsequent passes instead of spiking CPU.
#[test]
fn single_pass_compression_cap_defers_under_budget_backlog() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
for i in 0..5u64 {
let name = format!("app.log.2024-01-0{i}");
create_log_file(&dir, &name, 1024)?;
set_mtime_ago(&dir.join(&name), Duration::from_secs((10 - i) * 60));
}
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(0)
.max_total_size_bytes(0)
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.max_compress_files_per_pass(2)
.min_file_age_seconds(0)
.build();
let (deleted_pass_1, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_1, 2, "first pass must compress at most 2 files");
assert!(dir.join("app.log.2024-01-00.gz").exists());
assert!(dir.join("app.log.2024-01-01.gz").exists());
for i in 2..5 {
assert!(
dir.join(format!("app.log.2024-01-0{i}")).exists(),
"deferred file {i} must wait for a later pass"
);
assert!(!dir.join(format!("app.log.2024-01-0{i}.gz")).exists());
}
let (deleted_pass_2, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_2, 2, "second pass compresses the next 2 files");
let (deleted_pass_3, _) = cleaner.cleanup()?;
assert_eq!(deleted_pass_3, 1, "third pass finishes the backlog");
Ok(())
}
/// P2-6 under storm pressure: when rolled files exceed `max_total_size_bytes`,
/// at most `max_compress_files_per_pass` files are compressed and older
/// mandatory over-budget files are deleted directly so the disk cap holds in
/// one pass without unbounded CPU work.
#[test]
fn single_pass_compression_cap_evicts_over_budget_excess_without_compressing() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
for i in 0..6u64 {
let name = format!("app.log.2024-01-0{i}");
create_log_file(&dir, &name, 1024)?;
set_mtime_ago(&dir.join(&name), Duration::from_secs((60 - i * 5) * 60));
}
// 6 KiB rolled, 2 KiB rolled budget -> 4 files must be evicted immediately.
// Separate archive budget keeps the 2 created archives visible for assertion.
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(10 * 1024))
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.max_compress_files_per_pass(2)
.min_file_age_seconds(0)
.build();
let (deleted, _) = cleaner.cleanup()?;
assert_eq!(deleted, 4, "all 4 over-budget files must be removed in one pass");
// Oldest 2 deleted directly without compression.
for i in 0..2 {
assert!(!dir.join(format!("app.log.2024-01-0{i}")).exists());
assert!(
!dir.join(format!("app.log.2024-01-0{i}.gz")).exists(),
"excess over-budget file {i} must bypass compression"
);
}
// Newest 2 of the evicted 4 are compressed (respecting cap=2).
for i in 2..4 {
assert!(!dir.join(format!("app.log.2024-01-0{i}")).exists());
assert!(dir.join(format!("app.log.2024-01-0{i}.gz")).exists());
}
// Newest 2 remain as plain rolled logs within the 2 KiB budget.
for i in 4..6 {
assert!(dir.join(format!("app.log.2024-01-0{i}")).exists());
}
Ok(())
}
/// When `max_archive_size_bytes` is unset, rolled logs and compressed
/// archives share the single `max_total_size_bytes` ceiling instead of each
/// consuming up to `max_total_size_bytes` independently.
#[test]
fn shared_total_budget_bounds_rolled_logs_and_archives_together() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
create_log_file(&dir, "app.log.2024-01-01.gz", 1024)?;
create_log_file(&dir, "app.log.2024-01-02.gz", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-01.gz"), Duration::from_secs(300));
set_mtime_ago(&dir.join("app.log.2024-01-02.gz"), Duration::from_secs(200));
create_log_file(&dir, "app.log.2024-01-03", 1024)?;
create_log_file(&dir, "app.log.2024-01-04", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-03"), Duration::from_secs(100));
set_mtime_ago(&dir.join("app.log.2024-01-04"), Duration::from_secs(50));
// 2 KiB rolled + 2 KiB archives = 4 KiB total; shared budget is 3 KiB.
// Rolled logs (2 KiB) fit, leaving 1 KiB for archives -> oldest archive goes.
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(3 * 1024)
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
let (deleted, _) = cleaner.cleanup()?;
assert_eq!(deleted, 1, "oldest archive must be trimmed to keep rolled+archives <= total budget");
assert!(!dir.join("app.log.2024-01-01.gz").exists());
assert!(dir.join("app.log.2024-01-02.gz").exists());
assert!(dir.join("app.log.2024-01-03").exists());
assert!(dir.join("app.log.2024-01-04").exists());
Ok(())
}
/// Setting `max_archive_size_bytes(Some(cap))` enforces separate rolled-log
/// and archive budgets independently, including archives created in the same
/// cleanup pass.
#[test]
fn explicit_separate_archive_budget_applies_independently_and_same_pass() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path().to_path_buf();
create_log_file(&dir, "app.log.2024-01-01.gz", 1024)?;
create_log_file(&dir, "app.log.2024-01-02.gz", 1024)?;
set_mtime_ago(&dir.join("app.log.2024-01-01.gz"), Duration::from_secs(300));
set_mtime_ago(&dir.join("app.log.2024-01-02.gz"), Duration::from_secs(200));
// Rolled logs fit inside 2 KiB rolled budget while separate archive budget is 3 KiB.
create_log_file(&dir, "app.log.2024-01-03", 1024)?;
create_log_file(&dir, "app.log.2024-01-04", 1024)?;
let cleaner = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(30)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(3 * 1024))
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
assert_eq!(
cleaner.cleanup()?,
(0, 0),
"both rolled (2 KiB <= 2 KiB) and archives (2 KiB <= 3 KiB) fit their separate budgets"
);
// Now tighten the separate archive budget to 1024 bytes while compressing a new log in the same pass.
create_log_file(&dir, "app.log.2024-01-00", 2048)?;
set_mtime_ago(&dir.join("app.log.2024-01-00"), Duration::from_secs(400));
let tight = LogCleaner::builder(dir.clone(), "app.log.".to_string(), "app.log".to_string())
.match_mode(FileMatchMode::Prefix)
.keep_files(2)
.max_total_size_bytes(2 * 1024)
.max_archive_size_bytes(Some(1024))
.compress_old_files(true)
.compression_algorithm(CompressionAlgorithm::Gzip)
.parallel_compress(false)
.compressed_file_retention_days(0)
.min_file_age_seconds(0)
.build();
let _ = tight.cleanup()?;
let archive_bytes: u64 = std::fs::read_dir(&dir)?
.filter_map(Result::ok)
.filter(|e| e.file_name().to_string_lossy().ends_with(".gz"))
.map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))
.sum();
assert!(
archive_bytes <= 1024,
"same-pass newly created archives must obey the archive budget (got {archive_bytes} bytes)"
);
Ok(())
}
}
+83 -14
View File
@@ -26,17 +26,19 @@ use rustfs_config::observability::{
DEFAULT_OBS_ENVIRONMENT_PRODUCTION, DEFAULT_OBS_LOG_CLEANUP_INTERVAL_SECONDS, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES,
DEFAULT_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM, DEFAULT_OBS_LOG_DELETE_EMPTY_FILES,
DEFAULT_OBS_LOG_DRY_RUN, DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_MATCH_MODE,
DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS, DEFAULT_OBS_LOG_PARALLEL_COMPRESS,
DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP,
DEFAULT_OBS_LOG_ZSTD_WORKERS, ENV_OBS_ENDPOINT, ENV_OBS_ENDPOINT_HEADERS, ENV_OBS_ENDPOINT_LOGS_HEADERS,
ENV_OBS_ENDPOINT_LOGS_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_METRICS_HEADERS, ENV_OBS_ENDPOINT_METRICS_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_TRACES_HEADERS, ENV_OBS_ENDPOINT_TRACES_TIMEOUT_MILLIS,
ENV_OBS_ENVIRONMENT, ENV_OBS_LOG_CLEANUP_INTERVAL_SECONDS, ENV_OBS_LOG_COMPRESS_OLD_FILES,
ENV_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, ENV_OBS_LOG_COMPRESSION_ALGORITHM, ENV_OBS_LOG_DELETE_EMPTY_FILES,
ENV_OBS_LOG_DIRECTORY, ENV_OBS_LOG_DRY_RUN, ENV_OBS_LOG_ENDPOINT, ENV_OBS_LOG_EXCLUDE_PATTERNS, ENV_OBS_LOG_FILENAME,
ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL, ENV_OBS_LOG_KEEP_FILES, ENV_OBS_LOG_MATCH_MODE, ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES,
ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, ENV_OBS_LOG_MIN_FILE_AGE_SECONDS, ENV_OBS_LOG_PARALLEL_COMPRESS,
ENV_OBS_LOG_PARALLEL_WORKERS, ENV_OBS_LOG_ROTATION_TIME, ENV_OBS_LOG_STDOUT_ENABLED, ENV_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS,
DEFAULT_OBS_LOG_PARALLEL_COMPRESS, DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS,
ENV_OBS_ENDPOINT, ENV_OBS_ENDPOINT_HEADERS, ENV_OBS_ENDPOINT_LOGS_HEADERS, ENV_OBS_ENDPOINT_LOGS_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_METRICS_HEADERS, ENV_OBS_ENDPOINT_METRICS_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_TIMEOUT_MILLIS,
ENV_OBS_ENDPOINT_TRACES_HEADERS, ENV_OBS_ENDPOINT_TRACES_TIMEOUT_MILLIS, ENV_OBS_ENVIRONMENT,
ENV_OBS_LOG_CLEANUP_INTERVAL_SECONDS, ENV_OBS_LOG_COMPRESS_OLD_FILES, ENV_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS,
ENV_OBS_LOG_COMPRESSION_ALGORITHM, ENV_OBS_LOG_DELETE_EMPTY_FILES, ENV_OBS_LOG_DIRECTORY, ENV_OBS_LOG_DRY_RUN,
ENV_OBS_LOG_ENDPOINT, ENV_OBS_LOG_EXCLUDE_PATTERNS, ENV_OBS_LOG_FILENAME, ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL,
ENV_OBS_LOG_KEEP_FILES, ENV_OBS_LOG_MATCH_MODE, ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, ENV_OBS_LOG_MIN_FILE_AGE_SECONDS,
ENV_OBS_LOG_PARALLEL_COMPRESS, ENV_OBS_LOG_PARALLEL_WORKERS, ENV_OBS_LOG_ROTATION_TIME, ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC, ENV_OBS_LOG_STDOUT_ENABLED, ENV_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
ENV_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, ENV_OBS_LOG_ZSTD_WORKERS, ENV_OBS_LOGGER_LEVEL, ENV_OBS_LOGS_EXPORT_ENABLED,
ENV_OBS_METER_INTERVAL, ENV_OBS_METRIC_ENDPOINT, ENV_OBS_METRICS_EXPORT_ENABLED, ENV_OBS_PROFILING_ENDPOINT,
ENV_OBS_PROFILING_EXPORT_ENABLED, ENV_OBS_SAMPLE_RATIO, ENV_OBS_SERVICE_NAME, ENV_OBS_SERVICE_VERSION, ENV_OBS_TLS_CA_FILE,
@@ -188,14 +190,34 @@ pub struct OtelConfig {
pub log_keep_files: Option<usize>,
// ── Log cleanup ───────────────────────────────────────────────────────────
/// Byte budget for rolled log files, and separately for compressed
/// archives (default: 2 GiB); `0` means no budget. The active file is not
/// counted.
/// Byte budget for rolled log files (and shared with compressed archives
/// when `log_max_archive_size_bytes` is unset); default 2 GiB, `0` = no
/// budget. The active file is not counted.
pub log_max_total_size_bytes: Option<u64>,
/// Optional separate byte budget for compressed archives (`.gz`/`.zst`).
/// When unset, archives share the remaining `log_max_total_size_bytes`
/// budget with surviving rolled logs. `Some(0)` removes the archive byte
/// cap while keeping retention days active.
#[serde(default)]
pub log_max_archive_size_bytes: Option<u64>,
/// Per-file size ceiling (bytes). Unset or unparsable: the active file
/// rolls at 256 MiB (less under a small byte budget) and the cleaner
/// applies no per-file trim. `0`: no size roll and no trim.
pub log_max_single_file_size_bytes: Option<u64>,
/// Maximum rolled log files compressed in a single cleanup pass (default:
/// `32`; `0` = unlimited). Over-budget files beyond this cap are deleted
/// directly without compression so disk usage remains bounded.
#[serde(default)]
pub log_max_compress_files_per_pass: Option<usize>,
/// Global file-sink event rate limit in events/sec (default: `10_000`;
/// `0` = unlimited).
#[serde(default)]
pub log_sink_max_events_per_sec: Option<u64>,
/// Per-callsite file-sink event rate limit in events/sec. Unset defaults
/// to `(log_sink_max_events_per_sec / 4).max(1)`; `0` disables per-callsite
/// isolation while retaining the global sink ceiling.
#[serde(default)]
pub log_sink_per_callsite_max_events_per_sec: Option<u64>,
/// Compress eligible files with gzip before deletion (default: `true`).
pub log_compress_old_files: Option<bool>,
/// Gzip compression level `1`–`9` (default: `6`).
@@ -347,8 +369,19 @@ impl OtelConfig {
log_keep_files,
// Log cleanup
log_max_total_size_bytes: Some(get_env_u64(ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES)),
// Unset stays `None`: archives then share the remaining total budget.
log_max_archive_size_bytes: get_env_opt_u64(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES),
// Unset stays `None`: the appender and the cleaner default differently.
log_max_single_file_size_bytes: get_env_opt_u64(ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES),
log_max_compress_files_per_pass: Some(get_env_usize(
ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
)),
log_sink_max_events_per_sec: Some(get_env_u64(
ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
)),
log_sink_per_callsite_max_events_per_sec: get_env_opt_u64(ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC),
log_compress_old_files: Some(get_env_bool(ENV_OBS_LOG_COMPRESS_OLD_FILES, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES)),
log_gzip_compression_level: Some(get_env_u64(
ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL,
@@ -642,4 +675,40 @@ mod tests {
});
});
}
#[test]
fn log_disk_bounds_and_sink_rate_limit_env_defaults_and_overrides() {
with_profiling_env_lock(|| {
temp_env::with_vars_unset(
[
ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES,
ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS,
ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC,
ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC,
],
|| {
let config = OtelConfig::extract_otel_config_from_env(None);
assert_eq!(config.log_max_archive_size_bytes, None);
assert_eq!(config.log_max_compress_files_per_pass, Some(DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS));
assert_eq!(config.log_sink_max_events_per_sec, Some(DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC));
assert_eq!(config.log_sink_per_callsite_max_events_per_sec, None);
},
);
temp_env::with_vars(
[
(ENV_OBS_LOG_MAX_ARCHIVE_SIZE_BYTES, Some("4096")),
(ENV_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, Some("8")),
(ENV_OBS_LOG_SINK_MAX_EVENTS_PER_SEC, Some("500")),
(ENV_OBS_LOG_SINK_PER_CALLSITE_MAX_EVENTS_PER_SEC, Some("100")),
],
|| {
let config = OtelConfig::extract_otel_config_from_env(None);
assert_eq!(config.log_max_archive_size_bytes, Some(4096));
assert_eq!(config.log_max_compress_files_per_pass, Some(8));
assert_eq!(config.log_sink_max_events_per_sec, Some(500));
assert_eq!(config.log_sink_per_callsite_max_events_per_sec, Some(100));
},
);
});
}
}
+4
View File
@@ -38,6 +38,8 @@ pub(crate) const METRIC_LOG_CLEANER_ROTATION_TOTAL: &str = "rustfs_log_cleaner_r
pub(crate) const METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL: &str = "rustfs_log_cleaner_rotation_failures_total";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS: &str = "rustfs_log_cleaner_rotation_duration_seconds";
pub(crate) const METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES: &str = "rustfs_log_cleaner_active_file_size_bytes";
pub(crate) const METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL: &str = "rustfs_log_cleaner_rotation_dropped_bytes_total";
pub(crate) const METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL: &str = "rustfs_log_cleaner_sink_dropped_events_total";
/// Check whether Observability metric is enabled
pub fn observability_metric_enabled() -> bool {
@@ -224,6 +226,8 @@ mod tests {
METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL,
METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS,
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES,
METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL,
METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL,
];
for metric in metrics {
+17 -6
View File
@@ -37,16 +37,17 @@ use crate::cleaner::types::{CompressionAlgorithm, FileMatchMode};
use crate::config::OtelConfig;
use crate::global::{METRIC_LOG_CLEANER_RUN_FAILURES_TOTAL, METRIC_LOG_CLEANER_RUNS_TOTAL, set_observability_metric_enabled};
use crate::telemetry::filter::{build_env_filter, effective_verbose_logging, pyroscope_log_filter, s3_dependency_log_filter};
use crate::telemetry::rate_limit::{FileSinkRateLimitFilter, RateLimitedLayer};
use crate::telemetry::rolling::{RollingAppender, Rotation};
use metrics::counter;
use rustfs_config::observability::{
DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES, DEFAULT_OBS_LOG_CLEANUP_INTERVAL_SECONDS, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES,
DEFAULT_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM, DEFAULT_OBS_LOG_DELETE_EMPTY_FILES,
DEFAULT_OBS_LOG_DRY_RUN, DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_MATCH_MODE,
DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS,
DEFAULT_OBS_LOG_PARALLEL_COMPRESS, DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SPAN_EVENTS,
DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS,
ENV_OBS_LOG_SPAN_EVENTS,
DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS, DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES,
DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS, DEFAULT_OBS_LOG_PARALLEL_COMPRESS,
DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_SPAN_EVENTS, DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS, ENV_OBS_LOG_SPAN_EVENTS,
};
use rustfs_config::{APP_NAME, DEFAULT_LOG_KEEP_FILES, DEFAULT_LOG_ROTATION_TIME};
use rustfs_utils::get_env_str;
@@ -516,8 +517,12 @@ fn init_file_logging_internal(
let span_list = resolve_span_list(logger_level);
// File output stays machine-readable and free of ANSI sequences so the
// resulting files are safe to parse or ship to log processors.
let file_layer = build_json_log_layer(non_blocking, false, span_events.clone(), span_list);
// resulting files are safe to parse or ship to log processors, guarded by
// the sink-side rate limiter against unthrottled log storms.
let file_layer = RateLimitedLayer::new(
build_json_log_layer(non_blocking, false, span_events.clone(), span_list),
FileSinkRateLimitFilter::from_config(config),
);
// Optional stdout mirror: enabled explicitly via `log_stdout_enabled`, or
// unconditionally in non-production environments so developers still see
@@ -703,7 +708,11 @@ pub fn spawn_cleanup_task(
let max_total_size = config
.log_max_total_size_bytes
.unwrap_or(DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES);
let max_archive_size = config.log_max_archive_size_bytes;
let max_single_file_size = resolve_cleanup_single_file_limit(config);
let max_compress_files_per_pass = config
.log_max_compress_files_per_pass
.unwrap_or(DEFAULT_OBS_LOG_MAX_COMPRESS_FILES_PER_PASS);
let compress = config.log_compress_old_files.unwrap_or(DEFAULT_OBS_LOG_COMPRESS_OLD_FILES);
let gzip_level = config
.log_gzip_compression_level
@@ -743,7 +752,9 @@ pub fn spawn_cleanup_task(
.match_mode(match_mode)
.keep_files(keep_files)
.max_total_size_bytes(max_total_size)
.max_archive_size_bytes(max_archive_size)
.max_single_file_size_bytes(max_single_file_size)
.max_compress_files_per_pass(max_compress_files_per_pass)
.compress_old_files(compress)
.gzip_compression_level(gzip_level)
// Compression behavior stays fully config-driven, but the builder
+1
View File
@@ -47,6 +47,7 @@ mod guard;
mod http2_ping;
mod local;
mod otel;
mod rate_limit;
mod recorder;
mod resource;
mod rolling;
+5 -1
View File
@@ -42,6 +42,7 @@ use crate::global::set_observability_metric_enabled;
use crate::telemetry::filter::{build_env_filter, pyroscope_log_filter, s3_dependency_log_filter};
use crate::telemetry::guard::{OtelGuard, ProfilingAgent};
use crate::telemetry::local::{build_json_log_layer, open_rolling_appender, spawn_cleanup_task};
use crate::telemetry::rate_limit::{FileSinkRateLimitFilter, RateLimitedLayer};
use crate::telemetry::recorder::{Recorder, install_process_global_recorder};
use crate::telemetry::resource::build_resource;
use crate::telemetry::rolling::Rotation;
@@ -264,7 +265,10 @@ pub(super) fn init_observability_http(
crate::telemetry::local::validate_stdout_sink(&file_appender)?;
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
let file_layer = build_json_log_layer(non_blocking, false, span_events.clone(), span_list);
let file_layer = RateLimitedLayer::new(
build_json_log_layer(non_blocking, false, span_events.clone(), span_list),
FileSinkRateLimitFilter::from_config(config),
);
let cleanup_handle = spawn_cleanup_task(config, log_directory, log_filename, keep_files, roll_signal);
Ok((file_layer, guard, cleanup_handle, rotation_str))
})();
+445
View File
@@ -0,0 +1,445 @@
// Copyright 2026 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Sink-side rate-limiting tracing layer for file-backed log outputs.
//!
//! Protects on-disk log sinks against unthrottled hot-path log storms even if a
//! call site lacks a dedicated source-side throttle. Wraps only the file layer
//! via [`RateLimitedLayer`] so metrics, traces, and sibling layers remain
//! unaffected.
//!
//! Token accounting executes strictly in [`Layer::on_event`] (never for spans,
//! and only after upstream `EnvFilter` / target filters have admitted the
//! event), using lock-free single-word atomic fixed-window counters:
//! - a global file-sink ceiling across all call sites;
//! - a fixed-size per-callsite fairness table (zero heap growth) so one noisy
//! site cannot starve infrequent errors from other call sites.
use crate::config::OtelConfig;
use crate::global::METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL;
use metrics::counter;
use rustfs_config::observability::DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use tracing::{Dispatch, Event, Metadata, Subscriber, span, subscriber::Interest};
use tracing_subscriber::{Layer, layer::Context, registry::LookupSpan};
/// Number of fixed direct-mapped callsite fairness slots (power of two).
const CALLSITE_SLOTS: usize = 256;
/// Number of low bits reserved for the per-window event counter (`2^24 - 1`).
const COUNT_BITS: u32 = 24;
const COUNT_MASK: u64 = (1u64 << COUNT_BITS) - 1;
const WINDOW_MASK: u64 = (1u64 << (64 - COUNT_BITS)) - 1;
/// Clock abstraction for deterministic, sleep-free unit tests.
trait WindowClock: Send + Sync {
fn current_window(&self) -> u64;
}
struct MonotonicSecondClock {
started: Instant,
}
impl MonotonicSecondClock {
fn new() -> Self {
Self { started: Instant::now() }
}
}
impl WindowClock for MonotonicSecondClock {
fn current_window(&self) -> u64 {
self.started.elapsed().as_secs() & WINDOW_MASK
}
}
/// Lock-free fixed-window counter packed into one `AtomicU64`:
/// upper 40 bits = window index, lower 24 bits = admitted count in that window.
#[derive(Default)]
struct PackedWindowBucket {
state: AtomicU64,
}
impl PackedWindowBucket {
fn try_admit(&self, window: u64, limit: u64) -> bool {
if limit == 0 {
return true;
}
let capped_limit = limit.min(COUNT_MASK);
let window = window & WINDOW_MASK;
let mut packed = self.state.load(Ordering::Acquire);
loop {
let stored_window = packed >> COUNT_BITS;
let stored_count = packed & COUNT_MASK;
let next = if stored_window != window {
(window << COUNT_BITS) | 1
} else if stored_count < capped_limit {
(window << COUNT_BITS) | (stored_count + 1)
} else {
return false;
};
match self
.state
.compare_exchange_weak(packed, next, Ordering::AcqRel, Ordering::Acquire)
{
Ok(_) => return true,
Err(observed) => packed = observed,
}
}
}
}
struct RateLimiterState {
global_limit_per_sec: u64,
per_callsite_limit_per_sec: u64,
global_bucket: PackedWindowBucket,
callsite_buckets: Box<[PackedWindowBucket; CALLSITE_SLOTS]>,
dropped_events: AtomicU64,
clock: Box<dyn WindowClock>,
}
/// Lock-free global and per-callsite event rate limiter backing [`RateLimitedLayer`].
#[derive(Clone)]
pub(crate) struct FileSinkRateLimitFilter {
state: Arc<RateLimiterState>,
}
impl FileSinkRateLimitFilter {
/// Construct from [`OtelConfig`] defaults and overrides.
///
/// When `log_sink_max_events_per_sec` is `Some(0)`, sink-side rate limiting
/// is disabled (pass-through). When `log_sink_per_callsite_max_events_per_sec`
/// is unset, each callsite bucket is capped at `(global / 4).max(1)` so a
/// single noisy site cannot exhaust the global sink budget.
pub(crate) fn from_config(config: &OtelConfig) -> Self {
let global_limit = config
.log_sink_max_events_per_sec
.unwrap_or(DEFAULT_OBS_LOG_SINK_MAX_EVENTS_PER_SEC);
let per_callsite_limit = if global_limit == 0 {
0
} else {
config
.log_sink_per_callsite_max_events_per_sec
.unwrap_or_else(|| (global_limit / 4).max(1))
};
Self::new(global_limit, per_callsite_limit)
}
/// Construct with explicit per-second global and per-callsite limits.
pub(crate) fn new(global_limit_per_sec: u64, per_callsite_limit_per_sec: u64) -> Self {
Self::with_clock(global_limit_per_sec, per_callsite_limit_per_sec, Box::new(MonotonicSecondClock::new()))
}
fn with_clock(global_limit_per_sec: u64, per_callsite_limit_per_sec: u64, clock: Box<dyn WindowClock>) -> Self {
let callsite_buckets = Box::new(std::array::from_fn(|_| PackedWindowBucket::default()));
Self {
state: Arc::new(RateLimiterState {
global_limit_per_sec,
per_callsite_limit_per_sec,
global_bucket: PackedWindowBucket::default(),
callsite_buckets,
dropped_events: AtomicU64::new(0),
clock,
}),
}
}
/// Total events shed by this sink filter.
#[cfg(test)]
pub(crate) fn dropped_events(&self) -> u64 {
self.state.dropped_events.load(Ordering::Acquire)
}
fn callsite_slot(meta: &Metadata<'_>) -> usize {
// Deterministic FNV-1a hash of (target, file, line) into
// `[0, CALLSITE_SLOTS)` so slot mapping is stable across runs/ASLR.
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for byte in meta.target().as_bytes() {
h ^= u64::from(*byte);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h ^= 0xff;
h = h.wrapping_mul(0x0100_0000_01b3);
if let Some(file) = meta.file() {
for byte in file.as_bytes() {
h ^= u64::from(*byte);
h = h.wrapping_mul(0x0100_0000_01b3);
}
}
h ^= u64::from(meta.line().unwrap_or(0));
h = h.wrapping_mul(0x0100_0000_01b3);
h ^= h >> 32;
(h as usize) & (CALLSITE_SLOTS - 1)
}
fn allow_event(&self, meta: &Metadata<'_>) -> bool {
if self.state.global_limit_per_sec == 0 && self.state.per_callsite_limit_per_sec == 0 {
return true;
}
let window = self.state.clock.current_window();
// Check per-callsite fairness first so a single stormy site is dropped
// before it can consume the shared global budget reserved for other sites.
if self.state.per_callsite_limit_per_sec > 0 {
let slot = Self::callsite_slot(meta);
if !self.state.callsite_buckets[slot].try_admit(window, self.state.per_callsite_limit_per_sec) {
self.record_drop();
return false;
}
}
if self.state.global_limit_per_sec > 0 && !self.state.global_bucket.try_admit(window, self.state.global_limit_per_sec) {
self.record_drop();
return false;
}
true
}
fn record_drop(&self) {
self.state.dropped_events.fetch_add(1, Ordering::Relaxed);
counter!(METRIC_LOG_CLEANER_SINK_DROPPED_EVENTS_TOTAL).increment(1);
}
}
/// Wrapping [`Layer`] that enforces a [`FileSinkRateLimitFilter`] strictly on
/// `on_event` for its inner file-sink layer while forwarding all span lifecycle
/// hooks untouched.
pub(crate) struct RateLimitedLayer<L> {
inner: L,
limiter: FileSinkRateLimitFilter,
}
impl<L> RateLimitedLayer<L> {
pub(crate) fn new(inner: L, limiter: FileSinkRateLimitFilter) -> Self {
Self { inner, limiter }
}
}
impl<S, L> Layer<S> for RateLimitedLayer<L>
where
S: Subscriber + for<'lookup> LookupSpan<'lookup>,
L: Layer<S>,
{
fn on_register_dispatch(&self, collector: &Dispatch) {
self.inner.on_register_dispatch(collector);
}
fn on_layer(&mut self, subscriber: &mut S) {
self.inner.on_layer(subscriber);
}
fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
self.inner.register_callsite(metadata)
}
fn enabled(&self, metadata: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
self.inner.enabled(metadata, ctx)
}
fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_new_span(attrs, id, ctx);
}
fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) {
self.inner.on_record(span, values, ctx);
}
fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<'_, S>) {
self.inner.on_follows_from(span, follows, ctx);
}
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
if self.limiter.allow_event(event.metadata()) {
self.inner.on_event(event, ctx);
}
}
fn on_enter(&self, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_enter(id, ctx);
}
fn on_exit(&self, id: &span::Id, ctx: Context<'_, S>) {
self.inner.on_exit(id, ctx);
}
fn on_close(&self, id: span::Id, ctx: Context<'_, S>) {
self.inner.on_close(id, ctx);
}
fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<'_, S>) {
self.inner.on_id_change(old, new, ctx);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::telemetry::local::build_json_log_layer;
use std::io;
use std::sync::Mutex;
use tracing_subscriber::{EnvFilter, Registry, fmt::format::FmtSpan, layer::SubscriberExt};
struct ManualClock {
window: Arc<AtomicU64>,
}
impl WindowClock for ManualClock {
fn current_window(&self) -> u64 {
self.window.load(Ordering::Acquire)
}
}
#[derive(Clone, Default)]
struct CaptureWriter {
buf: Arc<Mutex<Vec<u8>>>,
}
struct CaptureGuard(Arc<Mutex<Vec<u8>>>);
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CaptureWriter {
type Writer = CaptureGuard;
fn make_writer(&'a self) -> Self::Writer {
CaptureGuard(Arc::clone(&self.buf))
}
}
impl io::Write for CaptureGuard {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
self.0.lock().expect("capture lock").extend_from_slice(data);
Ok(data.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl CaptureWriter {
fn lines(&self) -> Vec<String> {
let bytes = self.buf.lock().expect("capture lock").clone();
String::from_utf8(bytes)
.expect("valid UTF-8")
.lines()
.map(str::to_owned)
.collect()
}
}
fn test_filter(global: u64, per_callsite: u64) -> (FileSinkRateLimitFilter, Arc<AtomicU64>) {
let clock = Arc::new(AtomicU64::new(0));
let filter = FileSinkRateLimitFilter::with_clock(
global,
per_callsite,
Box::new(ManualClock {
window: Arc::clone(&clock),
}),
);
(filter, clock)
}
#[test]
fn storm_is_capped_per_window_and_recovers_on_next_window() {
let (filter, clock) = test_filter(5, 5);
let file_writer = CaptureWriter::default();
let stdout_writer = CaptureWriter::default();
let file_layer =
RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let stdout_layer = build_json_log_layer(stdout_writer.clone(), false, FmtSpan::NONE, false);
let subscriber = Registry::default().with(file_layer).with(stdout_layer);
tracing::subscriber::with_default(subscriber, || {
for idx in 0..20 {
tracing::error!(idx, "storm event");
}
clock.store(1, Ordering::Release);
for idx in 0..3 {
tracing::error!(idx, "next window event");
}
});
assert_eq!(file_writer.lines().len(), 8, "5 in window 0 + 3 in window 1");
assert_eq!(filter.dropped_events(), 15, "15 excess storm events dropped");
assert_eq!(
stdout_writer.lines().len(),
23,
"sibling stdout layer must not be throttled by file-sink filter"
);
}
#[test]
fn noisy_callsite_cannot_starve_distinct_critical_callsite() {
let (filter, _clock) = test_filter(10, 3);
let file_writer = CaptureWriter::default();
let layer = RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(layer);
tracing::subscriber::with_default(subscriber, || {
let span = tracing::info_span!("req", request_id = "req-42");
let _guard = span.enter();
for i in 0..50 {
tracing::warn!(i, "noisy site");
}
tracing::error!("distinct critical site");
});
let lines = file_writer.lines();
assert_eq!(lines.len(), 4, "3 from noisy site + 1 from critical site");
assert!(
lines
.iter()
.any(|line| line.contains("distinct critical site") && line.contains("req-42")),
"distinct callsite must still be logged with intact span request_id: {lines:?}"
);
assert_eq!(filter.dropped_events(), 47);
}
#[test]
fn upstream_env_filter_rejections_consume_zero_sink_budget() {
let (filter, _clock) = test_filter(2, 2);
let file_writer = CaptureWriter::default();
let file_layer =
RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(EnvFilter::new("error")).with(file_layer);
tracing::subscriber::with_default(subscriber, || {
for _ in 0..10 {
tracing::info!("filtered out upstream");
}
tracing::error!("first real error");
tracing::error!("second real error");
tracing::error!("third real error over budget");
});
assert_eq!(file_writer.lines().len(), 2);
assert_eq!(filter.dropped_events(), 1);
}
#[test]
fn zero_limits_disable_sink_rate_limiting() {
let (filter, _clock) = test_filter(0, 0);
let file_writer = CaptureWriter::default();
let layer = RateLimitedLayer::new(build_json_log_layer(file_writer.clone(), false, FmtSpan::NONE, false), filter.clone());
let subscriber = Registry::default().with(layer);
tracing::subscriber::with_default(subscriber, || {
for idx in 0..25 {
tracing::error!(idx, "unbounded event");
}
});
assert_eq!(file_writer.lines().len(), 25);
assert_eq!(filter.dropped_events(), 0);
}
}
+296 -25
View File
@@ -20,11 +20,12 @@
use crate::cleaner::types::FileMatchMode;
use crate::global::{
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES, METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS,
METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL, METRIC_LOG_CLEANER_ROTATION_TOTAL,
METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES, METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL,
METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS, METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL, METRIC_LOG_CLEANER_ROTATION_TOTAL,
};
use jiff::{Timestamp, ZonedDateTime, tz::TimeZone};
use metrics::{counter, gauge, histogram};
use rustfs_config::observability::DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
@@ -50,6 +51,15 @@ pub enum Rotation {
/// timestamp tick.
static ROLL_UNIQUIFIER: AtomicU64 = AtomicU64::new(0);
const ROTATION_RETRY_COOLDOWN: Duration = Duration::from_secs(5);
const ROTATION_RETRY_MAX_COOLDOWN: Duration = Duration::from_secs(60);
/// Consecutive rotation failures after which the appender tightens its active
/// file hard cap instead of allowing a grace overrun.
const ROTATION_FAILURE_HARD_CAP_STREAK: u32 = 3;
/// Emergency grace active-file byte cap applied immediately on rotation
/// failure when size rolling was explicitly disabled (`max_size_bytes == 0`),
/// tightened to `DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES` once failures
/// reach `ROTATION_FAILURE_HARD_CAP_STREAK`.
const ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES: u64 = DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES.saturating_mul(2);
impl Rotation {
fn check_should_roll(&self, last: i64, now: i64) -> bool {
@@ -86,6 +96,10 @@ pub struct RollingAppender {
// Store as seconds since Unix epoch
last_roll_ts: i64,
rotation_retry_cooldown_until: Option<Instant>,
rotation_retry_base_cooldown: Duration,
consecutive_rotation_failures: u32,
dropped_bytes_due_to_rotation_failure: u64,
shedding_warning_emitted_for_streak: bool,
/// Woken after every successful roll so the cleaner can enforce the
/// directory budget on the file that was just rolled.
roll_signal: Option<Arc<tokio::sync::Notify>>,
@@ -136,11 +150,15 @@ impl RollingAppender {
size: 0,
last_roll_ts: ZonedDateTime::now().timestamp().as_second(),
rotation_retry_cooldown_until: None,
rotation_retry_base_cooldown: ROTATION_RETRY_COOLDOWN,
consecutive_rotation_failures: 0,
dropped_bytes_due_to_rotation_failure: 0,
shedding_warning_emitted_for_streak: false,
roll_signal: None,
};
// Eagerly open the file to validate the path and capture accurate
// initial size / last-roll timestamp.
appender.open_file()?;
appender.open_file(true)?;
Ok(appender)
}
@@ -166,7 +184,7 @@ impl RollingAppender {
Ok((metadata.dev(), metadata.ino()))
}
fn open_file(&mut self) -> io::Result<()> {
fn open_file(&mut self, seed_last_roll_ts: bool) -> io::Result<()> {
if self.file.is_some() {
return Ok(());
}
@@ -188,14 +206,17 @@ impl RollingAppender {
let meta = file.metadata()?;
self.size = meta.len();
// Seed `last_roll_ts` from the file's modification time so that a
// process restart correctly triggers time-based rotation if the active
// file belongs to a previous period.
if let Ok(modified) = meta.modified() {
// Convert SystemTime to jiff::Timestamp
if let Ok(ts) = jiff::Timestamp::try_from(modified) {
self.last_roll_ts = ts.as_second();
}
// Seed `last_roll_ts` from the file's modification time only on initial
// startup so a process restart triggers time-based rotation when the
// active file belongs to a previous period. Reopening after a failed
// rotation must preserve `self.last_roll_ts` so subsequent time-based
// rotation retries continue after backoff instead of stalling for the
// rest of the period.
if seed_last_roll_ts
&& let Ok(modified) = meta.modified()
&& let Ok(ts) = jiff::Timestamp::try_from(modified)
{
self.last_roll_ts = ts.as_second();
}
self.file = Some(file);
@@ -222,7 +243,7 @@ impl RollingAppender {
// 1. Size-based check (Cheap, check first)
// If max_size is set (non-zero) and writing would exceed it, roll immediately.
if self.max_size_bytes > 0 && (self.size + write_len) > self.max_size_bytes {
if self.max_size_bytes > 0 && self.size.saturating_add(write_len) > self.max_size_bytes {
return true;
}
@@ -233,6 +254,45 @@ impl RollingAppender {
self.rotation.check_should_roll(self.last_roll_ts, now)
}
/// Hard ceiling enforced on the active log file while rotation is failing.
///
/// A transient rename failure keeps a bounded grace ceiling (`2 * max_size_bytes`,
/// or `ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES` when size rolling is off)
/// from the first failure so brief filesystem locks do not immediately lose logs
/// while still preventing an uncapped window during backoff. Sustained failures
/// (`>= ROTATION_FAILURE_HARD_CAP_STREAK`) tighten the cap to `max_size_bytes`
/// (or `DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES` when size rolling is off)
/// so an unrotatable file can never exhaust disk space.
fn rotation_failure_hard_cap(&self) -> Option<u64> {
if self.consecutive_rotation_failures == 0 {
return None;
}
if self.max_size_bytes > 0 {
if self.consecutive_rotation_failures >= ROTATION_FAILURE_HARD_CAP_STREAK {
Some(self.max_size_bytes)
} else {
Some(self.max_size_bytes.saturating_mul(2))
}
} else if self.consecutive_rotation_failures >= ROTATION_FAILURE_HARD_CAP_STREAK {
Some(DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES)
} else {
Some(ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES)
}
}
fn record_rotation_failure(&mut self, rotate_started: Instant) {
self.consecutive_rotation_failures = self.consecutive_rotation_failures.saturating_add(1);
self.shedding_warning_emitted_for_streak = false;
let shift = self.consecutive_rotation_failures.saturating_sub(1).min(4);
let backoff = self
.rotation_retry_base_cooldown
.saturating_mul(1u32 << shift)
.min(ROTATION_RETRY_MAX_COOLDOWN);
self.rotation_retry_cooldown_until = Some(Instant::now() + backoff);
counter!(METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
}
fn roll(&mut self) -> io::Result<()> {
let rotate_started = std::time::Instant::now();
// 1. Close current file first to ensure all buffers are flushed to OS (if any)
@@ -241,6 +301,7 @@ impl RollingAppender {
&& let Err(e) = file.flush()
{
eprintln!("Failed to flush log file before rotation: {}", e);
self.record_rotation_failure(rotate_started);
return Err(e);
}
@@ -293,13 +354,15 @@ impl RollingAppender {
self.size = 0;
// 5. Re-open (creates new active file)
self.open_file()?;
self.open_file(false)?;
// Explicitly update last_roll_ts to the rotation time.
// This overrides whatever open_file() derived from mtime, ensuring
// we stick to the logical rotation time.
self.last_roll_ts = now.timestamp().as_second();
self.rotation_retry_cooldown_until = None;
self.consecutive_rotation_failures = 0;
self.shedding_warning_emitted_for_streak = false;
counter!(METRIC_LOG_CLEANER_ROTATION_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
gauge!(METRIC_LOG_CLEANER_ACTIVE_FILE_SIZE_BYTES).set(self.size as f64);
@@ -330,19 +393,18 @@ impl RollingAppender {
}
// 6. Recovery Failure
// If we exhausted retries, we MUST NOT lose log data.
// We re-open the ACTIVE file (which is still there because rename failed).
// The file will grow beyond max_size, but availability > strict sizing.
// Re-open the active file so transient rename errors keep logging up to
// `rotation_failure_hard_cap()`, while sustained failures shed excess
// writes instead of growing the unrotatable file without bound.
eprintln!(
"RollingAppender: Failed to rotate log file after {} retries. Error: {:?}",
MAX_RETRIES, last_error
);
self.rotation_retry_cooldown_until = Some(Instant::now() + ROTATION_RETRY_COOLDOWN);
counter!(METRIC_LOG_CLEANER_ROTATION_FAILURES_TOTAL).increment(1);
histogram!(METRIC_LOG_CLEANER_ROTATION_DURATION_SECONDS).record(rotate_started.elapsed().as_secs_f64());
self.record_rotation_failure(rotate_started);
// Attempt to re-open existing active file to allow continued writing
self.open_file()?;
// without clobbering `last_roll_ts`.
self.open_file(false)?;
// Return the error so it can be logged/handled, even though we recovered the handle.
Err(last_error.unwrap_or_else(|| io::Error::other("Unknown rename error")))
@@ -353,21 +415,38 @@ impl Write for RollingAppender {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
// Ensure file is open
if self.file.is_none() {
self.open_file()?;
self.open_file(false)?;
}
// Check rotation
if self.should_roll(buf.len() as u64)
&& let Err(e) = self.roll()
{
// If rotation fails, we log to stderr and try to continue writing to the active file
// to avoid losing logs if possible.
// If rotation fails, we log to stderr and enforce the rotation-failure
// hard ceiling below instead of allowing unbounded disk growth.
eprintln!("RollingAppender: failed to rotate log file: {}", e);
}
// Shed writes above the active-file hard cap while rotation is broken.
if let Some(hard_cap) = self.rotation_failure_hard_cap()
&& self.size.saturating_add(buf.len() as u64) > hard_cap
{
let dropped = buf.len() as u64;
self.dropped_bytes_due_to_rotation_failure = self.dropped_bytes_due_to_rotation_failure.saturating_add(dropped);
counter!(METRIC_LOG_CLEANER_ROTATION_DROPPED_BYTES_TOTAL).increment(dropped);
if !self.shedding_warning_emitted_for_streak {
self.shedding_warning_emitted_for_streak = true;
eprintln!(
"RollingAppender: rotation failed {} consecutive times; shedding writes above {} bytes (active size {} bytes, total shed {} bytes) until rotation recovers",
self.consecutive_rotation_failures, hard_cap, self.size, self.dropped_bytes_due_to_rotation_failure
);
}
return Ok(buf.len());
}
// Ensure file is open (in case roll closed it and failed to open new one, or open_file failed above)
if self.file.is_none() {
self.open_file()?;
self.open_file(false)?;
}
if let Some(file) = &mut self.file {
@@ -724,4 +803,196 @@ mod tests {
assert!(!appender.should_roll(1));
}
#[test]
fn continuous_rotation_failure_caps_active_file_growth_and_recovers() {
let tmp = TempDir::new().expect("temp dir");
let max_size = 64u64;
let mut appender =
RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Never, max_size, FileMatchMode::Suffix)
.expect("create appender");
appender.rotation_retry_base_cooldown = Duration::from_millis(1);
// Fill active file to max_size.
appender.write_all(&[b'a'; 64]).expect("initial write");
assert_eq!(appender.size, 64);
// Simulate a transient first rotation failure: grace cap is 2 * max_size (128 bytes).
appender.record_rotation_failure(Instant::now());
appender.rotation_retry_cooldown_until = Some(Instant::now() + Duration::from_secs(60));
assert_eq!(appender.rotation_failure_hard_cap(), Some(128));
// 32 bytes fit within the 2x grace window.
appender.write_all(&[b'b'; 32]).expect("grace write");
assert_eq!(appender.size, 96);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 0);
// Additional writes that would exceed 2 * max_size must be shed instead of growing disk.
for _ in 0..100 {
appender.write_all(&[b'c'; 64]).expect("shedding returns Ok");
}
appender.flush().expect("flush");
assert!(
fs::metadata(tmp.path().join("app.log")).expect("active meta").len() <= 2 * max_size,
"active file must never exceed 2x max_size while rotation is failing"
);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 100 * 64);
// Sustained streak (>= 3) tightens cap down to max_size.
appender.record_rotation_failure(Instant::now());
appender.record_rotation_failure(Instant::now());
assert_eq!(appender.rotation_failure_hard_cap(), Some(max_size));
// Once cooldown expires and filesystem allows rename again, rotation recovers cleanly.
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"recovered\n").expect("recovered write");
appender.flush().expect("flush after recovery");
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(appender.rotation_failure_hard_cap(), None);
assert_eq!(fs::read_to_string(tmp.path().join("app.log")).expect("read active"), "recovered\n");
assert_eq!(count_files(tmp.path()), 2, "recovered rotation must archive previous active file");
}
#[cfg(unix)]
#[test]
fn readonly_directory_rotation_failure_stops_unbounded_file_growth() -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
let tmp = TempDir::new()?;
let max_size = 64u64;
let mut appender =
RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Never, max_size, FileMatchMode::Suffix)?;
appender.rotation_retry_base_cooldown = Duration::from_secs(60);
appender.write_all(&[b'x'; 64])?;
appender.flush()?;
// Make the directory non-writable (0o555) while keeping app.log writable (0o644):
// rename() fails with PermissionDenied, while reopening app.log in append mode succeeds.
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o555))?;
// Privileged users (e.g. root in containers) bypass POSIX directory write bits.
if File::create(tmp.path().join(".write-probe")).is_ok() {
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o755))?;
return Ok(());
}
let write_res = (|| -> io::Result<()> {
for _ in 0..200 {
appender.write_all(&[b'y'; 64])?;
}
appender.flush()
})();
// Always restore directory permissions before asserting / dropping TempDir.
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o755))?;
write_res?;
let final_len = fs::metadata(tmp.path().join("app.log"))?.len();
assert!(
final_len <= 2 * max_size,
"active file grew to {final_len} bytes under continuous rotation failure (cap {})",
2 * max_size
);
assert!(appender.consecutive_rotation_failures >= 1, "rotation failure must be recorded");
assert!(
appender.dropped_bytes_due_to_rotation_failure > 0,
"excess writes must be shed while directory prevents rotation"
);
// Directory is writable again; expire cooldown and verify clean recovery.
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"after-recovery\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(fs::read_to_string(tmp.path().join("app.log"))?, "after-recovery\n");
Ok(())
}
#[cfg(unix)]
#[test]
fn time_based_rotation_failure_preserves_last_roll_ts_and_caps_when_max_size_zero() -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
struct RestoreDirPerms<'a>(&'a Path);
impl Drop for RestoreDirPerms<'_> {
fn drop(&mut self) {
let _ = fs::set_permissions(self.0, fs::Permissions::from_mode(0o755));
}
}
let tmp = TempDir::new()?;
let mut appender = RollingAppender::new(tmp.path(), "app.log".to_string(), Rotation::Hourly, 0, FileMatchMode::Suffix)?;
appender.rotation_retry_base_cooldown = Duration::from_secs(60);
appender.write_all(b"seed\n")?;
appender.flush()?;
// Wind `last_roll_ts` back two hours so time-based rotation is due.
let original_last_roll_ts = ZonedDateTime::now().timestamp().as_second() - 7200;
appender.last_roll_ts = original_last_roll_ts;
let _restore = RestoreDirPerms(tmp.path());
fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o555))?;
if File::create(tmp.path().join(".write-probe")).is_ok() {
return Ok(());
}
// Failure #1: `open_file(false)` must NOT clobber `last_roll_ts`, and a
// bounded emergency ceiling must apply immediately from failure #1.
appender.write_all(b"after-failure-1\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 1);
assert_eq!(
appender.last_roll_ts, original_last_roll_ts,
"failed rotation reopen must preserve last_roll_ts so time-based retries keep firing"
);
assert_eq!(
appender.rotation_failure_hard_cap(),
Some(ROTATION_FAILURE_UNBOUNDED_FALLBACK_CAP_BYTES),
"max_size_bytes == 0 must enforce a bounded grace cap starting on failure #1"
);
// Expire cooldown and retry twice more; `should_roll` must still fire
// even though the write above updated app.log's mtime to the current hour.
for expected_failures in [2u32, 3u32] {
appender.rotation_retry_cooldown_until = None;
assert!(
appender.should_roll(1),
"time-based rotation must remain due after failure #{}",
expected_failures - 1
);
appender.write_all(b"retry-write\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, expected_failures);
assert_eq!(appender.last_roll_ts, original_last_roll_ts);
}
// Sustained failure (>= 3) tightens the fallback cap and sheds excess writes.
assert_eq!(appender.rotation_failure_hard_cap(), Some(DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES));
let pre_shed_len = fs::metadata(tmp.path().join("app.log"))?.len();
appender.size = DEFAULT_OBS_LOG_ACTIVE_FILE_ROLL_SIZE_BYTES;
appender.write_all(&[b'z'; 64])?;
appender.flush()?;
assert_eq!(
fs::metadata(tmp.path().join("app.log"))?.len(),
pre_shed_len,
"writes exceeding tightened fallback cap must be shed without disk growth"
);
assert_eq!(appender.dropped_bytes_due_to_rotation_failure, 64);
// Restore writability, expire cooldown, and verify clean time-based recovery.
drop(_restore);
appender.size = pre_shed_len;
appender.rotation_retry_cooldown_until = None;
appender.write_all(b"recovered-hourly\n")?;
appender.flush()?;
assert_eq!(appender.consecutive_rotation_failures, 0);
assert_eq!(appender.rotation_failure_hard_cap(), None);
assert!(
appender.last_roll_ts > original_last_roll_ts,
"successful recovery rotation must advance last_roll_ts"
);
assert_eq!(fs::read_to_string(tmp.path().join("app.log"))?, "recovered-hourly\n");
assert_eq!(count_files(tmp.path()), 2);
Ok(())
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,271 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::*;
use std::future::Future;
use std::pin::Pin;
/// Poll `future` in its own frame.
///
/// A direct `.await` can inline the child state machine into the caller. Debug
/// scanner frames are large enough that fusing them overflows the 4 MiB stack
/// used by scanner tests. Trait-object dispatch keeps each frame separate.
pub(super) fn poll_apart<'a, F>(future: F) -> Pin<Box<dyn Future<Output = F::Output> + Send + 'a>>
where
F: Future + Send + 'a,
{
Box::pin(future)
}
/// The current folder owns its accumulator even when its parent lent it a compacted total.
pub(super) struct FolderFrame {
pub(super) folder: CachedFolder,
pub(super) mode: FolderScanMode,
pub(super) hash: DataUsageHash,
pub(super) entry: DataUsageEntry,
pub(super) was_compacted: bool,
pub(super) started: Instant,
pub(super) trace_started_at: Option<Instant>,
}
impl FolderFrame {
fn new(folder: CachedFolder, entry: DataUsageEntry, mode: FolderScanMode) -> Self {
Self {
mode,
hash: hash_path(&folder.name),
folder,
was_compacted: entry.compacted,
entry,
started: Instant::now(),
trace_started_at: trace_start_instant(),
}
}
}
pub(super) struct FolderListing {
pub(super) dir_reader: Option<ScannerDirectory>,
pub(super) queued_folders: std::vec::IntoIter<QueuedFolder>,
pub(super) acknowledge_previous: Option<(String, bool)>,
pub(super) force_compact: bool,
pub(super) isolate_compacted_children: bool,
pub(super) found_object_metadata: bool,
pub(super) forward_sweep: bool,
pub(super) active_life_cycle: Option<Arc<rustfs_gateway_types::persistence::PersistedLifecycleConfiguration>>,
pub(super) abandoned_children: DataUsageHashMap,
pub(super) healing: Option<AbandonedFolders>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum ChildAccounting {
Linked,
Shared,
Summary { isolated: bool },
}
pub(super) enum ChildOrigin {
Queued,
Abandoned(tokio_util::sync::DropGuard),
}
pub(super) struct ChildRequest {
pub(super) folder: CachedFolder,
pub(super) mode: FolderScanMode,
pub(super) accounting: ChildAccounting,
pub(super) origin: ChildOrigin,
}
pub(super) enum WalkAction {
Enter(bool),
Advance(Box<FolderListing>),
Descend(Box<FolderListing>, ChildRequest),
Finish,
Return(Result<FolderScanOutcome, ScannerError>),
}
struct SuspendedFolder {
frame: FolderFrame,
listing: Box<FolderListing>,
accounting: ChildAccounting,
origin: ChildOrigin,
checkpointed: bool,
suspended_updates: Option<ScannerUsageUpdates>,
}
impl FolderScanner {
pub(super) fn suspend_checkpoint_parent(
&mut self,
hash: &mut DataUsageHash,
entry: &mut DataUsageEntry,
) -> Result<bool, ScannerError> {
if self.checkpoint_tx.is_none() || self.old_cache.info.scan_progress.is_none() {
return Ok(false);
}
let depth = self.checkpoint_depth;
if depth >= MAX_DATA_USAGE_CACHE_DEPTH {
return Err(ScannerError::Other("scanner checkpoint ancestor depth limit exceeded".to_string()));
}
if self.checkpoint_ancestors.len() == depth {
self.checkpoint_ancestors.push(ScannerCheckpointAncestor::default());
}
let slot = &mut self.checkpoint_ancestors[depth];
std::mem::swap(hash, &mut slot.hash);
std::mem::swap(entry, &mut slot.entry);
self.checkpoint_depth += 1;
Ok(true)
}
#[inline(never)]
async fn advance_folder(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
mut listing: Box<FolderListing>,
) -> Result<WalkAction, ScannerError> {
if listing.healing.is_none() {
if let Some(child) = poll_apart(self.next_queued_child(ctx, frame, &mut listing)).await? {
return Ok(WalkAction::Descend(listing, child));
}
if !poll_apart(self.prepare_abandoned_children(ctx, frame, &mut listing)).await? {
return Ok(WalkAction::Finish);
}
}
if let Some(abandoned) = &mut listing.healing
&& let Some((folder, guard)) = poll_apart(self.next_abandoned_child(ctx, frame, abandoned)).await?
{
let accounting = if frame.entry.compacted {
ChildAccounting::Shared
} else {
ChildAccounting::Linked
};
return Ok(WalkAction::Descend(
listing,
ChildRequest {
folder,
mode: FolderScanMode::Namespace,
accounting,
origin: ChildOrigin::Abandoned(guard),
},
));
}
Ok(WalkAction::Finish)
}
#[inline(never)]
pub(super) async fn scan_folder_inner(
&mut self,
ctx: CancellationToken,
folder: CachedFolder,
into: &mut DataUsageEntry,
mode: FolderScanMode,
isolate_compacted_namespace_errors: bool,
) -> Result<FolderScanOutcome, ScannerError> {
let mut parents = Vec::<SuspendedFolder>::new();
// A compacted child borrows the entire parent accumulator. Reuse the
// empty replacement across siblings, including its histogram allocations.
let mut shared_slots = Vec::new();
let mut current = FolderFrame::new(folder, std::mem::take(into), mode);
let mut action = WalkAction::Enter(isolate_compacted_namespace_errors);
loop {
#[cfg(test)]
tests::checkpoint_fixture::deep_compacted::observe_folder_frame_depth(parents.len() + 1);
action = match action {
WalkAction::Enter(isolate) => poll_apart(self.enumerate_folder(&ctx, &mut current, isolate)).await,
WalkAction::Advance(listing) => poll_apart(self.advance_folder(&ctx, &mut current, listing)).await,
WalkAction::Finish => Ok(WalkAction::Return(poll_apart(self.finish_folder(&ctx, &mut current)).await)),
WalkAction::Descend(listing, child) => {
let checkpoint = if child.accounting == ChildAccounting::Linked {
self.suspend_checkpoint_parent(&mut current.hash, &mut current.entry)
} else {
Ok(false)
};
let isolated = child.accounting == ChildAccounting::Summary { isolated: true };
let suspended_updates = if isolated { self.usage_updates.take() } else { None };
let entry = match child.accounting {
ChildAccounting::Shared => std::mem::replace(&mut current.entry, shared_slots.pop().unwrap_or_default()),
ChildAccounting::Linked => DataUsageEntry::default(),
ChildAccounting::Summary { .. } => DataUsageEntry {
compacted: true,
..Default::default()
},
};
parents.push(SuspendedFolder {
frame: current,
listing,
accounting: child.accounting,
origin: child.origin,
checkpointed: matches!(checkpoint, Ok(true)),
suspended_updates,
});
current = FolderFrame::new(child.folder, entry, child.mode);
checkpoint.map(|_| WalkAction::Enter(isolated))
}
WalkAction::Return(result) => {
Metrics::inc_time(Metric::ScanFolder, current.started.elapsed());
let Some(mut parent) = parents.pop() else {
*into = current.entry;
return result;
};
if parent.checkpointed {
self.checkpoint_depth -= 1;
let slot = &mut self.checkpoint_ancestors[self.checkpoint_depth];
std::mem::swap(&mut parent.frame.hash, &mut slot.hash);
std::mem::swap(&mut parent.frame.entry, &mut slot.entry);
}
if parent.accounting == ChildAccounting::Shared {
std::mem::swap(&mut parent.frame.entry, &mut current.entry);
}
if parent.accounting == (ChildAccounting::Summary { isolated: true }) {
self.usage_updates = parent.suspended_updates;
}
// Settle even errors from entering a child: the parent owns the
// decision to propagate a partial result or isolate a coverage gap.
let resume = match parent.origin {
ChildOrigin::Queued => {
poll_apart(self.accept_queued_child(
&ctx,
&mut parent.frame,
&mut parent.listing,
&current,
parent.accounting,
result,
))
.await
}
ChildOrigin::Abandoned(_cancel_on_exit) => poll_apart(self.accept_abandoned_child(
&ctx,
&mut parent.frame,
&current,
result,
parent.accounting == ChildAccounting::Shared,
))
.await
.map(|()| true),
};
if parent.accounting == ChildAccounting::Shared {
shared_slots.push(current.entry);
}
current = parent.frame;
resume.map(|more| {
if more {
WalkAction::Advance(parent.listing)
} else {
WalkAction::Finish
}
})
}
}
.unwrap_or_else(|error| WalkAction::Return(Err(error)));
}
}
}
@@ -0,0 +1,451 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::*;
use tokio_util::sync::DropGuard;
pub(super) struct AbandonedFolders {
names: std::collections::hash_set::IntoIter<String>,
previous_bucket: String,
}
impl AbandonedFolders {
pub(super) fn new(names: HashSet<String>) -> Self {
Self {
names: names.into_iter(),
previous_bucket: String::new(),
}
}
}
impl FolderScanner {
#[inline(never)]
pub(super) async fn next_abandoned_child(
&mut self,
ctx: &CancellationToken,
frame: &FolderFrame,
abandoned: &mut AbandonedFolders,
) -> Result<Option<(CachedFolder, DropGuard)>, ScannerError> {
for name in abandoned.names.by_ref() {
if !self.try_should_heal().await? {
break;
}
let (bucket, prefix) = path2_bucket_object(&name);
if bucket != abandoned.previous_bucket {
self.send_required_scanner_heal_request(
PendingScannerHealKind::Bucket,
bucket.clone(),
None,
None,
build_bucket_heal_request(bucket.clone(), HealChannelPriority::High),
)
.await?;
abandoned.previous_bucket.clone_from(&bucket);
}
let child_ctx = ctx.child_token();
let cancel_on_exit = child_ctx.clone().drop_guard();
if self.discover_abandoned_child(child_ctx.clone(), bucket, prefix).await? {
let child = CachedFolder {
name,
parent: Some(frame.hash.clone()),
object_heal_prob_div: 1,
};
return Ok(Some((child, cancel_on_exit)));
}
}
Ok(None)
}
#[inline(never)]
pub(super) async fn accept_abandoned_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
child: &FolderFrame,
result: Result<FolderScanOutcome, ScannerError>,
shared: bool,
) -> Result<(), ScannerError> {
if shared {
result?;
self.send_update_for_entry(&frame.hash, &frame.folder.parent, &frame.entry)
.await;
tokio::task::yield_now().await;
return Ok(());
}
if let Err(error) = result {
if matches!(error, ScannerError::SourceUnavailable(_)) {
return Err(error);
}
if ctx.is_cancelled() || matches!(&error, ScannerError::ResourceDeferred) {
self.preserve_partial_child_progress(&child.folder.parent, &child.hash, &mut frame.entry, &child.entry)
.await;
return Err(error);
}
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
folder = %frame.folder.name,
child_folder = %child.folder.name,
state = "heal_child_scan_failed",
error = %error,
"Scanner heal child folder scan failed"
);
return Ok(());
}
tokio::task::yield_now().await;
frame.entry.add_child(&child.hash);
self.refresh_usage_subtree(&child.hash, &child.folder.parent);
self.send_update().await;
self.maybe_send_checkpoint(&frame.folder, &frame.hash, &frame.entry);
Ok(())
}
#[inline(never)]
async fn discover_abandoned_child(
&mut self,
child_ctx: CancellationToken,
bucket: String,
prefix: String,
) -> Result<bool, ScannerError> {
let (agreed_tx, mut agreed_rx) = mpsc::channel::<String>(1);
let (partial_tx, mut partial_rx) = mpsc::channel::<MetaCacheEntries>(1);
let (finished_tx, mut finished_rx) = mpsc::channel::<Vec<Option<DiskError>>>(1);
let disks = self.disks.iter().cloned().map(Some).collect();
let disks_quorum = self.disks_quorum;
let bucket_clone = bucket.clone();
let prefix_clone = prefix.clone();
let child_ctx_clone = child_ctx.clone();
#[cfg(test)]
let list_path_raw_options_observer = self.list_path_raw_options_observer.clone();
tokio::spawn(async move {
let options = ListPathRawOptions {
disks,
bucket: bucket_clone.clone(),
path: prefix_clone.clone(),
recursive: true,
report_not_found: true,
min_disks: disks_quorum,
agreed: Some(Box::new(move |entry: MetaCacheEntry| {
let entry_name = entry.name.clone();
let agreed_tx = agreed_tx.clone();
Box::pin(async move {
if let Err(e) = agreed_tx.send(entry_name).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
entry = %entry.name,
state = "list_path_agreed_send_failed",
error = %e,
"Scanner list_path_raw agreed callback failed"
);
}
Ok(())
})
})),
partial: Some(Box::new(move |entries: MetaCacheEntries, _: &[Option<DiskError>]| {
let partial_tx = partial_tx.clone();
Box::pin(async move {
if let Err(e) = partial_tx.send(entries).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_partial_send_failed",
error = %e,
"Scanner list_path_raw partial callback failed"
);
}
})
})),
finished: Some(Box::new(move |errs: &[Option<DiskError>]| {
let finished_tx = finished_tx.clone();
let errs_clone = errs.to_vec();
Box::pin(async move {
if let Err(e) = finished_tx.send(errs_clone).await {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_send_failed",
error = %e,
"Scanner list_path_raw finished callback failed"
);
}
})
})),
..scanner_abandoned_child_list_options()
};
#[cfg(test)]
if let Some(observer) = list_path_raw_options_observer {
let _ =
observer.send((options.skip_walkdir_total_timeout, options.walkdir_timeout, options.walkdir_stall_timeout));
}
if let Err(e) = crate::storage_api::ecstore_with_background_disk_io(
child_ctx_clone.clone(),
list_path_raw(child_ctx_clone.clone(), options),
)
.await
{
if is_missing_path_disk_error(&e) {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
bucket = %bucket_clone,
prefix = %prefix_clone,
state = "list_path_missing",
error = %e,
"Scanner list_path_raw missing path skipped"
);
} else {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
bucket = %bucket_clone,
prefix = %prefix_clone,
state = "list_path_failed",
error = %e,
"Scanner list_path_raw failed"
);
}
}
});
let mut found_objects = false;
let mut agreed_closed = false;
let mut partial_closed = false;
let mut finished_closed = false;
let mut seen_heal_candidates: HashSet<(String, Option<String>, MetaCacheHealCandidateKind)> = HashSet::new();
let mut seen_truncated_objects: HashSet<String> = HashSet::new();
loop {
if child_ctx.is_cancelled() || (agreed_closed && partial_closed && finished_closed) {
break;
}
#[cfg(test)]
let defer_entries = self.defer_abandoned_entries_until_finished && !finished_closed;
#[cfg(not(test))]
let defer_entries = false;
select! {
entry_name = agreed_rx.recv(), if !agreed_closed && !defer_entries => {
let Some(entry_name) = entry_name else {
agreed_closed = true;
continue;
};
(self.update_current_path)(&entry_name).await;
}
entries = partial_rx.recv(), if !partial_closed && !defer_entries => {
let Some(entries) = entries else {
partial_closed = true;
continue;
};
if !self.try_should_heal().await? {
child_ctx.cancel();
break;
}
#[cfg(test)]
let candidate_limit = self.partial_heal_candidate_limit.unwrap_or(MAX_META_CACHE_HEAL_CANDIDATES);
#[cfg(not(test))]
let candidate_limit = MAX_META_CACHE_HEAL_CANDIDATES;
let discovery = entries.discover_heal_candidates(&bucket, candidate_limit);
#[cfg(test)]
if let Some(observer) = &self.partial_heal_discovery_observer {
let _ = observer.send((discovery.candidates.len(), discovery.truncated_candidates.len()));
}
counter!(METRIC_SCANNER_HEAL_DISCOVERY_CANDIDATES_TOTAL)
.increment(u64::try_from(discovery.candidates.len()).unwrap_or(u64::MAX));
counter!(METRIC_SCANNER_HEAL_DISCOVERY_SUB_QUORUM_TOTAL).increment(
u64::try_from(
discovery
.candidates
.iter()
.filter(|candidate| candidate.replica_count < disks_quorum)
.count(),
)
.unwrap_or(u64::MAX),
);
counter!(METRIC_SCANNER_HEAL_DISCOVERY_UNVERIFIED_TOTAL).increment(
u64::try_from(discovery.unverified_count).unwrap_or(u64::MAX),
);
if discovery.truncated {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_TRUNCATED_TOTAL).increment(1);
}
for candidate in discovery.candidates {
let sub_quorum_candidate = candidate.replica_count < disks_quorum;
let version_id = candidate.validated_version().map(|id| id.to_string());
let identity = (candidate.object.clone(), version_id.clone(), candidate.kind.clone());
if seen_heal_candidates.len() >= MAX_META_CACHE_HEAL_CANDIDATES
&& !seen_heal_candidates.contains(&identity)
{
continue;
}
if !seen_heal_candidates.insert(identity) {
continue;
}
let request = if candidate.is_unversioned() {
build_non_destructive_object_heal_request(
bucket.clone(),
candidate.object.clone(),
self.scan_mode,
HealChannelPriority::High,
)
} else {
build_object_heal_request(
bucket.clone(),
candidate.object.clone(),
version_id.clone(),
self.scan_mode,
HealChannelPriority::High,
)
};
(self.update_current_path)(&candidate.object).await;
let admission = self.send_required_scanner_heal_request(
PendingScannerHealKind::Object,
bucket.clone(),
Some(candidate.object.clone()),
version_id.clone(),
request,
)
.await?;
if admission.is_admitted() {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_QUEUED_TOTAL).increment(1);
} else if sub_quorum_candidate {
self.mark_pending_scanner_heal_reason(
PendingScannerHealKind::Object,
&bucket,
Some(&candidate.object),
version_id.as_deref(),
"sub_quorum_metadata",
);
}
found_objects = true;
}
// Candidates beyond the main cap remain exact
// version requests; never downgrade them to a
// latest-version (version_id=None) heal.
for candidate in discovery.truncated_candidates {
let version_id = candidate.validated_version().map(|id| id.to_string());
let identity = (candidate.object.clone(), version_id.clone(), candidate.kind.clone());
if seen_truncated_objects.len() >= MAX_META_CACHE_HEAL_TRUNCATED_OBJECTS
&& !seen_truncated_objects.contains(&candidate.object)
{
continue;
}
seen_truncated_objects.insert(candidate.object.clone());
if !seen_heal_candidates.insert(identity) {
continue;
}
let request = if candidate.is_unversioned() {
build_non_destructive_object_heal_request(
bucket.clone(),
candidate.object.clone(),
self.scan_mode,
HealChannelPriority::High,
)
} else {
build_object_heal_request(
bucket.clone(),
candidate.object.clone(),
version_id.clone(),
self.scan_mode,
HealChannelPriority::High,
)
};
(self.update_current_path)(&candidate.object).await;
let admission = self
.send_required_scanner_heal_request(
PendingScannerHealKind::Object,
bucket.clone(),
Some(candidate.object.clone()),
version_id,
request,
)
.await?;
if admission.is_admitted() {
counter!(METRIC_SCANNER_HEAL_DISCOVERY_QUEUED_TOTAL).increment(1);
}
found_objects = true;
}
}
errs = finished_rx.recv(), if !finished_closed => {
let Some(errs) = errs else {
finished_closed = true;
continue;
};
finished_closed = true;
// The callback preserves the input disk order. A failing sibling does
// not invalidate this walk, but the selected source's rejection does.
if let Some(error) = self.disks.iter().position(|disk| Arc::ptr_eq(disk, &self.local_disk))
.and_then(|idx| errs.get(idx)).and_then(Option::as_ref)
{
let error = StorageError::from(error.clone());
if is_scanner_source_unavailable(&error) {
return Err(ScannerError::source_unavailable(error));
}
}
if disk_errors_are_only_missing_paths(&errs) {
debug!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_missing_paths",
errors = ?errs,
"Scanner list_path_raw finished with missing paths"
);
} else {
error!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "list_path_finished_with_errors",
errors = ?errs,
"Scanner list_path_raw finished with disk errors"
);
}
// The producer awaited callback sends, not their
// consumption. Drain the remaining candidate and
// agreed frames before closing this child walk.
}
_ = child_ctx.cancelled() => {
break;
}
}
}
Ok(found_objects)
}
}
@@ -0,0 +1,330 @@
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::folder_walk::{ChildAccounting, ChildOrigin, ChildRequest};
use super::*;
impl FolderScanner {
#[inline(never)]
pub(super) async fn next_queued_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
listing: &mut FolderListing,
) -> Result<Option<ChildRequest>, ScannerError> {
let folder = &frame.folder;
let this_hash = &frame.hash;
let into = &mut frame.entry;
let mut work = listing.dir_reader.as_mut().and_then(ScannerDirectory::work);
loop {
if let Some(work) = &mut work
&& let Some((name, linked)) = listing.acknowledge_previous.take()
{
work.gap |= self.coverage_gap;
work.acknowledge(&name, linked, into.compacted);
}
if ctx.is_cancelled() {
return Err(ScannerError::Other("Operation cancelled".to_string()));
}
let queued_folder = if let Some(work) = &mut work {
let Some(name) =
wait_for_scanner_io(ctx, run_scanner_node_operation(self.node_admission.as_ref(), ctx, work.next_name()))
.await???
else {
return Ok(None);
};
let name = path_join_buf(&[&folder.name, &name]);
let source = if !listing.force_compact && self.old_cache.find(&name).is_some() {
FolderScanSource::Existing
} else {
FolderScanSource::New
};
let h = hash_path(&name);
if source == FolderScanSource::Existing
&& let Some(updates) = &mut self.usage_updates
{
updates
.cache
.copy_with_children(&self.old_cache, &h, &Some(this_hash.clone()));
}
QueuedFolder {
folder: CachedFolder {
name,
parent: Some(this_hash.clone()),
object_heal_prob_div: folder.object_heal_prob_div,
},
source,
}
} else {
let Some(queued) = listing.queued_folders.next() else { return Ok(None) };
queued
};
let mut folder_item = queued_folder.folder;
let h = hash_path(&folder_item.name);
if work.is_some() {
listing.acknowledge_previous = Some((folder_item.name.clone(), false));
}
if work.is_some()
&& queued_folder.source == FolderScanSource::Existing
&& self.can_reuse_scoped_child(folder, into, &folder_item.name, &h)
{
self.reuse_clean_root_child(&folder_item, &h, into);
if let Some((_, linked)) = &mut listing.acknowledge_previous {
*linked = true;
}
continue;
}
let reuse_covered = self.can_reuse_covered_namespace(&folder_item.name, into.compacted);
let mut child_mode = if self.is_erasure_mode && is_erasure_candidate(&folder_item.name) {
FolderScanMode::ErasureCandidate {
reuse_namespace: reuse_covered,
parent_has_metadata: listing.found_object_metadata,
}
} else {
FolderScanMode::Namespace
};
if child_mode == FolderScanMode::Namespace && reuse_covered {
let started = Instant::now();
self.new_cache.copy_with_children(&self.old_cache, &h, &folder_item.parent);
into.add_child(&h);
if let Some((_, linked)) = &mut listing.acknowledge_previous {
*linked = true;
}
global_metrics()
.scan_observation()
.record_cache_reuse(ScannerCacheReuseKind::CoveredNamespace, started.elapsed());
continue;
}
match queued_folder.source {
FolderScanSource::New => {
// Add new folders to the update tree so totals update for these.
if !into.compacted
&& let Some(updates) = &mut self.usage_updates
{
let mut found_any = false;
let mut parent = clone_cache_value(this_hash);
let update_root_hash = hash_path(&updates.cache.info.name);
while parent != update_root_hash {
let parent_key = clone_cache_value(&parent.0);
let e = updates.cache.find(&parent_key);
if e.is_none_or(|v| v.compacted) {
found_any = true;
break;
}
if let Some(next) = updates.cache.search_parent(&parent) {
parent = next;
} else {
found_any = true;
break;
}
}
if !found_any {
// Add non-compacted empty entry.
updates
.cache
.replace_hashed(&h, &Some(clone_cache_value(this_hash)), &DataUsageEntry::default());
}
}
}
FolderScanSource::Existing => {
// Lifecycle evaluation must still visit matching prefixes between usage samples.
let has_lifecycle_work = listing.active_life_cycle.as_ref().is_some_and(|config| {
let (_, prefix) = path2_bucket_object_with_base_path(&self.root, &folder_item.name);
config.has_active_rules(&prefix)
});
if !has_lifecycle_work
&& self.new_cache.info.size_reconciliation.is_empty()
&& let Some(reuse) = self.sampled_namespace_reuse(&h, into.compacted, listing.forward_sweep)
{
if reuse {
if child_mode == FolderScanMode::Namespace {
let started = Instant::now();
self.new_cache.copy_with_children(&self.old_cache, &h, &folder_item.parent);
into.add_child(&h);
global_metrics()
.scan_observation()
.record_cache_reuse(ScannerCacheReuseKind::SampledNamespace, started.elapsed());
self.record_scan_resume_hint(&folder_item.name);
continue;
}
// Sampling may skip namespace work, never the
// classification that protects its parent object.
child_mode = FolderScanMode::ErasureCandidate {
reuse_namespace: true,
parent_has_metadata: listing.found_object_metadata,
};
} else {
folder_item.object_heal_prob_div = data_usage_update_dir_cycles();
}
}
}
}
(self.update_current_path)(&folder_item.name).await;
// Keep a compacted namespace child's accounting local until it
// succeeds. Ordinary child errors can then discard it without
// rolling back totals already committed by healthy siblings.
let isolate_compacted_child =
into.compacted && listing.isolate_compacted_children && child_mode == FolderScanMode::Namespace;
// A parked queue owns only committed subtree totals. Run the
// active child in its own accumulator so cancellation cannot
// count a partial child twice at the next admission.
let child_summary = isolate_compacted_child || (into.compacted && work.is_some());
let accounting = if child_summary {
ChildAccounting::Summary {
isolated: isolate_compacted_child,
}
} else if into.compacted {
ChildAccounting::Shared
} else {
ChildAccounting::Linked
};
return Ok(Some(ChildRequest {
folder: folder_item,
mode: child_mode,
accounting,
origin: ChildOrigin::Queued,
}));
}
}
#[inline(never)]
pub(super) async fn accept_queued_child(
&mut self,
ctx: &CancellationToken,
frame: &mut FolderFrame,
listing: &mut FolderListing,
child: &FolderFrame,
accounting: ChildAccounting,
result: Result<FolderScanOutcome, ScannerError>,
) -> Result<bool, ScannerError> {
let into = &mut frame.entry;
let folder = &frame.folder;
let this_hash = &frame.hash;
let folder_item = &child.folder;
let h = &child.hash;
let child_mode = child.mode;
let mut work = listing.dir_reader.as_mut().and_then(ScannerDirectory::work);
let outcome = match (accounting, result) {
(ChildAccounting::Shared, result) => result?,
(ChildAccounting::Summary { .. }, Ok(outcome)) => {
into.merge(&child.entry);
if let Some(work) = &mut work {
if outcome == FolderScanOutcome::Namespace && !self.coverage_gap && child.entry.failed_objects == 0 {
work.compacted_total.merge(&child.entry);
work.acknowledge(&folder_item.name, false, true);
} else if child.entry.failed_objects != 0 {
self.coverage_gap = true;
}
}
outcome
}
(ChildAccounting::Linked, Ok(outcome)) => outcome,
(accounting, Err(error)) => {
if matches!(error, ScannerError::SourceUnavailable(_)) {
return Err(error);
}
if ctx.is_cancelled() || matches!(&error, ScannerError::ResourceDeferred) {
if matches!(accounting, ChildAccounting::Summary { .. }) {
// Cancellation and resource deferral keep completed
// work even though the child has not finished.
into.merge(&child.entry);
} else {
self.preserve_partial_child_progress(&folder_item.parent, h, into, &child.entry)
.await;
}
return Err(error);
}
if child_mode != FolderScanMode::Namespace
|| (into.compacted && !matches!(accounting, ChildAccounting::Summary { isolated: true }))
{
return Err(error);
}
warn!(
target: "rustfs::scanner::folder",
event = EVENT_SCANNER_FOLDER_STATE,
component = LOG_COMPONENT_SCANNER,
subsystem = LOG_SUBSYSTEM_FOLDER,
state = "child_scan_failed",
folder = %folder.name,
child_folder = %folder_item.name,
error = %error,
"Scanner child folder scan failed"
);
// A skipped namespace is a coverage gap even when no
// checkpointed forward sweep is active.
self.coverage_gap = true;
self.finish_raw_enumeration_parent(&folder_item.name);
return Ok(true);
}
};
self.finish_raw_enumeration_parent(&folder_item.name);
if outcome == FolderScanOutcome::Vanished {
self.new_cache.delete_recursive(h);
if let Some(updates) = &mut self.usage_updates {
updates.cache.delete_recursive(h);
}
into.children.remove(&clone_cache_value(&h.0));
return Ok(true);
}
if outcome == FolderScanOutcome::ErasureData {
self.new_cache.delete_recursive(h);
if let Some(updates) = &mut self.usage_updates {
updates.cache.delete_recursive(h);
}
into.children.remove(&clone_cache_value(&h.0));
// Object keys can also be prefixes. A classified payload
// directory must not hide their other namespace children.
if listing.found_object_metadata {
return Ok(true);
}
// Earlier namespace siblings may have completed, but none
// can certify coverage of this unresolved parent object.
self.coverage_gap |= listing.forward_sweep;
if self.coverage_frontier.as_deref().is_some_and(|frontier| {
frontier
.strip_prefix(&folder.name)
.is_some_and(|suffix| suffix.starts_with('/'))
}) {
self.coverage_frontier = None;
}
self.record_missing_erasure_metadata(folder, into).await?;
return Ok(false);
}
if into.compacted {
self.record_completed_child(&folder_item.name);
if !frame.was_compacted && work.is_some() {
self.maybe_send_owned_checkpoint(folder, this_hash, into, work.as_deref());
}
self.send_update_for_entry(this_hash, &folder.parent, into).await;
tokio::task::yield_now().await;
} else {
into.add_child(h);
if let Some(work) = &mut work {
work.acknowledge(&folder_item.name, true, false);
}
self.record_completed_child(&folder_item.name);
tokio::task::yield_now().await;
self.maybe_send_checkpoint(folder, this_hash, into);
self.refresh_usage_subtree(h, &folder_item.parent);
self.send_update().await;
}
Ok(true)
}
}
+2 -15
View File
@@ -616,22 +616,9 @@ async fn checkpoint_ancestor_depth_limit_preserves_suspended_accounting() {
size: 7,
..Default::default()
};
let mut child = DataUsageEntry::default();
let error = scanner
.scan_child_folder(
CancellationToken::new(),
CachedFolder {
name: "bucket/parent/child".to_string(),
parent: Some(hash.clone()),
object_heal_prob_div: 1,
},
&mut hash,
&mut parent,
&mut child,
FolderScanMode::Namespace,
)
.await
.expect_err("unsupported depth must stop before recursion");
.suspend_checkpoint_parent(&mut hash, &mut parent)
.expect_err("unsupported checkpoint depth must preserve the parent");
assert!(matches!(error, ScannerError::Other(message) if message.contains("depth limit")));
assert_eq!(hash, hash_path("bucket/parent"));
assert_eq!((parent.objects, parent.size), (3, 7));
@@ -229,6 +229,105 @@ async fn large_prefix_deep_resumes_after_budget_across_cycles_and_leaders() {
check_large_prefix_resumption(HealScanMode::Deep).await;
}
tokio::task_local! {
static MAX_FOLDER_FRAMES: std::cell::Cell<usize>;
}
pub(in crate::scanner_folder) fn observe_folder_frame_depth(depth: usize) {
let _ = MAX_FOLDER_FRAMES.try_with(|peak| peak.set(peak.get().max(depth)));
}
#[test]
#[serial]
fn nested_folder_sweep_resumes_with_exact_usage() {
// Match the Linux server profiles even when nextest sets a larger libtest stack.
let stack_size = if cfg!(debug_assertions) {
8 * rustfs_config::DEFAULT_THREAD_STACK_SIZE
} else {
rustfs_config::DEFAULT_THREAD_STACK_SIZE
};
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_stack_size(stack_size)
.enable_all()
.build()
.expect("build scanner worker runtime");
let worker = runtime.spawn(MAX_FOLDER_FRAMES.scope(std::cell::Cell::new(0), check_nested_folder_sweep()));
runtime
.block_on(worker)
.expect("scanner worker must complete the folder sweep");
}
async fn check_nested_folder_sweep() {
let (scanner, root) = build_test_scanner().await;
let _cleanup = TestGuard {
temp_dir: Some(root.clone()),
};
write_checkpoint_object(
&root,
"documents/archive/2024/quarter-1/finance/receipts/first",
&[(Some(uuid::Uuid::from_u128(1)), 3), (Some(uuid::Uuid::from_u128(2)), 7)],
)
.await;
for (key, bytes) in [
("documents/archive/2024/quarter-1/finance/receipts/second", 11),
("documents/archive/2025/quarter-2/finance/reports/first", 13),
("pictures/archive/2024/quarter-2/projects/meeting/first", 17),
] {
write_checkpoint_object(&root, key, &[(None, bytes)]).await;
}
let identity = crate::DataUsageScanIdentity {
tier_registry_generation: crate::runtime_tier_registry_for_cycle(11, 7).await.generation,
..bound_checkpoint().1
};
let mut initial = DataUsageCache::default();
initial.prepare_bucket_checkpoint("bucket", 11, 7, SOURCE, PLAN, identity);
initial.info.skip_healing = true;
let mode = HealScanMode::Normal;
let (fresh, visits) = scan(&scanner.local_disk, initial.clone(), mode, 5).await;
let ScannerDiskScanOutcome::Complete(fresh) = fresh else {
panic!("the uninterrupted sweep must visit all sibling prefixes");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.replace(0)) >= 8,
"the driver must own all ancestor frames"
);
assert_eq!(visits.progress().0, 4);
let expected = (4, 2, 51);
let totals = fresh.checked_flatten("bucket").expect("complete fresh bucket tree");
assert_eq!((totals.objects, totals.versions, totals.size), expected);
let (interrupted, visits) = scan(&scanner.local_disk, initial, mode, 2).await;
let ScannerDiskScanOutcome::Partial(partial) = interrupted else {
panic!("the two-object budget must stop inside the folder walk");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.replace(0)) >= 8,
"the budget must interrupt a nested walk"
);
assert_eq!(visits.reason(), Some(ScannerCycleBudgetReason::Objects));
let store = FixtureStore::new();
let mut resumed = save_reload(&store, &partial).await;
assert!(!resumed.info.snapshot_complete);
assert!(resumed.has_scan_position());
resumed.prepare_bucket_checkpoint("bucket", 12, 8, SOURCE, PLAN, identity);
resumed.info.skip_healing = true;
let (finished, _) = scan(&scanner.local_disk, resumed, mode, 5).await;
let ScannerDiskScanOutcome::Complete(finished) = finished else {
panic!("the resumed walk must finish the remaining sibling prefixes");
};
assert!(
MAX_FOLDER_FRAMES.with(|peak| peak.get()) >= 8,
"the driver must revisit nested work after reload"
);
let persisted = save_reload(&store, &finished).await;
assert!(persisted.info.snapshot_complete);
assert!(persisted.info.scan_checkpoint.is_none());
let totals = persisted.checked_flatten("bucket").expect("complete resumed bucket tree");
assert_eq!((totals.objects, totals.versions, totals.size), expected);
}
async fn check_large_prefix_resumption(mode: HealScanMode) {
let (scanner, root) = build_test_scanner().await;
let _cleanup = TestGuard {
+2
View File
@@ -87,6 +87,8 @@ checked_files=(
"crates/scanner/src/scanner.rs"
"crates/scanner/src/scanner_io.rs"
"crates/scanner/src/scanner_folder.rs"
"crates/scanner/src/scanner_folder/heal_walk.rs"
"crates/scanner/src/scanner_folder/queue_walk.rs"
"crates/concurrency/src/workers.rs"
"crates/concurrency/src/deadlock.rs"
"crates/trusted-proxies/src/global.rs"