mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-02 22:26:21 +00:00
fix(capacity): discard stale topology on bounded refresh
Reconcile a scheduled full refresh against the topology it scanned. Represent baseline completeness with the per-disk map and compute aggregate totals in one pass. Refs: rustfs/rustfs#9837 Refs: rustfs/backlog#3399 Co-Authored-By: heihutu <heihutu@gmail.com> Co-Authored-By: zhi22915 <qiuzgang@gmail.com> Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
This commit is contained in:
@@ -173,7 +173,7 @@ Refreshing only dirty disks is safe only when:
|
||||
|
||||
The first refresh builds an aggregate baseline. Scheduled refreshes stay idle when there are no dirty disks and the baseline still applies. A change in local disk membership triggers a full refresh, including replacements that keep the same disk count. Dirty disks with an incomplete per-disk baseline also trigger a full refresh.
|
||||
|
||||
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. That bounded estimate acknowledges dirty marks that predate the scan, while marks recorded during the scan remain pending. This prevents one old dirty mark from causing an endless timeout loop without treating the estimate as exact.
|
||||
A full refresh that reaches its time budget may publish an estimated aggregate without establishing a complete per-disk baseline. A bounded or degraded full refresh after a topology change discards the old per-disk baseline and publishes the available current aggregate. A timeout estimate acknowledges dirty marks that predate the scan. Marks recorded during the scan remain pending.
|
||||
|
||||
### Merge Rules After a Subset Refresh
|
||||
|
||||
|
||||
@@ -173,7 +173,7 @@ crate 不是“超时就直接失败”的设计:
|
||||
|
||||
首次刷新会建立聚合基线。没有脏盘且原基线仍适用时,定时刷新保持空闲。本地盘成员变化时触发全量刷新,包括盘数相同的替换。存在脏盘但每盘基线不完整时,也执行全量刷新。
|
||||
|
||||
全盘刷新达到时间预算后,可以发布估算聚合值,但不会借此建立完整 per-disk 基线。该有界估算会确认扫描开始前的脏标记;扫描过程中记录的新标记仍会保留。这样既不会把估算值当成精确值,也不会让一个旧脏标记永久触发超时循环。
|
||||
全盘刷新达到时间预算后,可以发布估算聚合值。拓扑变化后的全量刷新若超时或降级,会丢弃旧的每盘基线,并发布当前可用的聚合值。超时估算会确认扫描开始前的脏标记,扫描过程中记录的新标记仍会保留。
|
||||
|
||||
### 子集刷新后的合并规则
|
||||
|
||||
|
||||
@@ -764,7 +764,6 @@ pub struct HybridCapacityManager {
|
||||
/// Per-disk cache populated after a successful full refresh and updated by dirty subset refreshes.
|
||||
disk_cache: Arc<RwLock<HashMap<CapacityScopeDisk, CachedDiskCapacity>>>,
|
||||
/// Whether the per-disk cache currently covers all known disks.
|
||||
disk_cache_complete: Arc<RwLock<bool>>,
|
||||
/// Configuration
|
||||
config: HybridStrategyConfig,
|
||||
/// Shared singleflight refresh state
|
||||
@@ -797,7 +796,6 @@ impl HybridCapacityManager {
|
||||
write_record: Arc::new(WriteRecord::new()),
|
||||
dirty_disks: Arc::new(RwLock::new(HashMap::new())),
|
||||
disk_cache: Arc::new(RwLock::new(HashMap::new())),
|
||||
disk_cache_complete: Arc::new(RwLock::new(false)),
|
||||
config,
|
||||
refresh_state: Arc::new(Mutex::new(RefreshState::default())),
|
||||
}
|
||||
@@ -821,57 +819,62 @@ impl HybridCapacityManager {
|
||||
/// only the scanned subset's totals; callers that publish or return this value (e.g. the
|
||||
/// `refresh_or_join` leader and joiners, admin used-capacity) must use the reconciled copy
|
||||
/// so they never report the subset bytes as the whole-cluster total.
|
||||
pub async fn update_capacity(&self, mut update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
|
||||
pub async fn update_capacity(&self, update: CapacityUpdate, source: DataSource) -> CapacityUpdate {
|
||||
self.commit_capacity(update, source, None).await
|
||||
}
|
||||
|
||||
async fn commit_capacity(
|
||||
&self,
|
||||
mut update: CapacityUpdate,
|
||||
source: DataSource,
|
||||
full_scan_disks: Option<&[CapacityDiskRef]>,
|
||||
) -> CapacityUpdate {
|
||||
let start = Instant::now();
|
||||
|
||||
if !update.per_disk.is_empty() || update.degraded {
|
||||
let mut disk_cache = self.disk_cache.write().await;
|
||||
let mut disk_cache_complete = self.disk_cache_complete.write().await;
|
||||
|
||||
let recompute = if !update.per_disk.is_empty()
|
||||
let replaces_cache = !update.per_disk.is_empty()
|
||||
&& update.replaces_disk_cache
|
||||
&& update.expected_disk_count == Some(update.per_disk.len())
|
||||
{
|
||||
&& update.expected_disk_count == Some(update.per_disk.len());
|
||||
if replaces_cache {
|
||||
disk_cache.clear();
|
||||
for entry in &update.per_disk {
|
||||
disk_cache.insert(
|
||||
entry.disk.clone(),
|
||||
CachedDiskCapacity {
|
||||
used_bytes: entry.used_bytes,
|
||||
file_count: entry.file_count,
|
||||
is_estimated: entry.is_estimated,
|
||||
},
|
||||
);
|
||||
} else if !disk_cache.is_empty()
|
||||
&& let Some(disks) = full_scan_disks
|
||||
{
|
||||
// A bounded full scan may publish bytes without establishing a
|
||||
// baseline. Do not merge a previous topology into that result.
|
||||
let local: HashSet<_> = disks
|
||||
.iter()
|
||||
.map(|disk| (disk.endpoint.as_str(), disk.drive_path.as_str()))
|
||||
.collect();
|
||||
if disk_cache.len() != local.len()
|
||||
|| !disk_cache
|
||||
.keys()
|
||||
.all(|disk| local.contains(&(disk.endpoint.as_str(), disk.drive_path.as_str())))
|
||||
{
|
||||
disk_cache.clear();
|
||||
}
|
||||
*disk_cache_complete = true;
|
||||
true
|
||||
} else if *disk_cache_complete {
|
||||
// Merging over a complete cache also covers a degraded
|
||||
// (partial-failure) full refresh: successfully scanned disks
|
||||
// are refreshed while failed disks keep their last-known
|
||||
// values, so the published total does not dip to the
|
||||
// surviving-subset sum and bounce back on the next refresh.
|
||||
for entry in &update.per_disk {
|
||||
disk_cache.insert(
|
||||
entry.disk.clone(),
|
||||
CachedDiskCapacity {
|
||||
used_bytes: entry.used_bytes,
|
||||
file_count: entry.file_count,
|
||||
is_estimated: entry.is_estimated,
|
||||
},
|
||||
);
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
}
|
||||
|
||||
if recompute {
|
||||
// Reconcile cluster-wide aggregates from the full per-disk cache so a
|
||||
// dirty-subset refresh reports the merged cluster totals, not the subset sum.
|
||||
update.total_used = disk_cache.values().map(|entry| entry.used_bytes).sum();
|
||||
update.file_count = disk_cache.values().map(|entry| entry.file_count).sum();
|
||||
update.is_estimated = disk_cache.values().any(|entry| entry.is_estimated);
|
||||
// A nonempty disk cache always covers one complete topology. A
|
||||
// degraded refresh on that topology keeps last-known disk entries.
|
||||
if replaces_cache || !disk_cache.is_empty() {
|
||||
for entry in &update.per_disk {
|
||||
disk_cache.insert(
|
||||
entry.disk.clone(),
|
||||
CachedDiskCapacity {
|
||||
used_bytes: entry.used_bytes,
|
||||
file_count: entry.file_count,
|
||||
is_estimated: entry.is_estimated,
|
||||
},
|
||||
);
|
||||
}
|
||||
let (bytes, files, estimated) = disk_cache.values().fold((0, 0, false), |(bytes, files, estimated), entry| {
|
||||
(bytes + entry.used_bytes, files + entry.file_count, estimated || entry.is_estimated)
|
||||
});
|
||||
update.total_used = bytes;
|
||||
update.file_count = files;
|
||||
update.is_estimated = estimated;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1061,23 +1064,33 @@ impl HybridCapacityManager {
|
||||
|
||||
/// Returns true if the manager has a complete per-disk cache and can safely refresh only dirty disks.
|
||||
pub async fn can_refresh_dirty_subset(&self) -> bool {
|
||||
*self.disk_cache_complete.read().await
|
||||
!self.disk_cache.read().await.is_empty()
|
||||
}
|
||||
|
||||
// Read both together in the same lock order as update_capacity.
|
||||
pub(crate) async fn disk_cache_matches(&self, local: &HashSet<CapacityScopeDisk>) -> Option<bool> {
|
||||
let cache = self.disk_cache.read().await;
|
||||
self.can_refresh_dirty_subset()
|
||||
.await
|
||||
.then(|| cache.len() == local.len() && cache.keys().all(|disk| local.contains(disk)))
|
||||
(!cache.is_empty()).then(|| cache.len() == local.len() && cache.keys().all(|disk| local.contains(disk)))
|
||||
}
|
||||
|
||||
/// Run a singleflight refresh. Callers either join an existing in-flight refresh or become the leader.
|
||||
///
|
||||
/// Joiners subscribe to the watch channel *before* releasing the mutex, which guarantees
|
||||
/// they cannot miss the completion notification even if the leader finishes very quickly.
|
||||
#[hotpath::measure]
|
||||
pub async fn refresh_or_join<F, Fut>(&self, source: DataSource, refresh_fn: F) -> Result<CapacityUpdate, String>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Result<CapacityUpdate, String>>,
|
||||
{
|
||||
self.refresh_or_join_for_disks(source, None, refresh_fn).await
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
async fn refresh_or_join_for_disks<F, Fut>(
|
||||
&self,
|
||||
source: DataSource,
|
||||
full_scan_disks: Option<&[CapacityDiskRef]>,
|
||||
refresh_fn: F,
|
||||
) -> Result<CapacityUpdate, String>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Result<CapacityUpdate, String>>,
|
||||
@@ -1159,7 +1172,7 @@ impl HybridCapacityManager {
|
||||
// returned to this caller and the one published to joiners carry the cluster totals
|
||||
// rather than a dirty-subset's partial bytes.
|
||||
let result = match result {
|
||||
Ok(update) => Ok(self.update_capacity(update, source).await),
|
||||
Ok(update) => Ok(self.commit_capacity(update, source, full_scan_disks).await),
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
let refresh_duration = refresh_start.elapsed();
|
||||
@@ -1445,8 +1458,8 @@ async fn run_scheduled_capacity_refresh(manager: Arc<HybridCapacityManager>, dis
|
||||
"capacity refresh scheduled"
|
||||
);
|
||||
let result = manager
|
||||
.refresh_or_join(DataSource::Scheduled, move || async move {
|
||||
refresh_capacity_with_scope(disks, dirty_subset).await
|
||||
.refresh_or_join_for_disks(DataSource::Scheduled, (!dirty_subset).then_some(disks.as_slice()), || {
|
||||
refresh_capacity_with_scope(&disks, dirty_subset)
|
||||
})
|
||||
.await;
|
||||
scheduled_refresh_was_clean(&result)
|
||||
@@ -2494,6 +2507,84 @@ mod tests {
|
||||
assert!(!cached.degraded);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_degraded_refresh_after_replacement_drops_retired_capacity() {
|
||||
let manager = create_isolated_manager(HybridStrategyConfig::default());
|
||||
let temp = tempfile::TempDir::new().expect("create capacity fixture");
|
||||
let active = temp.path().join("active");
|
||||
let replacement = temp.path().join("replacement");
|
||||
std::fs::create_dir(&active).expect("create active disk");
|
||||
std::fs::write(active.join("object"), b"abc").expect("write active disk data");
|
||||
let active = active.to_str().expect("UTF-8 active path");
|
||||
let replacement_path = replacement.to_str().expect("UTF-8 replacement path");
|
||||
let mut old = full_two_disk_update();
|
||||
old.per_disk[0] = disk_entry("active", active, 100, 1);
|
||||
manager.update_capacity(old, DataSource::Scheduled).await;
|
||||
|
||||
let current = vec![
|
||||
CapacityDiskRef {
|
||||
endpoint: "active".into(),
|
||||
drive_path: active.into(),
|
||||
},
|
||||
CapacityDiskRef {
|
||||
endpoint: "replacement".into(),
|
||||
drive_path: replacement_path.into(),
|
||||
},
|
||||
];
|
||||
assert!(!run_scheduled_capacity_refresh(manager.clone(), current.clone()).await);
|
||||
let published = manager.get_capacity().await.expect("publish degraded refresh");
|
||||
assert!(published.degraded);
|
||||
assert_eq!(published.total_used, 3);
|
||||
assert!(!manager.can_refresh_dirty_subset().await);
|
||||
assert_eq!(
|
||||
select_scheduled_capacity_refresh(&manager, ¤t).await,
|
||||
ScheduledCapacityRefresh::Idle
|
||||
);
|
||||
|
||||
std::fs::create_dir(&replacement).expect("make replacement readable");
|
||||
std::fs::write(replacement.join("object"), b"12345").expect("write replacement disk data");
|
||||
manager
|
||||
.mark_dirty_scope(&CapacityScope {
|
||||
disks: vec![scope_disk("replacement", replacement_path)],
|
||||
})
|
||||
.await;
|
||||
assert!(run_scheduled_capacity_refresh(manager.clone(), current).await);
|
||||
let published = manager.get_capacity().await.expect("publish recovered refresh");
|
||||
assert_eq!(published.total_used, 8);
|
||||
assert!(!published.degraded);
|
||||
assert!(manager.can_refresh_dirty_subset().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_timed_out_full_refresh_after_replacement_uses_current_estimate() {
|
||||
let manager = create_isolated_manager(HybridStrategyConfig::default());
|
||||
manager.update_capacity(full_two_disk_update(), DataSource::Scheduled).await;
|
||||
let current = [
|
||||
CapacityDiskRef {
|
||||
endpoint: "node-a".into(),
|
||||
drive_path: "/tmp/disk-a".into(),
|
||||
},
|
||||
CapacityDiskRef {
|
||||
endpoint: "node-c".into(),
|
||||
drive_path: "/tmp/disk-c".into(),
|
||||
},
|
||||
];
|
||||
let mut timed_out = CapacityUpdate::estimated(160, 2);
|
||||
timed_out.timed_out = true;
|
||||
timed_out.per_disk = vec![
|
||||
disk_entry("node-a", "/tmp/disk-a", 60, 1),
|
||||
disk_entry("node-c", "/tmp/disk-c", 100, 1),
|
||||
];
|
||||
let published = manager
|
||||
.refresh_or_join_for_disks(DataSource::Scheduled, Some(¤t), || async { Ok(timed_out) })
|
||||
.await
|
||||
.expect("publish bounded full refresh");
|
||||
assert_eq!(published.total_used, 160);
|
||||
assert!(published.timed_out);
|
||||
assert!(published.is_estimated);
|
||||
assert!(!manager.can_refresh_dirty_subset().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_update_capacity_degraded_with_empty_per_disk_serves_merged_cache() {
|
||||
let manager = create_isolated_manager(HybridStrategyConfig::default());
|
||||
|
||||
@@ -420,9 +420,13 @@ pub async fn select_capacity_refresh_disks(
|
||||
}
|
||||
|
||||
#[hotpath::measure]
|
||||
pub async fn refresh_capacity_with_scope(disks: Vec<CapacityDiskRef>, dirty_subset: bool) -> Result<CapacityUpdate, String> {
|
||||
pub async fn refresh_capacity_with_scope(
|
||||
disks: impl AsRef<[CapacityDiskRef]>,
|
||||
dirty_subset: bool,
|
||||
) -> Result<CapacityUpdate, String> {
|
||||
let disks = disks.as_ref();
|
||||
let scan_started_at = Instant::now();
|
||||
let report = calculate_data_dir_used_capacity_report(&disks)
|
||||
let report = calculate_data_dir_used_capacity_report(disks)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user