mirror of
https://github.com/rustfs/rustfs.git
synced 2026-12-02 22:26:21 +00:00
Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bacd330baf | |||
| bd8f831824 | |||
| 7c74186666 | |||
| 460838f691 | |||
| 7648acba97 | |||
| c06a02ce4b | |||
| 485c719ec0 | |||
| 560ee032c7 | |||
| 9d30470316 | |||
| 0e326157cc | |||
| f86e7069d9 | |||
| 7c15d2cc71 | |||
| 1967dec141 | |||
| 5ee681679a | |||
| 123f801671 | |||
| 94ea64359a | |||
| 4f0063da8b | |||
| b71942cf26 |
@@ -106,6 +106,7 @@ jobs:
|
||||
targets_csv: ${{ steps.select.outputs.targets_csv }}
|
||||
has_targets: ${{ steps.select.outputs.has_targets }}
|
||||
run_mutants: ${{ steps.select.outputs.run_mutants }}
|
||||
build_matrix: ${{ steps.group-builds.outputs.matrix }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -164,6 +165,19 @@ jobs:
|
||||
--ci-mode "$CALLER_CI_MODE" \
|
||||
--output artifacts/security-input-gate/selection-manifest.json
|
||||
|
||||
- name: Group selected harness builds
|
||||
id: group-builds
|
||||
env:
|
||||
SELECTED_TARGETS: ${{ steps.select.outputs.targets_json }}
|
||||
run: |
|
||||
matrix=$(jq -cn --argjson selected "$SELECTED_TARGETS" '
|
||||
{include: [
|
||||
{profile: "core", targets_csv: ($selected | map(select(. != "fuzz_s3_select_sql")) | join(","))},
|
||||
{profile: "s3-select", targets_csv: ($selected | map(select(. == "fuzz_s3_select_sql")) | join(","))}
|
||||
] | map(select(.targets_csv != ""))}
|
||||
')
|
||||
printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Upload selection manifest
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
@@ -184,7 +198,10 @@ jobs:
|
||||
needs.select-targets.outputs.has_targets == 'true'
|
||||
# Self-hosted runner required: nightly libFuzzer builds exceed hosted disk budget.
|
||||
runs-on: sm-standard-4
|
||||
# The full target set shares one instrumented dependency build.
|
||||
# Full validation builds one instrumented dependency graph per runner.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.select-targets.outputs.build_matrix) }}
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
@@ -202,7 +219,7 @@ jobs:
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: nightly
|
||||
cache-shared-key: fuzz-nightly-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
|
||||
cache-shared-key: fuzz-nightly-${{ matrix.profile }}-${{ env.CARGO_BUILD_TARGET }}-cgu16-${{ hashFiles('fuzz/Cargo.lock', 'fuzz/Cargo.toml', 'fuzz/fuzz_targets/**') }}
|
||||
cache-save-if: ${{ github.ref == 'refs/heads/main' || github.event_name == 'schedule' }}
|
||||
|
||||
- name: Install cargo-fuzz
|
||||
@@ -219,12 +236,12 @@ jobs:
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
# Split monolithic ASan+SanCov LLVM modules across 16 codegen units so huge crates stay within 28 GB RAM.
|
||||
FUZZ_CODEGEN_UNITS: "16"
|
||||
FUZZ_TARGET: ${{ needs.select-targets.outputs.targets_csv }}
|
||||
FUZZ_TARGET: ${{ matrix.targets_csv }}
|
||||
run: BUILD_ONLY=1 ./scripts/fuzz/run.sh
|
||||
|
||||
- name: Stage prebuilt fuzz binaries
|
||||
env:
|
||||
SELECTED_TARGETS_CSV: ${{ needs.select-targets.outputs.targets_csv }}
|
||||
SELECTED_TARGETS_CSV: ${{ matrix.targets_csv }}
|
||||
run: |
|
||||
binary_root="fuzz/prebuilt/${CARGO_BUILD_TARGET}/release"
|
||||
mkdir -p "${binary_root}"
|
||||
@@ -242,8 +259,10 @@ jobs:
|
||||
- name: Upload prebuilt fuzz binaries
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.profile }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release/
|
||||
# Reuse successful group artifacts when another group is rerun.
|
||||
overwrite: true
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
compression-level: 0
|
||||
@@ -282,7 +301,7 @@ jobs:
|
||||
- name: Download prebuilt fuzz binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
|
||||
|
||||
- name: Restore executable bit
|
||||
@@ -391,7 +410,7 @@ jobs:
|
||||
- name: Download prebuilt fuzz binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
name: fuzz-prebuilt-binaries-${{ github.run_id }}-${{ matrix.target == 'fuzz_s3_select_sql' && 's3-select' || 'core' }}
|
||||
path: fuzz/prebuilt/${{ env.CARGO_BUILD_TARGET }}/release
|
||||
|
||||
- name: Restore executable bit
|
||||
|
||||
Generated
+3
-2
@@ -9924,9 +9924,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.18"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
|
||||
checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe"
|
||||
|
||||
[[package]]
|
||||
name = "piper"
|
||||
@@ -12784,6 +12784,7 @@ dependencies = [
|
||||
"rustfs-audit",
|
||||
"rustfs-common",
|
||||
"rustfs-config",
|
||||
"rustfs-data-usage",
|
||||
"rustfs-ecstore",
|
||||
"rustfs-heal-contracts",
|
||||
"rustfs-iam",
|
||||
|
||||
@@ -26,8 +26,8 @@
|
||||
//! channel and await a checkpoint receipt; ordinary complete writes do not use
|
||||
//! it.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::{BuildHasher, Hash};
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
@@ -225,19 +225,34 @@ impl MrfDurableRepairAnchor {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
|
||||
let Some(lease) = event.lease else {
|
||||
return false;
|
||||
};
|
||||
self.kind == event.kind
|
||||
&& self.bucket == event.bucket
|
||||
&& self.object == event.object
|
||||
&& self.version_id == event.version_id
|
||||
&& self.scope == event.scope
|
||||
&& self.delete_marker_purge == event.delete_marker_purge
|
||||
&& self.lease == lease
|
||||
&& self.bucket_incarnation_id == event.bucket_incarnation_id
|
||||
fn proof_identity(&self) -> MrfProofIdentity<'_> {
|
||||
MrfProofIdentity {
|
||||
kind: self.kind,
|
||||
bucket: &self.bucket,
|
||||
object: &self.object,
|
||||
version_id: self.version_id,
|
||||
scope: self.scope,
|
||||
delete_marker_purge: self.delete_marker_purge,
|
||||
lease: self.lease,
|
||||
bucket_incarnation_id: self.bucket_incarnation_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_proven_by(&self, event: &MrfVerifiedRepairEvent) -> bool {
|
||||
event.proof_identity() == Some(self.proof_identity())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Hash)]
|
||||
struct MrfProofIdentity<'a> {
|
||||
kind: MrfKind,
|
||||
bucket: &'a str,
|
||||
object: &'a str,
|
||||
version_id: Option<[u8; 16]>,
|
||||
scope: Option<MrfScope>,
|
||||
delete_marker_purge: Option<MrfDeleteMarkerPurgeIdentity>,
|
||||
lease: MrfIngressLease,
|
||||
bucket_incarnation_id: Uuid,
|
||||
}
|
||||
|
||||
/// Consume only anchors proven by a complete verified-repair identity. The
|
||||
@@ -252,44 +267,81 @@ pub fn consume_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnch
|
||||
before.saturating_sub(anchors.len())
|
||||
}
|
||||
|
||||
/// Consume recorded verified repairs for one bucket without draining
|
||||
/// unrelated or still-unmatched proofs. If the caller crashes before
|
||||
/// persisting the retained anchor set, the proof may be replayed by repair
|
||||
/// instead of silently deleting the old responsibility.
|
||||
/// Consume recorded verified repairs for one bucket, retaining unmatched events.
|
||||
pub fn consume_recorded_verified_mrf_repair_events_for(bucket: &str, anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
|
||||
consume_recorded_verified_mrf_repairs(anchors, Some(bucket))
|
||||
}
|
||||
|
||||
/// Match recorded receipts across all supplied anchors in one pass.
|
||||
/// Only the first exact receipt for each identity is consumed. The caller
|
||||
/// persists the successor checkpoint before cleaning up older replay files.
|
||||
pub fn consume_recorded_verified_mrf_repair_events(anchors: &mut Vec<MrfDurableRepairAnchor>) -> usize {
|
||||
consume_recorded_verified_mrf_repairs(anchors, None)
|
||||
}
|
||||
|
||||
fn consume_recorded_verified_mrf_repairs(anchors: &mut Vec<MrfDurableRepairAnchor>, bucket: Option<&str>) -> usize {
|
||||
let Some(registry) = MRF_VERIFIED_REPAIR_EVENTS.get() else {
|
||||
return 0;
|
||||
};
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
let leases: HashSet<_> = {
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
};
|
||||
if events.is_empty() {
|
||||
events.shrink_to_fit();
|
||||
return 0;
|
||||
}
|
||||
events
|
||||
.iter()
|
||||
.filter(|event| bucket.is_none_or(|bucket| event.bucket.as_ref() == bucket))
|
||||
.filter_map(|event| event.lease)
|
||||
.collect()
|
||||
};
|
||||
consume_verified_mrf_repair_events_from_queue(bucket, anchors, &mut events)
|
||||
let proved = {
|
||||
// The queue bounds the relevant leases. Scan the journal outside the
|
||||
// lock and hash full identities only for those leases.
|
||||
let pending = anchors
|
||||
.iter()
|
||||
.filter(|anchor| leases.contains(&anchor.lease) && bucket.is_none_or(|bucket| anchor.bucket.as_ref() == bucket))
|
||||
.map(|anchor| (anchor.proof_identity(), anchor))
|
||||
.collect();
|
||||
let matched = {
|
||||
let Ok(mut events) = registry.lock() else {
|
||||
return 0;
|
||||
};
|
||||
match_recorded_verified_mrf_repairs(&mut events, &pending)
|
||||
};
|
||||
matched.into_iter().cloned().collect()
|
||||
};
|
||||
remove_proved_anchors(anchors, &proved)
|
||||
}
|
||||
|
||||
fn consume_verified_mrf_repair_events_from_queue(
|
||||
bucket: &str,
|
||||
anchors: &mut Vec<MrfDurableRepairAnchor>,
|
||||
events: &mut std::collections::VecDeque<MrfVerifiedRepairEvent>,
|
||||
) -> usize {
|
||||
let before = anchors.len();
|
||||
fn match_recorded_verified_mrf_repairs<'a>(
|
||||
events: &mut VecDeque<MrfVerifiedRepairEvent>,
|
||||
pending: &HashMap<MrfProofIdentity<'_>, &'a MrfDurableRepairAnchor>,
|
||||
) -> HashSet<&'a MrfDurableRepairAnchor> {
|
||||
let previous_event_count = events.len();
|
||||
let mut proved = HashSet::new();
|
||||
events.retain(|event| {
|
||||
if event.bucket.as_ref() != bucket {
|
||||
let Some(anchor) = event.proof_identity().and_then(|identity| pending.get(&identity)) else {
|
||||
return true;
|
||||
}
|
||||
let mut matched = false;
|
||||
anchors.retain(|anchor| {
|
||||
let proven = anchor.is_proven_by(event);
|
||||
matched |= proven;
|
||||
!proven
|
||||
});
|
||||
!matched
|
||||
};
|
||||
!proved.insert(*anchor)
|
||||
});
|
||||
// The old queue rebuild reserved the pre-consumption event count. Reuse
|
||||
// that buffer when possible without extending its capacity lifetime:
|
||||
// an emptied queue releases its backing storage on the next consumption.
|
||||
// Release the backing buffer on an empty pass and keep all unmatched
|
||||
// notices in FIFO order.
|
||||
events.shrink_to(previous_event_count);
|
||||
before.saturating_sub(anchors.len())
|
||||
proved
|
||||
}
|
||||
|
||||
fn remove_proved_anchors(anchors: &mut Vec<MrfDurableRepairAnchor>, proved: &HashSet<MrfDurableRepairAnchor>) -> usize {
|
||||
if proved.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let before = anchors.len();
|
||||
let leases: HashSet<_> = proved.iter().map(|anchor| anchor.lease).collect();
|
||||
anchors.retain(|anchor| !leases.contains(&anchor.lease) || !proved.contains(anchor));
|
||||
before - anchors.len()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -870,6 +922,21 @@ pub struct MrfVerifiedRepairEvent {
|
||||
pub disposition: MrfVerifiedRepairDisposition,
|
||||
}
|
||||
|
||||
impl MrfVerifiedRepairEvent {
|
||||
fn proof_identity(&self) -> Option<MrfProofIdentity<'_>> {
|
||||
Some(MrfProofIdentity {
|
||||
kind: self.kind,
|
||||
bucket: &self.bucket,
|
||||
object: &self.object,
|
||||
version_id: self.version_id,
|
||||
scope: self.scope,
|
||||
delete_marker_purge: self.delete_marker_purge,
|
||||
lease: self.lease?,
|
||||
bucket_incarnation_id: self.bucket_incarnation_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound on the repaired-event backlog. Notices are best-effort hints; when
|
||||
/// the ring is full the oldest are dropped and the affected ledger entries
|
||||
/// simply expire through their own attempts/age limits.
|
||||
@@ -992,6 +1059,15 @@ pub fn note_mrf_unverified_legacy(event: MrfUnverifiedLegacyEvent) {
|
||||
/// Take held-legacy notices for one bucket. The durable ledger still verifies
|
||||
/// the full anchor before changing the journal entry to its held state.
|
||||
pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
take_mrf_unverified_legacy_events_matching(|candidate| candidate == bucket)
|
||||
}
|
||||
|
||||
/// Take held-legacy notices for the supplied buckets in queue order.
|
||||
pub fn take_mrf_unverified_legacy_events_for_buckets(buckets: &HashSet<&str>) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
take_mrf_unverified_legacy_events_matching(|bucket| buckets.contains(bucket))
|
||||
}
|
||||
|
||||
fn take_mrf_unverified_legacy_events_matching(mut matches: impl FnMut(&str) -> bool) -> Vec<MrfUnverifiedLegacyEvent> {
|
||||
let Some(registry) = MRF_UNVERIFIED_LEGACY_EVENTS.get() else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -1000,7 +1076,7 @@ pub fn take_mrf_unverified_legacy_events_for(bucket: &str) -> Vec<MrfUnverifiedL
|
||||
};
|
||||
let mut taken = Vec::new();
|
||||
events.retain(|event| {
|
||||
if event.anchor.bucket.as_ref() == bucket {
|
||||
if matches(&event.anchor.bucket) {
|
||||
taken.push(event.clone());
|
||||
false
|
||||
} else {
|
||||
|
||||
@@ -138,3 +138,70 @@ fn event_presence_keeps_poisoned_legacy_unknown() {
|
||||
assert!(mrf_durable_repair_events_may_be_pending());
|
||||
assert!(registry.is_poisoned(), "the hint must not clear or recover poisoned state");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_consumption_matches_exact_receipts_and_keeps_other_notices() {
|
||||
if isolated("batch_consumption_matches_exact_receipts_and_keeps_other_notices") {
|
||||
return;
|
||||
}
|
||||
let first = MrfDurableRepairAnchor {
|
||||
kind: MrfKind::PartialWrite,
|
||||
bucket: Arc::from("batch-first"),
|
||||
object: Arc::from("same-object"),
|
||||
version_id: None,
|
||||
scope: Some(MrfScope {
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
}),
|
||||
delete_marker_purge: None,
|
||||
lease: MrfIngressLease::new(41),
|
||||
bucket_incarnation_id: Uuid::new_v4(),
|
||||
};
|
||||
let second = MrfDurableRepairAnchor {
|
||||
bucket: Arc::from("batch-second"),
|
||||
..first.clone()
|
||||
};
|
||||
let waiting = MrfDurableRepairAnchor {
|
||||
lease: MrfIngressLease::new(42),
|
||||
..first.clone()
|
||||
};
|
||||
let other = MrfDurableRepairAnchor {
|
||||
bucket: Arc::from("batch-other"),
|
||||
..first.clone()
|
||||
};
|
||||
let proof = |anchor: &MrfDurableRepairAnchor| MrfVerifiedRepairEvent {
|
||||
kind: anchor.kind,
|
||||
bucket: anchor.bucket.clone(),
|
||||
object: anchor.object.clone(),
|
||||
version_id: anchor.version_id,
|
||||
scope: anchor.scope,
|
||||
delete_marker_purge: anchor.delete_marker_purge,
|
||||
lease: Some(anchor.lease),
|
||||
bucket_incarnation_id: anchor.bucket_incarnation_id,
|
||||
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
|
||||
};
|
||||
let stale = MrfVerifiedRepairEvent {
|
||||
bucket_incarnation_id: Uuid::new_v4(),
|
||||
..proof(&waiting)
|
||||
};
|
||||
for event in [proof(&other), proof(&second), proof(&first), stale.clone(), proof(&first)] {
|
||||
note_mrf_verified_repair(event);
|
||||
}
|
||||
let legacy = |anchor: &MrfDurableRepairAnchor| MrfUnverifiedLegacyEvent { anchor: anchor.clone() };
|
||||
for anchor in [&other, &second, &first] {
|
||||
note_mrf_unverified_legacy(legacy(anchor));
|
||||
}
|
||||
|
||||
let mut anchors = vec![first.clone(), waiting.clone(), second.clone(), first.clone()];
|
||||
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
|
||||
assert_eq!(
|
||||
take_mrf_unverified_legacy_events_for_buckets(&buckets),
|
||||
vec![legacy(&second), legacy(&first)]
|
||||
);
|
||||
assert_eq!(consume_recorded_verified_mrf_repair_events(&mut anchors), 3);
|
||||
assert_eq!(anchors, vec![waiting]);
|
||||
assert_eq!(take_mrf_verified_repair_events_for(&first.bucket), vec![stale, proof(&first)]);
|
||||
assert!(take_mrf_verified_repair_events_for(&second.bucket).is_empty());
|
||||
assert_eq!(take_mrf_verified_repair_events_for(&other.bucket), vec![proof(&other)]);
|
||||
assert_eq!(take_mrf_unverified_legacy_events_for(&other.bucket), vec![legacy(&other)]);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,25 @@
|
||||
use super::*;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
fn consume_verified_mrf_repair_events_from_queue(
|
||||
bucket: &str,
|
||||
anchors: &mut Vec<MrfDurableRepairAnchor>,
|
||||
events: &mut VecDeque<MrfVerifiedRepairEvent>,
|
||||
) -> usize {
|
||||
let proved = {
|
||||
let pending = anchors
|
||||
.iter()
|
||||
.filter(|anchor| anchor.bucket.as_ref() == bucket)
|
||||
.map(|anchor| (anchor.proof_identity(), anchor))
|
||||
.collect();
|
||||
match_recorded_verified_mrf_repairs(events, &pending)
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.collect()
|
||||
};
|
||||
remove_proved_anchors(anchors, &proved)
|
||||
}
|
||||
|
||||
fn proof_fixture() -> (MrfDurableRepairAnchor, MrfVerifiedRepairEvent) {
|
||||
let anchor = MrfDurableRepairAnchor {
|
||||
kind: MrfKind::PartialWrite,
|
||||
|
||||
@@ -25,6 +25,14 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
pub const S3VECTORS_MAINTENANCE_SUB_SYS: &str = "s3vectors_maintenance";
|
||||
/// Existing ordinary IAM account selected to execute Vector maintenance.
|
||||
pub const S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT: &str = "execution_account";
|
||||
/// Environment variable enabling or disabling the external S3 Vectors HTTP service.
|
||||
///
|
||||
/// Defaults to `true`. Setting `0`, `false`, `off`, or `no` makes S3 Vectors
|
||||
/// requests fail closed with `503 ServiceUnavailableException` while keeping
|
||||
/// ordinary S3 traffic unaffected.
|
||||
pub const ENV_S3VECTORS_ENABLE: &str = "RUSTFS_S3VECTORS_ENABLE";
|
||||
/// Default enablement for the external S3 Vectors HTTP service.
|
||||
pub const DEFAULT_S3VECTORS_ENABLE: bool = true;
|
||||
|
||||
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
|
||||
/// Defaults to false. Enable only after all possible writers support receipt
|
||||
|
||||
@@ -54,6 +54,9 @@ pub const DATA_USAGE_OBJECT_NAME: &str = ".usage.v2.json";
|
||||
/// [`DATA_USAGE_OBJECT_NAME`], this object is never authoritative for quota
|
||||
/// admission because namespace activity may have raced the scan.
|
||||
pub const DATA_USAGE_OBSERVED_OBJECT_NAME: &str = ".usage.observed.json";
|
||||
/// Completed bucket measurements between full namespace snapshots. Older
|
||||
/// leaders keep reading the unchanged authoritative object during rollout.
|
||||
pub const DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME: &str = ".usage.buckets.json";
|
||||
|
||||
/// Usage snapshot written by scanner implementations predating distributed
|
||||
/// leadership fencing. It is read only when neither authoritative snapshot
|
||||
@@ -634,6 +637,21 @@ pub struct DataUsageInfo {
|
||||
/// authoritative usage snapshot yet.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub usage_snapshot_bootstrap_pending: bool,
|
||||
/// Only an initial bootstrap can authorize display of first-scan progress.
|
||||
/// Recovery, reset and older markers leave this false across restarts.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub usage_snapshot_initial_bootstrap: bool,
|
||||
/// Present only on the independent completed-bucket snapshot object.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_certified_buckets: Option<CertifiedBucketsScope>,
|
||||
/// An older writer drops this opt-in, disabling initial fallback.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_initial_view_version: Option<u16>,
|
||||
/// Non-first barriers are durable before bucket-sidecar publication.
|
||||
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub usage_snapshot_noninitial_buckets: HashMap<String, String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_snapshot_rebuild_generation: Option<String>,
|
||||
/// Deprecated kept here for backward compatibility reasons
|
||||
pub bucket_sizes: HashMap<String, u64>,
|
||||
/// Per-disk snapshot information when available
|
||||
@@ -654,6 +672,25 @@ pub struct DataUsageSnapshotIdentity {
|
||||
pub scanner_epoch: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct CertifiedBucketsScope {
|
||||
pub version: u16,
|
||||
pub baseline_initial_bootstrap: bool,
|
||||
pub baseline_bootstrap_pending: bool,
|
||||
pub movement_generation: u64,
|
||||
pub sources: Vec<CertifiedBucketsSource>,
|
||||
pub bucket_incarnations: HashMap<String, String>,
|
||||
pub baseline: DataUsageSnapshotIdentity,
|
||||
pub baseline_rebuild_generation: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct CertifiedBucketsSource {
|
||||
pub pool_index: u64,
|
||||
pub set_index: u64,
|
||||
pub layout: [u8; 32],
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct DataUsageSegmentInvalidationProof {
|
||||
#[serde(default)]
|
||||
@@ -687,6 +724,149 @@ pub struct DataUsageSnapshotSetState {
|
||||
}
|
||||
|
||||
impl DataUsageInfo {
|
||||
/// Whether the canonical root can supply completed values to a persisted usage view.
|
||||
pub fn is_completed_usage_baseline(&self) -> bool {
|
||||
self.is_complete_bucket_usage_snapshot()
|
||||
&& !self.usage_snapshot_observational
|
||||
&& !self.usage_snapshot_partial
|
||||
&& self.usage_snapshot_certified_buckets.is_none()
|
||||
}
|
||||
|
||||
/// A bootstrap marker records ownership and history before a namespace baseline exists.
|
||||
/// It cannot contain measurements, observations or partial coverage.
|
||||
pub fn has_usage_bootstrap_marker_shape(&self) -> bool {
|
||||
self.usage_snapshot_bootstrap_pending
|
||||
&& self.last_update.is_some()
|
||||
&& self
|
||||
== &Self {
|
||||
last_update: self.last_update,
|
||||
scanner_epoch: self.scanner_epoch,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_rebuild_generation: self.usage_snapshot_rebuild_generation.clone(),
|
||||
usage_snapshot_initial_bootstrap: self.usage_snapshot_initial_bootstrap,
|
||||
usage_snapshot_initial_view_version: self.usage_snapshot_initial_view_version,
|
||||
usage_snapshot_noninitial_buckets: self.usage_snapshot_noninitial_buckets.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Ownership fencing alone does not refresh a completed measurement.
|
||||
pub fn certified_buckets_match_baseline(&self, baseline: &Self) -> bool {
|
||||
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
|
||||
(baseline.is_completed_usage_baseline() || baseline.has_usage_bootstrap_marker_shape())
|
||||
&& self.is_certified_buckets_snapshot()
|
||||
&& scope.baseline.last_update == baseline.last_update
|
||||
&& scope.baseline.scanner_cycle == baseline.scanner_cycle
|
||||
&& baseline.scanner_epoch >= scope.baseline.scanner_epoch
|
||||
&& scope.baseline_initial_bootstrap == baseline.usage_snapshot_initial_bootstrap
|
||||
&& scope.baseline_bootstrap_pending == baseline.usage_snapshot_bootstrap_pending
|
||||
&& scope.baseline_rebuild_generation == baseline.usage_snapshot_rebuild_generation
|
||||
}
|
||||
/// Keep earlier complete bucket values under the same persisted scope.
|
||||
pub fn retain_prior_certified_buckets(&mut self, previous: &Self) -> bool {
|
||||
let (Some(current), Some(old)) = (&self.usage_snapshot_certified_buckets, &previous.usage_snapshot_certified_buckets)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
if !previous.is_certified_buckets_snapshot()
|
||||
|| current.baseline.last_update != old.baseline.last_update
|
||||
|| current.baseline.scanner_cycle != old.baseline.scanner_cycle
|
||||
|| current.baseline.scanner_epoch < old.baseline.scanner_epoch
|
||||
|| current.baseline_rebuild_generation != old.baseline_rebuild_generation
|
||||
|| current.baseline_initial_bootstrap != old.baseline_initial_bootstrap
|
||||
|| current.baseline_bootstrap_pending != old.baseline_bootstrap_pending
|
||||
|| current.movement_generation != old.movement_generation
|
||||
|| current.sources != old.sources
|
||||
{
|
||||
return true;
|
||||
}
|
||||
for (bucket, usage) in &previous.buckets_usage {
|
||||
if usage.bucket_incarnation.as_ref() == current.bucket_incarnations.get(bucket) {
|
||||
let replace = self.buckets_usage.get(bucket).is_none_or(|current| {
|
||||
match (usage.usage_certification, current.usage_certification) {
|
||||
(Some(old), Some(next)) => {
|
||||
(old.epoch, old.cycle, old.certified_at) > (next.epoch, next.cycle, next.certified_at)
|
||||
}
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
if replace {
|
||||
self.buckets_usage.insert(bucket.clone(), usage.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.buckets_count = u64::try_from(self.buckets_usage.len()).unwrap_or(u64::MAX);
|
||||
self.checked_calculate_totals() && self.is_certified_buckets_snapshot()
|
||||
}
|
||||
|
||||
/// Validate the independent bucket snapshot without granting whole-cycle
|
||||
/// convergence, namespace completeness or dirty-usage acknowledgement.
|
||||
pub fn is_certified_buckets_snapshot(&self) -> bool {
|
||||
let Some(scope) = &self.usage_snapshot_certified_buckets else { return false };
|
||||
let (Some(epoch), Some(cycle), Some(updated_at)) = (self.scanner_epoch, self.scanner_cycle, self.last_update) else {
|
||||
return false;
|
||||
};
|
||||
if scope.version != 1
|
||||
|| scope.sources.is_empty()
|
||||
|| !scope
|
||||
.sources
|
||||
.windows(2)
|
||||
.all(|pair| (pair[0].pool_index, pair[0].set_index) < (pair[1].pool_index, pair[1].set_index))
|
||||
|| scope.sources.iter().any(|source| source.layout == [0; 32])
|
||||
|| self.usage_snapshot_authoritative_baseline != Some(scope.baseline)
|
||||
|| scope.baseline.last_update.is_none()
|
||||
|| self.usage_snapshot_complete
|
||||
|| self.usage_snapshot_converged == Some(true)
|
||||
|| !self.usage_snapshot_partial
|
||||
|| self.usage_snapshot_observational
|
||||
|| self.usage_snapshot_admin_projection
|
||||
|| self.usage_snapshot_bootstrap_pending
|
||||
|| self.buckets_usage.is_empty()
|
||||
|| u64::try_from(self.buckets_usage.len()).ok() != Some(self.buckets_count)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut objects = 0_u64;
|
||||
let mut bytes = 0_u64;
|
||||
let mut versions = 0_u64;
|
||||
let mut markers = 0_u64;
|
||||
for (bucket, usage) in &self.buckets_usage {
|
||||
let Some(certificate) = usage.usage_certification else { return false };
|
||||
if usage.bucket_incarnation.as_ref() != scope.bucket_incarnations.get(bucket)
|
||||
|| usage.bucket_incarnation.is_none()
|
||||
|| !matches!(
|
||||
usage.usage_value_state,
|
||||
Some(crate::BucketUsageValueState::Certified | crate::BucketUsageValueState::Carried)
|
||||
)
|
||||
|| (certificate.epoch, certificate.cycle) > (epoch, cycle)
|
||||
|| certificate.certified_at > updated_at
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let (Some(next_objects), Some(next_bytes)) =
|
||||
(objects.checked_add(usage.objects_count), bytes.checked_add(usage.size))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
objects = next_objects;
|
||||
bytes = next_bytes;
|
||||
let (Some(next_versions), Some(next_markers)) = (
|
||||
versions.checked_add(usage.versions_count),
|
||||
markers.checked_add(usage.delete_markers_count),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
versions = next_versions;
|
||||
markers = next_markers;
|
||||
}
|
||||
objects == self.objects_total_count
|
||||
&& bytes == self.objects_total_size
|
||||
&& versions == self.versions_total_count
|
||||
&& markers == self.delete_markers_total_count
|
||||
}
|
||||
|
||||
pub fn snapshot_identity(&self) -> DataUsageSnapshotIdentity {
|
||||
DataUsageSnapshotIdentity {
|
||||
last_update: self.last_update,
|
||||
@@ -2457,6 +2637,24 @@ impl DataUsageInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update all scalar totals atomically, rejecting overflow without wrapping.
|
||||
pub fn checked_calculate_totals(&mut self) -> bool {
|
||||
let totals = self.buckets_usage.values().try_fold([0_u64; 4], |total, usage| {
|
||||
Some([
|
||||
total[0].checked_add(usage.objects_count)?,
|
||||
total[1].checked_add(usage.size)?,
|
||||
total[2].checked_add(usage.versions_count)?,
|
||||
total[3].checked_add(usage.delete_markers_count)?,
|
||||
])
|
||||
});
|
||||
let Some([objects, size, versions, markers]) = totals else { return false };
|
||||
self.objects_total_count = objects;
|
||||
self.objects_total_size = size;
|
||||
self.versions_total_count = versions;
|
||||
self.delete_markers_total_count = markers;
|
||||
true
|
||||
}
|
||||
|
||||
/// Merge another DataUsageInfo into this one
|
||||
pub fn merge(&mut self, other: &DataUsageInfo) {
|
||||
// Merge bucket usage
|
||||
@@ -2653,6 +2851,117 @@ pub struct CompressionTotalInfo {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn complete_bucket_sidecar() -> (DataUsageInfo, DataUsageInfo) {
|
||||
let time = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
|
||||
let baseline = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
scanner_epoch: Some(1),
|
||||
scanner_cycle: Some(2),
|
||||
usage_snapshot_complete: true,
|
||||
..Default::default()
|
||||
};
|
||||
let id = "00000000-0000-0000-0000-000000000001".to_owned();
|
||||
let mut usage = BucketUsageInfo {
|
||||
size: 71,
|
||||
objects_count: 7,
|
||||
versions_count: 8,
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
usage.certify(crate::BucketUsageCertification {
|
||||
epoch: 3,
|
||||
cycle: 4,
|
||||
certified_at: time,
|
||||
});
|
||||
let mut data = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
scanner_epoch: Some(3),
|
||||
scanner_cycle: Some(4),
|
||||
usage_snapshot_partial: true,
|
||||
buckets_count: 1,
|
||||
buckets_usage: HashMap::from([("bucket".into(), usage)]),
|
||||
usage_snapshot_authoritative_baseline: Some(baseline.snapshot_identity()),
|
||||
usage_snapshot_certified_buckets: Some(CertifiedBucketsScope {
|
||||
version: 1,
|
||||
baseline: baseline.snapshot_identity(),
|
||||
baseline_initial_bootstrap: false,
|
||||
baseline_bootstrap_pending: false,
|
||||
baseline_rebuild_generation: None,
|
||||
movement_generation: 0,
|
||||
sources: vec![CertifiedBucketsSource {
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
layout: [1; 32],
|
||||
}],
|
||||
bucket_incarnations: HashMap::from([("bucket".into(), id)]),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
data.calculate_totals();
|
||||
(baseline, data)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_is_not_whole_namespace_or_observational_usage() {
|
||||
let (mut baseline, data) = complete_bucket_sidecar();
|
||||
assert!(data.is_certified_buckets_snapshot());
|
||||
assert!(!data.is_complete_bucket_usage_snapshot());
|
||||
assert!(data.certified_buckets_match_baseline(&baseline));
|
||||
baseline.scanner_epoch = Some(5);
|
||||
assert!(
|
||||
data.certified_buckets_match_baseline(&baseline),
|
||||
"owner fencing must retain the original complete bucket value"
|
||||
);
|
||||
baseline.usage_snapshot_rebuild_generation = Some("reset".into());
|
||||
assert!(!data.certified_buckets_match_baseline(&baseline));
|
||||
let mut bad = data.clone();
|
||||
bad.versions_total_count += 1;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
let mut bad = data.clone();
|
||||
bad.buckets_usage.get_mut("bucket").expect("bucket").usage_certification = None;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
let mut bad = data;
|
||||
bad.usage_snapshot_observational = true;
|
||||
assert!(!bad.is_certified_buckets_snapshot());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_retains_newer_sidecar_value_over_carried_primary_value() {
|
||||
let (_, previous) = complete_bucket_sidecar();
|
||||
let mut candidate = previous.clone();
|
||||
candidate.scanner_cycle = Some(5);
|
||||
let carried = candidate.buckets_usage.get_mut("bucket").expect("carried bucket");
|
||||
carried.objects_count = 1;
|
||||
carried.usage_certification.as_mut().expect("certificate").cycle = 3;
|
||||
let id = "00000000-0000-0000-0000-000000000002".to_owned();
|
||||
let mut next = BucketUsageInfo {
|
||||
size: 20,
|
||||
objects_count: 2,
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
next.certify(crate::BucketUsageCertification {
|
||||
epoch: 3,
|
||||
cycle: 5,
|
||||
certified_at: candidate.last_update.expect("timestamp"),
|
||||
});
|
||||
candidate
|
||||
.usage_snapshot_certified_buckets
|
||||
.as_mut()
|
||||
.expect("scope")
|
||||
.bucket_incarnations
|
||||
.insert("new".into(), id);
|
||||
candidate.buckets_usage.insert("new".into(), next);
|
||||
assert!(candidate.retain_prior_certified_buckets(&previous));
|
||||
assert_eq!(candidate.buckets_usage["bucket"].objects_count, 7);
|
||||
assert_eq!(
|
||||
candidate.buckets_usage["bucket"].usage_certification,
|
||||
previous.buckets_usage["bucket"].usage_certification
|
||||
);
|
||||
assert_eq!((candidate.objects_total_count, candidate.objects_total_size), (9, 91));
|
||||
assert_eq!(candidate.buckets_usage["new"].objects_count, 2);
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct LegacyUsageReader {
|
||||
buckets_count: u64,
|
||||
|
||||
@@ -47,6 +47,10 @@ pub struct BucketScanProgressSource {
|
||||
/// Accepted logical object usage; enumeration alone leaves both absent.
|
||||
pub objects: Option<u64>,
|
||||
pub size: Option<u64>,
|
||||
/// Why this sample has not completed its sweep, when the writer knows.
|
||||
/// Display-only; it never authorizes reuse or quota admission.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocker: Option<String>,
|
||||
}
|
||||
|
||||
/// Response-only progress, deliberately separate from a bucket's total usage.
|
||||
@@ -58,6 +62,15 @@ pub struct BucketScanProgress {
|
||||
pub size: Option<u64>,
|
||||
pub sources_observed: u64,
|
||||
pub sources_total: u64,
|
||||
/// True while this sample is not an authoritative complete sweep.
|
||||
#[serde(default)]
|
||||
pub partial: bool,
|
||||
/// True only when every expected source completed and agrees.
|
||||
#[serde(default)]
|
||||
pub converged: bool,
|
||||
/// The dominant incomplete stage, or `unknown` when no writer reported one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocker: Option<String>,
|
||||
}
|
||||
|
||||
impl BucketScanProgressSource {
|
||||
@@ -120,6 +133,21 @@ pub fn aggregate_bucket_scan_progress(
|
||||
}
|
||||
}
|
||||
let complete = selected.len() == expected.len() && selected.values().all(|s| s.stage == BucketScanStage::Completed);
|
||||
let blockers = selected
|
||||
.values()
|
||||
.filter_map(|sample| sample.blocker.as_deref())
|
||||
.filter(|blocker| !blocker.is_empty())
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
let blocker = if complete {
|
||||
None
|
||||
} else {
|
||||
match blockers.len() {
|
||||
// Samples written before the blocker field existed remain readable.
|
||||
0 => Some("unknown".to_owned()),
|
||||
1 => blockers.first().map(|blocker| (*blocker).to_owned()),
|
||||
_ => Some("multiple".to_owned()),
|
||||
}
|
||||
};
|
||||
Some(BucketScanProgress {
|
||||
stage: if complete {
|
||||
BucketScanStage::Completed
|
||||
@@ -135,6 +163,9 @@ pub fn aggregate_bucket_scan_progress(
|
||||
size,
|
||||
sources_observed: u64::try_from(selected.len()).ok()?,
|
||||
sources_total: u64::try_from(expected.len()).ok()?,
|
||||
partial: !complete,
|
||||
converged: complete,
|
||||
blocker,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -158,6 +189,7 @@ mod tests {
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(77),
|
||||
blocker: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,6 +240,43 @@ mod tests {
|
||||
assert!(aggregate_bucket_scan_progress([sample(0), huge], &[(0, 0), (0, 1)]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_progress_reports_blocker_and_completion_converges() {
|
||||
let mut scanning = sample(0);
|
||||
scanning.blocker = Some("object_budget".into());
|
||||
let partial = aggregate_bucket_scan_progress([scanning], &[(0, 0)]).expect("partial progress");
|
||||
assert!(partial.partial);
|
||||
assert!(!partial.converged);
|
||||
assert_eq!(partial.blocker.as_deref(), Some("object_budget"));
|
||||
|
||||
let mut one = sample(0);
|
||||
one.stage = BucketScanStage::Completed;
|
||||
one.blocker = None;
|
||||
let mut two = sample(1);
|
||||
two.stage = BucketScanStage::Completed;
|
||||
two.blocker = None;
|
||||
let done = aggregate_bucket_scan_progress([one, two], &[(0, 0), (0, 1)]).expect("completed progress");
|
||||
assert!(!done.partial);
|
||||
assert!(done.converged);
|
||||
assert_eq!(done.blocker, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aggregate_progress_defaults_new_state_for_old_readers() {
|
||||
let decoded: BucketScanProgress = serde_json::from_value(serde_json::json!({
|
||||
"stage": "scanning",
|
||||
"updated_at": 1000,
|
||||
"objects": 7,
|
||||
"size": 77,
|
||||
"sources_observed": 1,
|
||||
"sources_total": 2
|
||||
}))
|
||||
.expect("legacy aggregate progress");
|
||||
assert!(!decoded.partial);
|
||||
assert!(!decoded.converged);
|
||||
assert_eq!(decoded.blocker, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_cannot_cross_bucket_incarnation_or_movement_generation() {
|
||||
let one = sample(0);
|
||||
|
||||
@@ -226,6 +226,18 @@ mod tests {
|
||||
.await?;
|
||||
|
||||
let resumed_client = env.create_s3_client();
|
||||
let pending = resumed_client
|
||||
.list_multipart_uploads()
|
||||
.bucket(bucket)
|
||||
.prefix(&key)
|
||||
.send()
|
||||
.await?;
|
||||
let upload = pending
|
||||
.uploads()
|
||||
.iter()
|
||||
.find(|upload| upload.key() == Some(key.as_str()) && upload.upload_id() == Some(upload_id))
|
||||
.ok_or("ListMultipartUploads omitted the pending upload")?;
|
||||
assert_eq!(upload.storage_class().map(StorageClass::as_str), Some(class_name));
|
||||
let before_retry = resumed_client
|
||||
.list_parts()
|
||||
.bucket(bucket)
|
||||
|
||||
@@ -56,6 +56,15 @@ async fn admin<T: DeserializeOwned>(env: &RustFSTestEnvironment, resource: &str)
|
||||
Ok(response.error_for_status()?.json().await?)
|
||||
}
|
||||
|
||||
async fn account_bucket(env: &RustFSTestEnvironment, resource: &str) -> TestResult<serde_json::Value> {
|
||||
let account: serde_json::Value = admin(env, resource).await?;
|
||||
account["buckets"]
|
||||
.as_array()
|
||||
.and_then(|buckets| buckets.iter().find(|bucket| bucket["name"] == BUCKET))
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("accountinfo omitted visible bucket {BUCKET}").into())
|
||||
}
|
||||
|
||||
async fn inventory(client: &Client) -> TestResult<BTreeMap<String, u64>> {
|
||||
let mut pages = client.list_objects_v2().bucket(BUCKET).max_keys(37).into_paginator().send();
|
||||
let mut sizes = BTreeMap::new();
|
||||
@@ -135,6 +144,20 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
// The checkpoint and its display companion commit independently. Wait for
|
||||
// both before terminating the process to exercise the actual first-scan API.
|
||||
let row = account_bucket(&env, "accountinfo?view=snapshot").await?;
|
||||
if row["initial_scan"] != true {
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
continue;
|
||||
}
|
||||
assert!(row.get("objects").is_none() && row.get("size").is_none(), "{row}");
|
||||
let progress = &row["scan_progress"];
|
||||
assert_eq!(progress["sources_observed"], 1);
|
||||
assert_eq!(progress["sources_total"], 1);
|
||||
assert!(progress["updated_at"].as_u64().is_some_and(|ts| ts > 0));
|
||||
assert_eq!(progress["partial"], true);
|
||||
assert_eq!(progress["converged"], false);
|
||||
assert!(!status.disk_io_budget.is_empty(), "scanner never admitted disk I/O");
|
||||
break Ok::<_, Box<dyn std::error::Error + Send + Sync>>(());
|
||||
}
|
||||
@@ -143,6 +166,8 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "scanner did not re-enter the bucket after exhausting the fixed runtime budget")??;
|
||||
let ordinary = account_bucket(&env, "accountinfo").await?;
|
||||
assert!(ordinary.get("initial_scan").is_none(), "default account view opted into initial progress");
|
||||
let partial: DataUsageInfo = admin(&env, "datausageinfo").await?;
|
||||
assert!(
|
||||
partial
|
||||
@@ -192,6 +217,16 @@ async fn certifies_wide_directory_after_mid_scan_process_restart() -> TestResult
|
||||
let bytes = expected.values().sum::<u64>();
|
||||
assert_eq!((bucket.objects_count, bucket.size), (count, bytes));
|
||||
assert_eq!((usage.objects_total_count, usage.objects_total_size), (count, bytes));
|
||||
let completed = account_bucket(&env, "accountinfo?view=snapshot").await?;
|
||||
assert_eq!(completed["initial_scan"], false);
|
||||
assert!(completed.get("scan_progress").is_none());
|
||||
assert_eq!(completed["objects"], count);
|
||||
assert_eq!(completed["size"], bytes);
|
||||
let snapshot: serde_json::Value = admin(&env, "datausageinfo?view=snapshot").await?;
|
||||
assert_eq!(snapshot["snapshot_view"], true);
|
||||
assert_eq!(snapshot["buckets_usage"][BUCKET]["objects_count"], count);
|
||||
assert_eq!(snapshot["buckets_usage"][BUCKET]["size"], bytes);
|
||||
assert!(snapshot["initial_scan_progress"].get(BUCKET).is_none());
|
||||
eprintln!(
|
||||
"PIDs {first_pid}/{second_pid}, runtime-limited cycles since restart {}, certificate epoch {} cycle {}, S3 and admin {} objects/{} bytes",
|
||||
status.metrics.partial_cycles_runtime, certificate.epoch, certificate.cycle, count, bytes
|
||||
|
||||
@@ -192,8 +192,8 @@ pub mod bucket {
|
||||
BUCKET_REPLICATION_CONFIG, BUCKET_REQUEST_PAYMENT_CONFIG, BUCKET_SSECONFIG, BUCKET_TABLE_CATALOG_META_PREFIX,
|
||||
BUCKET_TABLE_CATALOG_TABLE_BUCKETS_PREFIX, BUCKET_TABLE_CONFIG, BUCKET_TABLE_RESERVED_PREFIX, BUCKET_TAGGING_CONFIG,
|
||||
BUCKET_TARGETS_FILE, BUCKET_VECTOR_STORAGE_PREFIX, BUCKET_VERSIONING_CONFIG, BUCKET_WEBSITE_CONFIG, BucketMetadata,
|
||||
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, load_bucket_metadata,
|
||||
table_catalog_path_hash, unreadable_config_refusal,
|
||||
ConfigState, OBJECT_LOCK_CONFIG, UnreadableBucketConfig, is_unreadable_config_error, is_vector_pagination_session,
|
||||
load_bucket_metadata, table_catalog_path_hash, unreadable_config_refusal,
|
||||
};
|
||||
pub use crate::bucket::metadata::{
|
||||
BUCKET_DURABILITY_CONFIG, BUCKET_ETAG_CONFIG, BUCKET_ON_DEMAND_MIGRATION_CONFIG, MAX_SWIFT_METADATA_COUNT,
|
||||
@@ -453,8 +453,9 @@ pub mod data_usage {
|
||||
};
|
||||
#[cfg(feature = "test-util")]
|
||||
pub use crate::data_usage::seed_bucket_usage_memory_for_test;
|
||||
pub use crate::data_usage::{AdminUsageSnapshot, load_admin_usage_snapshot};
|
||||
pub use crate::data_usage::{
|
||||
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME,
|
||||
BucketUsagePendingReason, BucketUsageStatus, BucketUsageUnavailableReason, DATA_USAGE_CACHE_NAME, PutUsageReceipt,
|
||||
apply_bucket_usage_memory_overlay, compute_bucket_usage, init_compression_total_memory_from_backend,
|
||||
invalidate_admin_data_usage_snapshot_cache, invalidate_data_usage_snapshot_cache, live_bucket_usage_computations,
|
||||
load_admin_data_usage_from_backend_cached, load_admin_data_usage_with_memory_overlay,
|
||||
|
||||
@@ -5692,26 +5692,25 @@ const _MAX_RESTORE_OBJECT_REQUEST_SIZE: i64 = 2 << 20;
|
||||
|
||||
/// Builds an exact-version lifecycle delete target with the concrete
|
||||
/// generation observed by the evaluator. The null S3 version ID is reusable,
|
||||
/// so null data versions additionally require a write-unique data directory.
|
||||
/// so a null data version needs a body revision that survives pool movement.
|
||||
pub fn lifecycle_version_delete_target(oi: &ObjectInfo) -> Option<ObjectToDelete> {
|
||||
let version_id = oi.version_id?;
|
||||
if version_id.is_nil()
|
||||
&& ((!oi.delete_marker && oi.data_dir.is_none_or(|data_dir| data_dir.is_nil()))
|
||||
|| (oi.delete_marker && oi.mod_time.is_none_or(|mod_time| mod_time == OffsetDateTime::UNIX_EPOCH)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let target = ObjectToDelete {
|
||||
object_name: oi.name.clone(),
|
||||
version_id: Some(version_id),
|
||||
..Default::default()
|
||||
};
|
||||
Some(if version_id.is_nil() {
|
||||
target.with_expected_identity(oi.data_dir, oi.mod_time, oi.delete_marker)
|
||||
if !version_id.is_nil() {
|
||||
return Some(target);
|
||||
}
|
||||
let revision = if oi.delete_marker {
|
||||
oi.mod_time.filter(|time| *time != OffsetDateTime::UNIX_EPOCH)?;
|
||||
oi.data_dir
|
||||
} else {
|
||||
target
|
||||
})
|
||||
oi.data_dir.filter(|id| !id.is_nil())?;
|
||||
oi.logical_body_revision()
|
||||
};
|
||||
Some(target.with_expected_identity(revision, oi.mod_time, oi.delete_marker))
|
||||
}
|
||||
|
||||
pub async fn eval_action_from_lifecycle(
|
||||
|
||||
@@ -557,6 +557,23 @@ pub fn table_bucket_catalog_metadata_prefix(bucket: &str) -> String {
|
||||
/// Internal physical names are reserved even if their identity record is missing.
|
||||
pub const BUCKET_VECTOR_STORAGE_PREFIX: &str = "rustfs-v-";
|
||||
|
||||
/// Server-owned pagination sessions in physical Vector buckets carry no dataset quota charge.
|
||||
pub fn is_vector_pagination_session(bucket: &str, object: &str) -> bool {
|
||||
if !bucket.starts_with(BUCKET_VECTOR_STORAGE_PREFIX) {
|
||||
return false;
|
||||
}
|
||||
let Some(path) = object.strip_prefix(".rustfs-table/") else {
|
||||
return false;
|
||||
};
|
||||
let Some((table, file)) = path.split_once("/query-results/") else {
|
||||
return false;
|
||||
};
|
||||
Uuid::parse_str(table).is_ok_and(|id| !id.is_nil())
|
||||
&& file
|
||||
.strip_suffix(".session")
|
||||
.is_some_and(|id| id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct BucketIdentityConfigError(&'static str);
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ use crate::storage_api_contracts::heal::HealOperations as _;
|
||||
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
|
||||
use crate::store::{ECStore, await_bucket_namespace_operation};
|
||||
use futures::future::join_all;
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
use rustfs_gateway_types::cors_tagging::{PersistedCorsConfiguration as CORSConfiguration, PersistedTagging as Tagging};
|
||||
use rustfs_gateway_types::persistence::{
|
||||
PersistedAccelerateConfiguration as AccelerateConfiguration,
|
||||
@@ -51,7 +52,7 @@ use std::{
|
||||
};
|
||||
use time::OffsetDateTime;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use tokio::time::sleep;
|
||||
use tokio::time::{Instant, sleep};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::{error, warn};
|
||||
use uuid::Uuid;
|
||||
@@ -4232,6 +4233,70 @@ impl BucketMetadataSys {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read configured quota limits for observability, in input order.
|
||||
///
|
||||
/// An unavailable or unset limit is reported as zero. Cache misses use the
|
||||
/// regular metadata lookup, including its namespace and publication fences.
|
||||
/// Returns `None` after the observation's deadline. Already admitted reads
|
||||
/// finish their metadata publication before the result is discarded.
|
||||
pub async fn quota_limits_for_metrics<'a>(
|
||||
&self,
|
||||
mut buckets: impl ExactSizeIterator<Item = &'a str> + Send,
|
||||
deadline: Option<Instant>,
|
||||
) -> Option<Vec<u64>> {
|
||||
const CACHE_BATCH_SIZE: usize = 256;
|
||||
const MAX_COLD_READS: usize = 4;
|
||||
|
||||
let expired = || deadline.is_some_and(|deadline| Instant::now() >= deadline);
|
||||
if expired() {
|
||||
return None;
|
||||
}
|
||||
let mut limits = Vec::with_capacity(buckets.len());
|
||||
let mut missing = Vec::new();
|
||||
while buckets.len() != 0 {
|
||||
// Read only the quota field under the map lock. Release it between
|
||||
// batches and before acquiring any lazy-load or namespace locks.
|
||||
let cached = self.metadata_map.read().await;
|
||||
if expired() {
|
||||
return None;
|
||||
}
|
||||
for bucket in buckets.by_ref().take(CACHE_BATCH_SIZE) {
|
||||
let limit = match cached.get(bucket) {
|
||||
Some(metadata) => metadata
|
||||
.quota_config
|
||||
.as_ref()
|
||||
.and_then(BucketQuota::get_quota_limit)
|
||||
.unwrap_or(0),
|
||||
None => {
|
||||
missing.push((limits.len(), bucket));
|
||||
0
|
||||
}
|
||||
};
|
||||
limits.push(limit);
|
||||
}
|
||||
}
|
||||
|
||||
let mut missing = missing.into_iter();
|
||||
let mut reads = FuturesUnordered::new();
|
||||
loop {
|
||||
for (index, bucket) in missing.by_ref().take_while(|_| !expired()).take(MAX_COLD_READS - reads.len()) {
|
||||
reads.push(async move {
|
||||
let limit = self
|
||||
.get_quota_config(bucket)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|(quota, _)| quota.get_quota_limit());
|
||||
(index, limit.unwrap_or(0))
|
||||
});
|
||||
}
|
||||
let Some((index, limit)) = reads.next().await else {
|
||||
break;
|
||||
};
|
||||
limits[index] = limit;
|
||||
}
|
||||
(!expired()).then_some(limits)
|
||||
}
|
||||
|
||||
async fn cached_quota_config_and_incarnation(&self, bucket: &str) -> Result<Option<CachedQuotaMetadataSnapshot>> {
|
||||
let metadata = {
|
||||
let metadata_map = self.metadata_map.read().await;
|
||||
@@ -6615,6 +6680,92 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn metrics_quota_batch_reads_cache_and_falls_back_to_persisted_limits() {
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let (_dirs, store) = isolated_store_over_temp_disks().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let cold = "metrics-quota-cold";
|
||||
store
|
||||
.make_bucket(cold, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create cold quota fixture");
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(cold)
|
||||
.await
|
||||
.expect("read cold bucket incarnation");
|
||||
store
|
||||
.update_bucket_metadata_config_for_incarnation_validated(
|
||||
cold,
|
||||
"quota.json",
|
||||
br#"{"quota":4096}"#.to_vec(),
|
||||
incarnation,
|
||||
|| Ok(()),
|
||||
)
|
||||
.await
|
||||
.expect("persist cold quota fixture");
|
||||
|
||||
let sys = BucketMetadataSys::new(store.clone());
|
||||
let warm = "metrics-quota-warm";
|
||||
let mut cached = BucketMetadata::new(warm);
|
||||
cached.quota_config = Some(BucketQuota::new(Some(2048)));
|
||||
let invalid = "metrics-quota-invalid";
|
||||
let mut malformed = BucketMetadata::new(invalid);
|
||||
malformed.quota_config_json = b"{not-json".to_vec();
|
||||
sys.metadata_map.write().await.extend([
|
||||
(warm.to_string(), Arc::new(cached)),
|
||||
(invalid.to_string(), Arc::new(malformed)),
|
||||
]);
|
||||
|
||||
let buckets = [cold, warm, invalid, warm];
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
|
||||
Some(vec![4096, 2048, 0, 2048])
|
||||
);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(buckets.into_iter(), None).await,
|
||||
Some(vec![4096, 2048, 0, 2048])
|
||||
);
|
||||
assert_eq!(
|
||||
sys.quota_limits_for_metrics(std::iter::repeat_n(warm, 257), None).await,
|
||||
Some(vec![2048; 257]),
|
||||
);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn expired_metrics_quota_batch_drains_admitted_reads_without_starting_more() {
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let (_dirs, store) = isolated_store_over_temp_disks().await;
|
||||
let sys = BucketMetadataSys::new(store.clone());
|
||||
let names = ["expired-q1", "expired-q2", "expired-q3", "expired-q4", "expired-q5"];
|
||||
let mut guards = Vec::new();
|
||||
for name in &names[..4] {
|
||||
guards.push(sys.lazy_load_lock(name).lock_owned().await);
|
||||
}
|
||||
|
||||
tokio::time::pause();
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
let mut batch = std::pin::pin!(sys.quota_limits_for_metrics(names.into_iter(), Some(deadline)));
|
||||
assert!(futures::poll!(&mut batch).is_pending());
|
||||
tokio::time::advance(Duration::from_secs(2)).await;
|
||||
// The deadline alone cannot cancel a read holding or awaiting a metadata lock.
|
||||
assert!(futures::poll!(&mut batch).is_pending());
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 0);
|
||||
drop(guards);
|
||||
tokio::time::resume();
|
||||
|
||||
assert_eq!(batch.await, None);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
|
||||
assert_eq!(sys.quota_limits_for_metrics([names[4]].into_iter(), Some(deadline)).await, None,);
|
||||
assert_eq!(sys.lazy_disk_loads.load(Ordering::Relaxed), 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn validated_config_update_rejects_a_different_bucket_incarnation() {
|
||||
|
||||
@@ -782,12 +782,36 @@ impl QuotaReservation {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Complete the reservation after object publication. V1 growth is
|
||||
/// already charged, so its terminal record can drain in the background.
|
||||
/// Shrinking writes settle inline so they can signal the recount promptly.
|
||||
pub(crate) async fn commit(mut self) {
|
||||
self.state = ReservationState::Committed;
|
||||
let Some(ledger) = self.ledger.as_ref() else {
|
||||
return;
|
||||
};
|
||||
crate::store::list_objects::observe_scanner_namespace_mutations(ledger.bucket(), 1);
|
||||
if let ReservationLedgerData::Single(data) = ledger
|
||||
&& data.reservation.new_size >= data.reservation.old_size
|
||||
&& let Ok(slot) = Arc::clone(&data.store.ctx.v1_quota_settlement_slots).try_acquire_owned()
|
||||
{
|
||||
let ctx = Arc::clone(&data.store.ctx);
|
||||
drop(ctx.spawn_detached_mutation(async move {
|
||||
let _slot = slot;
|
||||
self.finish_commit().await;
|
||||
if let Some(ledger) = self.ledger.take() {
|
||||
retry_settlement(&ledger, true, self.metadata_guard.as_ref()).await;
|
||||
}
|
||||
}));
|
||||
return;
|
||||
}
|
||||
self.finish_commit().await;
|
||||
}
|
||||
|
||||
async fn finish_commit(&mut self) {
|
||||
let Some(ledger) = self.ledger.as_ref() else {
|
||||
return;
|
||||
};
|
||||
match settle(ledger, true, self.metadata_guard.as_ref()).await {
|
||||
Ok(()) => self.ledger = None,
|
||||
Err(err) => log_deferred_settlement(ledger, "commit_deferred", &err),
|
||||
@@ -829,13 +853,17 @@ impl Drop for QuotaReservation {
|
||||
};
|
||||
runtime.spawn(async move {
|
||||
let _shard_operation_guard = shard_operation_guard;
|
||||
if let Err(err) = settle(&ledger, committed, metadata_guard.as_ref()).await {
|
||||
log_deferred_settlement(&ledger, "background_retry_failed", &err);
|
||||
}
|
||||
retry_settlement(&ledger, committed, metadata_guard.as_ref()).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn retry_settlement(ledger: &ReservationLedgerData, committed: bool, metadata_guard: Option<&Arc<NamespaceLockGuard>>) {
|
||||
if let Err(err) = settle(ledger, committed, metadata_guard).await {
|
||||
log_deferred_settlement(ledger, "background_retry_failed", &err);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn begin(
|
||||
ctx: &crate::runtime::instance::InstanceContext,
|
||||
bucket: &str,
|
||||
@@ -849,8 +877,9 @@ pub(crate) async fn begin(
|
||||
// A lockless cache PUT is only taken when the bucket has no quota, so it
|
||||
// reserves nothing and needs no metadata-transaction lock.
|
||||
let lockless_cache = opts.is_lockless_cache_write() && snapshot_admission.is_none();
|
||||
if lockless_cache || crate::bucket::utils::is_meta_bucketname(bucket) {
|
||||
if !lockless_cache {
|
||||
let meta_bucket = crate::bucket::utils::is_meta_bucketname(bucket);
|
||||
if lockless_cache || meta_bucket || crate::bucket::metadata::is_vector_pagination_session(bucket, object) {
|
||||
if meta_bucket && !lockless_cache {
|
||||
let meta_bucket_fast_path_started = rustfs_io_metrics::put_stage_timer();
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_QUOTA_BEGIN_META_BUCKET_FAST_PATH,
|
||||
@@ -1080,15 +1109,11 @@ fn quota_cache_reason(quota: Option<&crate::bucket::quota::BucketQuota>) -> &'st
|
||||
}
|
||||
|
||||
pub(crate) async fn replaced_logical_size(set_disks: &SetDisks, bucket: &str, object: &str, opts: &ObjectOptions) -> Result<u64> {
|
||||
if opts.versioned && !opts.version_suspended && opts.version_id.is_none() {
|
||||
let Some(version_id) = opts.replaced_version_id()? else {
|
||||
return Ok(0);
|
||||
}
|
||||
let version_id = opts
|
||||
.version_id
|
||||
.clone()
|
||||
.or_else(|| opts.version_suspended.then(|| Uuid::nil().to_string()));
|
||||
};
|
||||
let lookup_opts = ObjectOptions {
|
||||
version_id,
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
@@ -2995,6 +3020,79 @@ mod tests {
|
||||
.expect("owner guard");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn v1_published_growth_settles_in_a_bounded_tracked_task() {
|
||||
let (_directories, job) = reconciliation_fixture(100).await;
|
||||
job.run().await.expect("bootstrap");
|
||||
let object = ledger_object(&job.bucket);
|
||||
let slots = &job.store.ctx.v1_quota_settlement_slots;
|
||||
let capacity = slots.available_permits();
|
||||
let mut reservation = quota_reservation(&job, 0, 1).await.expect("durable reservation");
|
||||
reservation.mark_commit_started().await.expect("durable marker");
|
||||
let Some(ReservationLedgerData::Single(data)) = reservation.ledger.as_ref() else {
|
||||
panic!("expected a v1 reservation");
|
||||
};
|
||||
let operation_id = data.operation_id;
|
||||
let operation = job
|
||||
.store
|
||||
.new_ns_lock(RUSTFS_META_BUCKET, &operation_lock_object(&object, operation_id))
|
||||
.await
|
||||
.expect("operation lock");
|
||||
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
|
||||
.await
|
||||
.expect("block settlement after the marker");
|
||||
tokio::time::timeout(Duration::from_secs(1), reservation.commit())
|
||||
.await
|
||||
.expect("publication must not wait for the blocked v1 settlement");
|
||||
assert_eq!(slots.available_permits(), capacity - 1);
|
||||
assert_eq!(job.store.ctx.detached_mutation_count(), 1);
|
||||
assert!(operation.get_write_lock_quiet(Duration::from_millis(10)).await.is_err());
|
||||
let pending = read_test_ledger(&job).await;
|
||||
assert_eq!(pending.accounted_usage, 11);
|
||||
assert!(pending.reservations[&operation_id].commit_started);
|
||||
|
||||
fail_next_quota_ledger_save_for_test();
|
||||
drop(guard);
|
||||
assert!(job.store.ctx.wait_for_detached_mutations(Duration::from_secs(10)).await);
|
||||
let settled = read_test_ledger(&job).await;
|
||||
assert_eq!(settled.accounted_usage, 11);
|
||||
assert!(settled.reservations.is_empty(), "the tracked task owns the retry");
|
||||
assert_eq!(slots.available_permits(), capacity);
|
||||
|
||||
let _full = Arc::clone(slots)
|
||||
.try_acquire_many_owned(capacity.try_into().expect("slot count fits"))
|
||||
.expect("fill the background budget");
|
||||
let mut reservation = quota_reservation(&job, 0, 0).await.expect("second reservation");
|
||||
reservation.mark_commit_started().await.expect("second marker");
|
||||
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
|
||||
.await
|
||||
.expect("block the inline fallback");
|
||||
let mut fallback = Box::pin(reservation.commit());
|
||||
assert!(futures::poll!(fallback.as_mut()).is_pending());
|
||||
assert_eq!(job.store.ctx.detached_mutation_count(), 0);
|
||||
drop(guard);
|
||||
tokio::time::timeout(Duration::from_secs(10), fallback)
|
||||
.await
|
||||
.expect("inline settlement completes");
|
||||
assert!(read_test_ledger(&job).await.reservations.is_empty());
|
||||
drop(_full);
|
||||
|
||||
let mut reservation = quota_reservation(&job, 1, 0).await.expect("shrinking reservation");
|
||||
reservation.mark_commit_started().await.expect("shrinking marker");
|
||||
let guard = lock_v1_ledger(&job.store, &object, "quota_ledger_test_hold", get_lock_acquire_timeout())
|
||||
.await
|
||||
.expect("block the shrinking settlement");
|
||||
let mut shrink = Box::pin(reservation.commit());
|
||||
assert!(futures::poll!(shrink.as_mut()).is_pending());
|
||||
assert_eq!(slots.available_permits(), capacity);
|
||||
drop(guard);
|
||||
tokio::time::timeout(Duration::from_secs(10), shrink)
|
||||
.await
|
||||
.expect("shrinking settlement completes inline");
|
||||
assert!(read_test_ledger(&job).await.reconcile_required);
|
||||
}
|
||||
|
||||
async fn queue_v1_test_admissions(
|
||||
job: &ReconcileJob,
|
||||
names: &[&str],
|
||||
@@ -3526,6 +3624,7 @@ mod tests {
|
||||
"shrink" | "grow" => {
|
||||
reservation.mark_commit_started().await.expect("commit marker");
|
||||
reservation.commit().await;
|
||||
assert!(job.store.ctx.wait_for_detached_mutations(Duration::from_secs(10)).await);
|
||||
None
|
||||
}
|
||||
"reap" => {
|
||||
|
||||
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
|
||||
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
|
||||
};
|
||||
use super::replication_resyncer::{
|
||||
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
|
||||
replicate_object_with_outcome, update_resync_status_cas,
|
||||
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
|
||||
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
|
||||
};
|
||||
use super::replication_state::ReplicationStats;
|
||||
use super::replication_storage_boundary::{
|
||||
@@ -1329,12 +1329,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let storage = self.storage.clone();
|
||||
let stats = self.stats.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut rx = rx;
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1389,12 +1391,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let stats = self.stats.clone();
|
||||
let storage = self.storage.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut rx = rx;
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1434,6 +1438,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let stats = self.stats.clone();
|
||||
let storage = self.storage.clone();
|
||||
let in_flight = self.in_flight.clone();
|
||||
let mrf_save_tx = self.mrf_save_tx.clone();
|
||||
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
@@ -1453,7 +1458,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
let Some(operation) = operation else { break };
|
||||
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
self.task_handles.lock().await.push(handle);
|
||||
@@ -1935,7 +1941,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
|
||||
process_replication_operation(
|
||||
operation,
|
||||
stats.clone(),
|
||||
self.storage.clone(),
|
||||
self.in_flight.clone(),
|
||||
&self.mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1953,7 +1966,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
|
||||
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1970,7 +1984,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
|
||||
) {
|
||||
while let Some(operation) = rx.recv().await {
|
||||
let _active = ActiveWorkerGuard::new(active_counter.clone());
|
||||
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
|
||||
process_replication_operation(
|
||||
operation,
|
||||
stats.clone(),
|
||||
self.storage.clone(),
|
||||
self.in_flight.clone(),
|
||||
&self.mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2539,6 +2560,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
|
||||
stats: Arc<ReplicationStats>,
|
||||
storage: Arc<S>,
|
||||
in_flight: Arc<ReplicationInFlight>,
|
||||
mrf_save_tx: &Sender<MrfReplicateEntry>,
|
||||
) {
|
||||
match operation {
|
||||
ReplicationOperation::Object(obj_info) => {
|
||||
@@ -2548,7 +2570,14 @@ async fn process_replication_operation<S: ReplicationStorage>(
|
||||
}
|
||||
ReplicationOperation::Delete(del_info) => {
|
||||
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
|
||||
replicate_delete(*del_info, storage).await;
|
||||
// The delete request already succeeded, so a source lock that is
|
||||
// still held (a bulk delete keeps its key locks until the whole
|
||||
// batch commits) must not cost the replication: journal it for
|
||||
// the next MRF replay.
|
||||
let retry_entry = del_info.to_mrf_entry();
|
||||
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
|
||||
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4506,6 +4535,102 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
|
||||
async fn delete_worker_journal(
|
||||
delete: DeletedObjectReplicationInfo,
|
||||
writeback_error: EcstoreError,
|
||||
) -> Vec<MrfReplicateEntry> {
|
||||
let shared = empty_resync_shared_state();
|
||||
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
|
||||
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
|
||||
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
|
||||
|
||||
process_replication_operation(
|
||||
ReplicationOperation::Delete(Box::new(delete)),
|
||||
Arc::new(ReplicationStats::new()),
|
||||
storage,
|
||||
Arc::new(ReplicationInFlight::default()),
|
||||
&mrf_save_tx,
|
||||
)
|
||||
.await;
|
||||
|
||||
drop(mrf_save_tx);
|
||||
let mut journaled = Vec::new();
|
||||
while let Some(entry) = mrf_save_rx.recv().await {
|
||||
journaled.push(entry);
|
||||
}
|
||||
journaled
|
||||
}
|
||||
|
||||
fn purged_on_target_delete(
|
||||
arn: &str,
|
||||
version_id: Uuid,
|
||||
target_status: VersionPurgeStatusType,
|
||||
) -> DeletedObjectReplicationInfo {
|
||||
DeletedObjectReplicationInfo {
|
||||
bucket: "source".to_string(),
|
||||
delete_object: ReplicationDeletedObject {
|
||||
object_name: "purged".to_string(),
|
||||
version_id: Some(version_id),
|
||||
replication_state: Some(ReplicationState {
|
||||
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
|
||||
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
op_type: ReplicationType::Delete,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
|
||||
let arn = "arn:test";
|
||||
let version_id = Uuid::new_v4();
|
||||
// A bulk delete of the same key still holds the object lock.
|
||||
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
|
||||
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
|
||||
));
|
||||
|
||||
let journaled =
|
||||
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
|
||||
|
||||
assert_eq!(
|
||||
journaled.len(),
|
||||
1,
|
||||
"a delete whose result never reached the source must be kept for replay"
|
||||
);
|
||||
let entry = &journaled[0];
|
||||
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
|
||||
assert_eq!(entry.version_id, Some(version_id));
|
||||
assert_eq!(entry.op, MrfOpKind::Delete);
|
||||
assert_eq!(entry.target_arns, vec![arn.to_string()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
|
||||
let arn = "arn:test";
|
||||
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
|
||||
|
||||
let completed = delete_worker_journal(
|
||||
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
|
||||
source_gone(),
|
||||
)
|
||||
.await;
|
||||
assert!(completed.is_empty(), "a completed delete must not be replayed");
|
||||
|
||||
let target_pending = delete_worker_journal(
|
||||
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
|
||||
source_gone(),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
target_pending.is_empty(),
|
||||
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_worker_preserves_persisted_admission_without_live_config() {
|
||||
let arn = "arn:test";
|
||||
|
||||
@@ -2422,12 +2422,40 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
|
||||
let _ = replicate_delete_with_outcome(dobj, storage).await;
|
||||
}
|
||||
|
||||
/// How one delete replication attempt ended.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum DeleteReplicationAttempt {
|
||||
/// Every admitted target finished and the source state was persisted.
|
||||
Completed,
|
||||
/// The attempt did not finish for a reason another path already owns: a
|
||||
/// target failure is recorded in the persisted state for the scanner, and
|
||||
/// a force delete or delete-marker purge journals its own intent.
|
||||
Unfinished,
|
||||
/// A source-side lock or read kept the attempt from running, or from
|
||||
/// persisting its result. Nothing durable records that, so the caller must
|
||||
/// keep the delete for a later attempt.
|
||||
SourceDeferred,
|
||||
}
|
||||
|
||||
impl DeleteReplicationAttempt {
|
||||
fn from_finished(finished: bool) -> Self {
|
||||
if finished { Self::Completed } else { Self::Unfinished }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
dobj: DeletedObjectReplicationInfo,
|
||||
storage: Arc<S>,
|
||||
) -> bool {
|
||||
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
|
||||
}
|
||||
|
||||
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
|
||||
dobj: DeletedObjectReplicationInfo,
|
||||
storage: Arc<S>,
|
||||
) -> DeleteReplicationAttempt {
|
||||
if dobj.delete_object.force_delete {
|
||||
return replicate_force_delete_to_targets(&dobj, storage).await;
|
||||
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
|
||||
}
|
||||
|
||||
let bucket = dobj.bucket.clone();
|
||||
@@ -2472,7 +2500,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return false;
|
||||
return DeleteReplicationAttempt::Unfinished;
|
||||
}
|
||||
};
|
||||
let target_arns = dobj.admitted_target_arns();
|
||||
@@ -2480,7 +2508,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
// Batch expiry can return an empty state after removing the source.
|
||||
// It owes no remote work or local writeback. Persisted target admission
|
||||
// must still be honored even when the live configuration is gone.
|
||||
return true;
|
||||
return DeleteReplicationAttempt::Completed;
|
||||
}
|
||||
|
||||
if dobj.delete_object.delete_marker
|
||||
@@ -2502,7 +2530,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
reason = "source_not_delete_marker",
|
||||
"Skipping stale delete-marker replication"
|
||||
);
|
||||
return true;
|
||||
return DeleteReplicationAttempt::Completed;
|
||||
}
|
||||
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
|
||||
debug!(
|
||||
@@ -2520,7 +2548,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
// purge-intent replay landing here on purpose). Purge instead
|
||||
// of just skipping; the result decides whether an MRF replay
|
||||
// may acknowledge the entry.
|
||||
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
|
||||
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
|
||||
}
|
||||
Err(err) => {
|
||||
// A transient source error (lock timeout, IO error) must not
|
||||
@@ -2529,7 +2557,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
// target mint one more delete marker (rustfs#6823). Fail the
|
||||
// entry without touching the target; the MRF replay / heal
|
||||
// scanner retries once the source is readable again.
|
||||
debug!(
|
||||
warn!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2554,7 +2582,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return false;
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2565,7 +2593,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
{
|
||||
Ok(ns_lock) => ns_lock,
|
||||
Err(e) => {
|
||||
debug!(
|
||||
warn!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2589,14 +2617,14 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return false;
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
};
|
||||
|
||||
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
|
||||
Ok(lock_guard) => lock_guard,
|
||||
Err(e) => {
|
||||
debug!(
|
||||
warn!(
|
||||
event = EVENT_REPLICATION_DELETE_SKIPPED,
|
||||
component = LOG_COMPONENT_ECSTORE,
|
||||
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
|
||||
@@ -2620,7 +2648,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
user_agent: "Internal: [Replication]".to_string(),
|
||||
..Default::default()
|
||||
});
|
||||
return false;
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -2858,7 +2886,12 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
}
|
||||
};
|
||||
|
||||
replicate_delete_outcome(
|
||||
if !state_persisted {
|
||||
// The targets were driven, but the result never reached the source
|
||||
// metadata, so a scanner pass would still see the pre-attempt state.
|
||||
return DeleteReplicationAttempt::SourceDeferred;
|
||||
}
|
||||
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
|
||||
expected_targets,
|
||||
rinfos.targets.len(),
|
||||
state_persisted,
|
||||
@@ -2866,7 +2899,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
|
||||
// error returns early above instead of replicating unverified.
|
||||
true,
|
||||
&replication_status,
|
||||
)
|
||||
))
|
||||
}
|
||||
|
||||
/// Reads the source version addressed by `delete_marker_version_id` so a
|
||||
|
||||
@@ -2008,10 +2008,12 @@ fn sync_rendered_target_section(
|
||||
|
||||
fn encode_server_config_blob(cfg: &Config, seed: Option<&[u8]>) -> Result<Vec<u8>> {
|
||||
let mut root = seed.and_then(parse_object_seed).unwrap_or_default();
|
||||
root.insert(
|
||||
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
|
||||
super::vector_maintenance::encode(cfg)?,
|
||||
);
|
||||
if !super::vector_maintenance::is_default(cfg) || root.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS) {
|
||||
root.insert(
|
||||
rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS.into(),
|
||||
super::vector_maintenance::encode(cfg)?,
|
||||
);
|
||||
}
|
||||
|
||||
if !matches!(root.get("version"), Some(Value::String(v)) if !v.trim().is_empty()) {
|
||||
root.insert("version".to_string(), Value::String("33".to_string()));
|
||||
@@ -3595,6 +3597,7 @@ mod tests {
|
||||
replication_decision: String::new(),
|
||||
checksum: None,
|
||||
multipart_completion_replayed: false,
|
||||
put_usage: None,
|
||||
backfilled_old_current_size: None,
|
||||
ec_block_size: None,
|
||||
}
|
||||
@@ -6166,4 +6169,43 @@ mod tests {
|
||||
assert!(err.is_quorum_error(), "expected quorum error, got {err:?}");
|
||||
assert_eq!(store.heal_calls.load(Ordering::SeqCst), 1, "heal should still be attempted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encode_server_config_blob_omits_default_s3vectors_maintenance_and_preserves_explicit() {
|
||||
super::super::init();
|
||||
let default_cfg = Config::new();
|
||||
assert!(
|
||||
default_cfg.0.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
|
||||
"Config::new() after config::init() populates default KVS"
|
||||
);
|
||||
|
||||
let blob = encode_server_config_blob(&default_cfg, None).expect("encode default server config");
|
||||
let parsed: serde_json::Map<String, Value> = serde_json::from_slice(&blob).expect("parse encoded config");
|
||||
assert!(
|
||||
!parsed.contains_key(rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS),
|
||||
"unrelated config saves must not inject default s3vectors_maintenance"
|
||||
);
|
||||
|
||||
let mut enabled_cfg = Config::new();
|
||||
let mut kvs = super::super::vector_maintenance::DEFAULT_KVS.clone();
|
||||
kvs.insert(rustfs_config::ENABLE_KEY.into(), "on".into());
|
||||
kvs.insert(rustfs_config::S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT.into(), "vec-maint-user".into());
|
||||
super::super::vector_maintenance::install(&mut enabled_cfg, kvs);
|
||||
|
||||
let enabled_blob = encode_server_config_blob(&enabled_cfg, None).expect("encode enabled vector maintenance");
|
||||
let enabled_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&enabled_blob).expect("parse enabled config");
|
||||
assert_eq!(
|
||||
enabled_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
|
||||
Value::String("on".into())
|
||||
);
|
||||
|
||||
// Resetting back to defaults on an existing seed that already contains s3vectors_maintenance
|
||||
// must overwrite the existing entry back to "off".
|
||||
let reset_blob = encode_server_config_blob(&default_cfg, Some(&enabled_blob)).expect("encode reset config");
|
||||
let reset_parsed: serde_json::Map<String, Value> = serde_json::from_slice(&reset_blob).expect("parse reset config");
|
||||
assert_eq!(
|
||||
reset_parsed[rustfs_config::S3VECTORS_MAINTENANCE_SUB_SYS]["enable"],
|
||||
Value::String("off".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,6 +174,20 @@ pub(super) fn encode(config: &Config) -> Result<Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn is_default(config: &Config) -> bool {
|
||||
let Some(targets) = config.0.get(S3VECTORS_MAINTENANCE_SUB_SYS) else {
|
||||
return true;
|
||||
};
|
||||
if targets.len() != 1 || !targets.contains_key(DEFAULT_DELIMITER) {
|
||||
return false;
|
||||
}
|
||||
let Ok(normalized) = normalize(&targets[DEFAULT_DELIMITER]) else {
|
||||
return false;
|
||||
};
|
||||
normalized.get(ENABLE_KEY) == DEFAULT_KVS.get(ENABLE_KEY)
|
||||
&& normalized.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT) == DEFAULT_KVS.get(S3VECTORS_MAINTENANCE_EXECUTION_ACCOUNT)
|
||||
}
|
||||
|
||||
pub(super) fn equivalent(lhs: &Config, rhs: &Config) -> bool {
|
||||
matches!((encode(lhs), encode(rhs)), (Ok(lhs), Ok(rhs)) if lhs == rhs)
|
||||
}
|
||||
|
||||
@@ -164,7 +164,8 @@ async fn verified_shard(info: &FileInfo) -> Result<Vec<u8>> {
|
||||
}
|
||||
let mut reader = BitrotReader::new(Cursor::new(data.clone()), shard_size, HashAlgorithm::HighwayHash256S, false);
|
||||
if let Some(integrity) = &info.parts[0].integrity {
|
||||
let proof = PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT)?;
|
||||
let proof =
|
||||
PartProofReader::new(integrity.clone(), std::slice::from_ref(info), &[None], RUSTFS_META_BUCKET, OBJECT, None)?;
|
||||
reader.set_integrity(ShardVerifier::new(proof, info.erasure.index - 1, 0, None)?)?;
|
||||
}
|
||||
let mut shard = vec![0; shard_size];
|
||||
|
||||
@@ -142,7 +142,7 @@ const DECOMMISSION_ENTRY_CONCURRENCY_DEFAULT_CAP: usize = 8;
|
||||
const DECOMMISSION_ENTRY_CONCURRENCY_HARD_CAP: usize = 64;
|
||||
const DECOMMISSION_ENTRY_WORKERS_PER_SET: usize = 2;
|
||||
const DECOMMISSION_CAPACITY_SNAPSHOT_CONCURRENCY: usize = 4;
|
||||
const DECOMMISSION_META_PREFIXES: [&str; 3] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX];
|
||||
const DECOMMISSION_META_PREFIXES: [&str; 5] = [CONFIG_PREFIX, BUCKET_META_PREFIX, ILM_META_PREFIX, "s3tables", "s3vectors"];
|
||||
const DECOMMISSION_CAPACITY_LEGACY_MODEL_VERSION: u16 = 1;
|
||||
const DECOMMISSION_CAPACITY_TARGET_FENCE_MODEL_VERSION: u16 = 2;
|
||||
#[cfg(test)]
|
||||
@@ -13684,17 +13684,6 @@ impl ECStore {
|
||||
target_pool_indices: &[usize],
|
||||
admission: DecommissionCapacityAdmission,
|
||||
) -> Result<rustfs_lock::NamespaceLockGuard> {
|
||||
Ok(self
|
||||
.acquire_external_decommission_capacity_fence_with_active_source(target_pool_indices, admission)
|
||||
.await?
|
||||
.0)
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_external_decommission_capacity_fence_with_active_source(
|
||||
&self,
|
||||
target_pool_indices: &[usize],
|
||||
admission: DecommissionCapacityAdmission,
|
||||
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
|
||||
let save_guard = self.pool_meta_save_gate.read().await;
|
||||
let (pool_meta_guard, snapshot) = self
|
||||
.acquire_pool_meta_read_guard(&save_guard, "target capacity admission failed")
|
||||
@@ -13715,9 +13704,7 @@ impl ECStore {
|
||||
for target_pool_index in target_pool_indices.iter().copied() {
|
||||
ensure_external_decommission_target_admission(&snapshot, target_pool_index, admission)?;
|
||||
}
|
||||
let has_active_source = pool_meta_has_active_decommission(&snapshot);
|
||||
drop(save_guard);
|
||||
Ok((pool_meta_guard, has_active_source))
|
||||
Ok(pool_meta_guard)
|
||||
}
|
||||
|
||||
/// Fence healing of the pool metadata object itself without recursively
|
||||
@@ -13745,16 +13732,12 @@ impl ECStore {
|
||||
Ok((pool_meta_guard, admissions, save_guard))
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_decommission_capacity_release_fence_with_active_source(
|
||||
&self,
|
||||
) -> Result<(rustfs_lock::NamespaceLockGuard, bool)> {
|
||||
pub(crate) async fn acquire_decommission_capacity_release_fence(&self) -> Result<rustfs_lock::NamespaceLockGuard> {
|
||||
let save_guard = self.pool_meta_save_gate.read().await;
|
||||
let (pool_meta_guard, snapshot) = self
|
||||
let (pool_meta_guard, _) = self
|
||||
.acquire_pool_meta_read_guard(&save_guard, "capacity release fence failed")
|
||||
.await?;
|
||||
let has_active_source = pool_meta_has_active_decommission(&snapshot);
|
||||
drop(save_guard);
|
||||
Ok((pool_meta_guard, has_active_source))
|
||||
Ok(pool_meta_guard)
|
||||
}
|
||||
|
||||
pub(crate) async fn run_decommission_capacity_admitted_mutation<T, F, Fut>(
|
||||
@@ -22577,6 +22560,7 @@ mod tests {
|
||||
"buckets/.usage.v2.json",
|
||||
"buckets/.usage.v2.json.bkp",
|
||||
"buckets/.usage.observed.json",
|
||||
"buckets/.usage.buckets.json",
|
||||
"buckets/.usage-progress.json",
|
||||
"buckets/photos/.usage-progress.json.bkp",
|
||||
"buckets/photos/.usage-progress.json.extra",
|
||||
@@ -22657,6 +22641,7 @@ mod tests {
|
||||
let controls = [
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.v2.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.observed.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/.usage.buckets.json"),
|
||||
(RUSTFS_META_BUCKET, "buckets/photos/.usage-progress.json.bkp"),
|
||||
(RUSTFS_META_BUCKET, "buckets/photos/.usage-cache.bin.extra"),
|
||||
(user_bucket, "ordinary-object"),
|
||||
@@ -22906,6 +22891,7 @@ mod tests {
|
||||
"buckets/photos/.usage-cache.bin.bkp.extra",
|
||||
"buckets/.usage.v2.json",
|
||||
"buckets/.usage.observed.json",
|
||||
"buckets/.usage.buckets.json",
|
||||
"buckets/photos/.usage-progress.json.bkp",
|
||||
] {
|
||||
let source_set = store.pools[0].get_disks_by_key(object);
|
||||
@@ -28016,7 +28002,7 @@ mod tests {
|
||||
.expect("hold the namespace writer while the read-only admission waits");
|
||||
let admission = tokio::spawn({
|
||||
let store = store.clone();
|
||||
async move { store.acquire_decommission_capacity_release_fence_with_active_source().await }
|
||||
async move { store.acquire_decommission_capacity_release_fence().await }
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
loop {
|
||||
@@ -28065,7 +28051,7 @@ mod tests {
|
||||
);
|
||||
|
||||
drop(writer);
|
||||
let (read_fence, _) = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
|
||||
let read_fence = tokio::time::timeout(std::time::Duration::from_secs(10), admission)
|
||||
.await
|
||||
.expect("the read-only admission must finish after releasing the namespace writer")
|
||||
.expect("the admission task must not panic")
|
||||
@@ -43367,6 +43353,12 @@ mod pools_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_decommission_meta_prefixes_include_s3tables_and_s3vectors() {
|
||||
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3tables"));
|
||||
assert!(super::DECOMMISSION_META_PREFIXES.contains(&"s3vectors"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(windows)]
|
||||
fn test_path2_bucket_object_with_base_path_supports_windows_separators() {
|
||||
|
||||
@@ -4150,6 +4150,97 @@ mod decommission_lock_order_tests {
|
||||
.expect("decommission activation should commit after the probe release");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn waiting_put_does_not_hold_capacity_needed_by_conditional_commit_and_activation() {
|
||||
use crate::set_disk::{PutObjectCommitBarrier, PutObjectCommitPause};
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
run_large_stack_current_thread_async_test("staged-put-activation", || async {
|
||||
let (_dirs, store, _peer) = test_three_pool_stores_with_isolated_node_contexts(None).await;
|
||||
let bucket = test_bucket("staged-put-activation");
|
||||
let object = "entry";
|
||||
store.make_bucket(&bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
let seeded = store.pools[2]
|
||||
.put_object(
|
||||
&bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"before".to_vec()),
|
||||
&ObjectOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let layout = DecommissionErasureLayout { data: 1, parity: 0 };
|
||||
set_decommission_capacity_info_overrides_for_test(
|
||||
store.id,
|
||||
vec![vec![
|
||||
DecommissionPoolCapacityInfo::for_test(0, layout, 0, 1024, 1024),
|
||||
DecommissionPoolCapacityInfo::for_test(1, layout, 1024, 1024, 0),
|
||||
DecommissionPoolCapacityInfo::for_test(2, layout, 1024, 1024, 0),
|
||||
]],
|
||||
);
|
||||
|
||||
let after = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::AfterNamespace);
|
||||
let conditional_store = Arc::clone(&store);
|
||||
let conditional_bucket = bucket.clone();
|
||||
let conditional = tokio::spawn(async move {
|
||||
conditional_store
|
||||
.put_object(
|
||||
&conditional_bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"conditional".to_vec()),
|
||||
&ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: seeded.etag,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
after.wait_until_paused().await;
|
||||
let before = PutObjectCommitBarrier::install(&bucket, object, PutObjectCommitPause::BeforeNamespace);
|
||||
let ordinary_store = Arc::clone(&store);
|
||||
let ordinary_bucket = bucket.clone();
|
||||
let ordinary = tokio::spawn(async move {
|
||||
ordinary_store.pools[2]
|
||||
.put_object(
|
||||
&ordinary_bucket,
|
||||
object,
|
||||
&mut PutObjReader::from_vec(b"ordinary".to_vec()),
|
||||
&ObjectOptions {
|
||||
decommission_capacity_admission: Some(Arc::clone(&ordinary_store)),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
before.wait_until_paused().await;
|
||||
before.release_and_wait_until_namespace_pending().await;
|
||||
assert!(!before.namespace_acquired());
|
||||
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
store.save_current_pool_meta_for_decommission_start(&[0], Vec::new()),
|
||||
)
|
||||
.await
|
||||
.expect("an object-lock waiter must leave capacity available to activation")
|
||||
.expect("activate decommission of a separate source");
|
||||
drop(after);
|
||||
drop(before);
|
||||
conditional
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("publish under the active capacity reservation");
|
||||
let written = ordinary.await.unwrap().expect("publish the queued PUT");
|
||||
let visible = store
|
||||
.get_object_info(&bucket, object, &ObjectOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(visible.etag, written.etag);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn staged_external_put_rechecks_retiring_source_on_another_node() {
|
||||
|
||||
@@ -1584,11 +1584,12 @@ impl Sets {
|
||||
version_id: &str,
|
||||
opts: &HealOpts,
|
||||
proof: crate::set_disk::AbsenceProofRequest<'_>,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<(HealResultItem, Option<Error>, Option<crate::set_disk::HealedObjectAbsence>)> {
|
||||
let mut absence = None;
|
||||
let (item, error) = self
|
||||
.get_disks_for_heal_object(object, opts)?
|
||||
.heal_object_with_retirement(bucket, object, version_id, opts, &mut absence, proof)
|
||||
.heal_object_for_store(bucket, object, version_id, opts, &mut absence, proof, capacity_store)
|
||||
.await?;
|
||||
// A caller-owned lock does not expose its lease to this boundary.
|
||||
// Keep cleanup unverified when that lease cannot be checked here.
|
||||
|
||||
@@ -369,6 +369,14 @@ fn data_movement_user_defined(object_info: &ObjectInfo) -> HashMap<String, Strin
|
||||
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
|
||||
user_defined.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
|
||||
insert_data_movement_checksum(&mut user_defined, object_info);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
if let Some(logical_rev) = object_info.logical_body_revision() {
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut user_defined,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
logical_rev.to_string(),
|
||||
);
|
||||
}
|
||||
if !object_info.user_tags.is_empty() {
|
||||
user_defined.insert(AMZ_OBJECT_TAGGING.to_string(), (*object_info.user_tags).clone());
|
||||
}
|
||||
@@ -995,6 +1003,24 @@ fn data_movement_publication_marker_valid(object_info: &ObjectInfo) -> bool {
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn data_movement_logical_body_revision_marker_presence(object_info: &ObjectInfo) -> Option<bool> {
|
||||
let mut found: Option<uuid::Uuid> = None;
|
||||
for (key, value) in object_info.user_defined.iter() {
|
||||
if !is_data_movement_internal_metadata(key, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX) {
|
||||
continue;
|
||||
}
|
||||
let parsed = uuid::Uuid::parse_str(value.trim()).ok().filter(|id| !id.is_nil())?;
|
||||
if found.is_some_and(|existing| existing != parsed) {
|
||||
return None;
|
||||
}
|
||||
found = Some(parsed);
|
||||
}
|
||||
if found.is_some() && object_info.data_dir.is_none_or(|dir| dir.is_nil()) {
|
||||
return None;
|
||||
}
|
||||
Some(found.is_some())
|
||||
}
|
||||
|
||||
fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, normalize_compression_size: bool) -> bool {
|
||||
[
|
||||
SUFFIX_DATA_MOVED,
|
||||
@@ -1006,6 +1032,7 @@ fn is_data_movement_rewritten_metadata(object_info: &ObjectInfo, key: &str, norm
|
||||
// Inline placement is local to each physical copy, like its data directory.
|
||||
rustfs_utils::http::SUFFIX_INLINE_DATA,
|
||||
crate::object_api::ENCRYPTED_PART_LAYOUT_QUORUM_SUFFIX,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
]
|
||||
.iter()
|
||||
.any(|suffix| is_data_movement_internal_metadata(key, suffix))
|
||||
@@ -1061,6 +1088,16 @@ pub(crate) fn is_equivalent_data_movement_metadata(
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let source_logical_rev_marker = data_movement_logical_body_revision_marker_presence(source);
|
||||
let target_logical_rev_marker = data_movement_logical_body_revision_marker_presence(target);
|
||||
if !is_compatible_data_movement_marker_presence(source_logical_rev_marker, target_logical_rev_marker) {
|
||||
return false;
|
||||
}
|
||||
if (source_logical_rev_marker == Some(true) || target_logical_rev_marker == Some(true))
|
||||
&& source.logical_body_revision() != target.logical_body_revision()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
source
|
||||
.user_defined
|
||||
@@ -1074,6 +1111,13 @@ pub(crate) fn is_equivalent_data_movement_metadata(
|
||||
.all(|(key, value)| source.user_defined.get(key) == Some(value))
|
||||
}
|
||||
|
||||
/// A listing can encounter either physical copy first. Migration verification
|
||||
/// itself remains directional so it still detects metadata lost on the target.
|
||||
pub(crate) fn equivalent_listed_object_versions(left: &ObjectInfo, right: &ObjectInfo) -> bool {
|
||||
is_equivalent_data_movement_object_identity(left, right, true, true)
|
||||
|| is_equivalent_data_movement_object_identity(right, left, true, true)
|
||||
}
|
||||
|
||||
pub(crate) fn is_equivalent_data_movement_object_identity(
|
||||
source: &ObjectInfo,
|
||||
target: &ObjectInfo,
|
||||
@@ -5223,4 +5267,75 @@ mod tests {
|
||||
|
||||
assert!(!result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_movement_preserves_logical_body_revision_across_hops_and_passes_equivalence() {
|
||||
let d1 = Uuid::from_u128(0x1111);
|
||||
let d2 = Uuid::from_u128(0x2222);
|
||||
let d3 = Uuid::from_u128(0x3333);
|
||||
let source = ObjectInfo {
|
||||
bucket: "vec-bucket".to_string(),
|
||||
name: "manifest.json".to_string(),
|
||||
size: 64,
|
||||
actual_size: 64,
|
||||
etag: Some("etag-1".to_string()),
|
||||
mod_time: Some(OffsetDateTime::UNIX_EPOCH),
|
||||
data_dir: Some(d1),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(source.logical_body_revision(), Some(d1));
|
||||
|
||||
let hop1 = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(data_movement_user_defined(&source)),
|
||||
..source.clone()
|
||||
};
|
||||
assert_eq!(hop1.logical_body_revision(), Some(d1));
|
||||
assert!(is_equivalent_data_movement_object(&source, &hop1));
|
||||
|
||||
let hop2 = ObjectInfo {
|
||||
data_dir: Some(d3),
|
||||
user_defined: Arc::new(data_movement_user_defined(&hop1)),
|
||||
..hop1.clone()
|
||||
};
|
||||
assert_eq!(hop2.logical_body_revision(), Some(d1));
|
||||
assert!(is_equivalent_data_movement_object(&hop1, &hop2));
|
||||
assert!(is_equivalent_data_movement_object(&source, &hop2));
|
||||
|
||||
// Dropping the marker after the object has already been migrated must fail equivalence.
|
||||
let dropped_marker = ObjectInfo {
|
||||
data_dir: Some(d3),
|
||||
user_defined: Arc::new(HashMap::new()),
|
||||
..hop1.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&hop1, &dropped_marker));
|
||||
|
||||
// Mismatched or malformed logical body revision markers must fail equivalence.
|
||||
let mut wrong_meta = data_movement_user_defined(&source);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut wrong_meta, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut wrong_meta,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
Uuid::from_u128(0x9999).to_string(),
|
||||
);
|
||||
let wrong_rev = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(wrong_meta),
|
||||
..source.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&source, &wrong_rev));
|
||||
|
||||
let mut malformed_meta = HashMap::new();
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut malformed_meta,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
"not-a-valid-uuid".to_string(),
|
||||
);
|
||||
let malformed = ObjectInfo {
|
||||
data_dir: Some(d2),
|
||||
user_defined: Arc::new(malformed_meta),
|
||||
..source.clone()
|
||||
};
|
||||
assert!(!is_equivalent_data_movement_object(&source, &malformed));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,9 @@ pub(crate) use admin_bucket_identity::current_admin_bucket_incarnations;
|
||||
pub use admin_bucket_identity::verified_account_bucket_usage;
|
||||
pub mod local_snapshot;
|
||||
mod scan_progress;
|
||||
mod snapshot_view;
|
||||
pub use scan_progress::load_bucket_scan_progress_for_admin;
|
||||
pub use snapshot_view::{AdminUsageSnapshot, load_admin_usage_snapshot};
|
||||
|
||||
use crate::storage_api_contracts::{
|
||||
bucket::{BucketOperations as _, BucketOptions},
|
||||
@@ -637,7 +639,7 @@ fn stale_data_usage_persist_reason_for_source(
|
||||
/// Store data usage info to backend storage
|
||||
#[instrument(skip(store))]
|
||||
pub async fn store_data_usage_in_backend(data_usage_info: DataUsageInfo, store: Arc<ECStore>) -> Result<(), Error> {
|
||||
reject_admin_usage_projection(&data_usage_info)?;
|
||||
reject_display_only_usage(&data_usage_info)?;
|
||||
if data_usage_info.usage_snapshot_converged == Some(false) {
|
||||
return Err(Error::other(
|
||||
"nonconverged data usage observations cannot replace the quota-authoritative snapshot",
|
||||
@@ -667,7 +669,7 @@ async fn save_data_usage_in_backend(
|
||||
store: Arc<ECStore>,
|
||||
expected_publication_epoch: u64,
|
||||
) -> Result<(), Error> {
|
||||
reject_admin_usage_projection(&data_usage_info)?;
|
||||
reject_display_only_usage(&data_usage_info)?;
|
||||
let data =
|
||||
serde_json::to_vec(&data_usage_info).map_err(|e| Error::other(format!("Failed to serialize data usage info: {e}")))?;
|
||||
|
||||
@@ -1282,14 +1284,17 @@ fn parse_usage_snapshot(buf: &[u8]) -> Result<DataUsageInfo, Error> {
|
||||
e.column()
|
||||
))
|
||||
})?;
|
||||
reject_admin_usage_projection(&info)?;
|
||||
reject_display_only_usage(&info)?;
|
||||
for usage in info.buckets_usage.values_mut() {
|
||||
usage.normalize_usage_provenance();
|
||||
}
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
fn reject_admin_usage_projection(info: &DataUsageInfo) -> Result<(), Error> {
|
||||
fn reject_display_only_usage(info: &DataUsageInfo) -> Result<(), Error> {
|
||||
if info.usage_snapshot_certified_buckets.is_some() {
|
||||
return Err(Error::other("completed-bucket sidecar is not a namespace baseline"));
|
||||
}
|
||||
if info.usage_snapshot_admin_projection {
|
||||
return Err(Error::other("admin usage projections cannot be persisted or used as a storage baseline"));
|
||||
}
|
||||
@@ -2121,6 +2126,9 @@ impl BucketUsageAccumulator {
|
||||
}
|
||||
|
||||
pub fn quota_object_size(object: &ObjectInfo) -> Result<u64, Error> {
|
||||
if crate::bucket::metadata::is_vector_pagination_session(&object.bucket, &object.name) {
|
||||
return Ok(0);
|
||||
}
|
||||
// A compressed object may carry -1 while the transformed size is unknown
|
||||
// (legacy streaming sentinel). In that case the persisted physical size
|
||||
// is still a valid accounting floor; every other negative value is corrupt.
|
||||
@@ -2460,54 +2468,84 @@ pub async fn seed_bucket_usage_memory_for_test(bucket: &str, size: u64) {
|
||||
.await;
|
||||
}
|
||||
|
||||
/// A successful PUT's change to logical bucket usage.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PutUsageReceipt {
|
||||
had_live_version: bool,
|
||||
replaced: ReplacedVersion,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum ReplacedVersion {
|
||||
Absent,
|
||||
DeleteMarker,
|
||||
Data(u64),
|
||||
}
|
||||
|
||||
impl PutUsageReceipt {
|
||||
pub(crate) fn from_predecessors(had_live_version: bool, replaced: Option<&ObjectInfo>) -> Result<Self, Error> {
|
||||
let replaced = match replaced {
|
||||
None => ReplacedVersion::Absent,
|
||||
Some(info) if info.delete_marker => ReplacedVersion::DeleteMarker,
|
||||
Some(info) => ReplacedVersion::Data(quota_object_size(info)?),
|
||||
};
|
||||
Ok(Self {
|
||||
had_live_version,
|
||||
replaced,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn replaced_size(&self) -> u64 {
|
||||
match self.replaced {
|
||||
ReplacedVersion::Data(size) => size,
|
||||
ReplacedVersion::Absent | ReplacedVersion::DeleteMarker => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply this committed version change to the bucket's immediate usage counters.
|
||||
pub async fn record(self, bucket: &str, new_size: u64) {
|
||||
ensure_bucket_usage_cached(bucket).await;
|
||||
let mut cache = memory_cache().write().await;
|
||||
let entry = cache
|
||||
.entry(bucket.to_owned())
|
||||
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
|
||||
entry.usage.size = entry.usage.size.saturating_sub(self.replaced_size()).saturating_add(new_size);
|
||||
if !self.had_live_version {
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
}
|
||||
if !matches!(self.replaced, ReplacedVersion::Data(_)) {
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
}
|
||||
if self.replaced == ReplacedVersion::DeleteMarker {
|
||||
entry.usage.delete_markers_count = entry.usage.delete_markers_count.saturating_sub(1);
|
||||
}
|
||||
let now = SystemTime::now();
|
||||
entry.refreshed_at = now;
|
||||
entry.usage_updated_at = now;
|
||||
entry.dirty = true;
|
||||
entry.stale_snapshot_pending = false;
|
||||
entry.pending_scanner_position = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fast in-memory update for immediate quota and admin usage consistency.
|
||||
pub async fn record_bucket_object_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
|
||||
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, false).await;
|
||||
PutUsageReceipt {
|
||||
had_live_version: previous_current_size.is_some(),
|
||||
replaced: previous_current_size.map_or(ReplacedVersion::Absent, ReplacedVersion::Data),
|
||||
}
|
||||
.record(bucket, new_size)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Fast in-memory update for versioned object writes.
|
||||
pub async fn record_bucket_object_version_write_memory(bucket: &str, previous_current_size: Option<u64>, new_size: u64) {
|
||||
record_bucket_object_write_memory_inner(bucket, previous_current_size, new_size, true).await;
|
||||
}
|
||||
|
||||
async fn record_bucket_object_write_memory_inner(
|
||||
bucket: &str,
|
||||
previous_current_size: Option<u64>,
|
||||
new_size: u64,
|
||||
creates_new_version: bool,
|
||||
) {
|
||||
ensure_bucket_usage_cached(bucket).await;
|
||||
|
||||
let mut cache = memory_cache().write().await;
|
||||
let entry = cache
|
||||
.entry(bucket.to_string())
|
||||
.or_insert_with(|| cached_bucket_usage_now(BucketUsageInfo::default()));
|
||||
|
||||
if creates_new_version {
|
||||
entry.usage.size = entry.usage.size.saturating_add(new_size);
|
||||
if previous_current_size.is_none() {
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
}
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
} else {
|
||||
match previous_current_size {
|
||||
Some(previous_size) => {
|
||||
entry.usage.size = entry.usage.size.saturating_sub(previous_size).saturating_add(new_size);
|
||||
}
|
||||
None => {
|
||||
entry.usage.size = entry.usage.size.saturating_add(new_size);
|
||||
entry.usage.objects_count = entry.usage.objects_count.saturating_add(1);
|
||||
entry.usage.versions_count = entry.usage.versions_count.saturating_add(1);
|
||||
}
|
||||
}
|
||||
PutUsageReceipt {
|
||||
had_live_version: previous_current_size.is_some(),
|
||||
replaced: ReplacedVersion::Absent,
|
||||
}
|
||||
|
||||
let now = SystemTime::now();
|
||||
entry.refreshed_at = now;
|
||||
entry.usage_updated_at = now;
|
||||
entry.dirty = true;
|
||||
entry.stale_snapshot_pending = false;
|
||||
entry.pending_scanner_position = None;
|
||||
.record(bucket, new_size)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Degraded in-memory update for an object write whose previous current size
|
||||
@@ -5790,6 +5828,26 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_exempt_sessions_require_the_vector_storage_bucket_and_session_key() {
|
||||
let table = uuid::Uuid::new_v4();
|
||||
let session = "b".repeat(64);
|
||||
let key = format!(".rustfs-table/{table}/query-results/{session}.session");
|
||||
let size = |bucket: &str, name: &str| {
|
||||
quota_object_size(&ObjectInfo {
|
||||
bucket: bucket.to_owned(),
|
||||
name: name.to_owned(),
|
||||
size: 17,
|
||||
..Default::default()
|
||||
})
|
||||
.expect("quota size")
|
||||
};
|
||||
assert_eq!(size("rustfs-v-abc", &key), 0);
|
||||
assert_eq!(size("general-bucket", &key), 17);
|
||||
assert_eq!(size("rustfs-v-abc", &key.replace("/query-results/", "/dataset/")), 17);
|
||||
assert_eq!(size("rustfs-v-abc", &key.replace(&session, "other")), 17);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quota_object_size_accepts_compressed_unknown_actual_size_sentinel() {
|
||||
let mut metadata = HashMap::new();
|
||||
@@ -7438,6 +7496,46 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn put_usage_charges_the_replaced_version_and_counts_markers_separately() {
|
||||
let bucket = "put-usage-versions";
|
||||
let baseline = BucketUsageInfo {
|
||||
objects_count: 1,
|
||||
versions_count: 2,
|
||||
size: 90,
|
||||
..Default::default()
|
||||
};
|
||||
let null = ObjectInfo {
|
||||
size: 20,
|
||||
actual_size: 20,
|
||||
..Default::default()
|
||||
};
|
||||
let marker = ObjectInfo {
|
||||
delete_marker: true,
|
||||
..Default::default()
|
||||
};
|
||||
for (mut initial, had_live, replaced, expected) in [
|
||||
(baseline.clone(), true, Some(&null), (100, 1, 2, 0)),
|
||||
(baseline.clone(), true, None, (120, 1, 3, 0)),
|
||||
(baseline, true, Some(&marker), (120, 1, 3, 0)),
|
||||
(BucketUsageInfo::default(), false, Some(&marker), (30, 1, 1, 0)),
|
||||
] {
|
||||
initial.delete_markers_count = u64::from(replaced.is_some_and(|version| version.delete_marker));
|
||||
clear_usage_memory_cache_for_test().await;
|
||||
replace_bucket_usage_memory_from_authoritative(bucket, initial, SystemTime::now()).await;
|
||||
let receipt = PutUsageReceipt::from_predecessors(had_live, replaced).expect("valid version sizes");
|
||||
receipt.record(bucket, 30).await;
|
||||
let cache = memory_cache().read().await;
|
||||
let usage = &cache[bucket].usage;
|
||||
assert_eq!(
|
||||
(usage.size, usage.objects_count, usage.versions_count, usage.delete_markers_count),
|
||||
expected
|
||||
);
|
||||
}
|
||||
clear_usage_memory_cache_for_test().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn authoritative_versioned_refresh_replaces_stale_dirty_memory() {
|
||||
|
||||
@@ -40,7 +40,19 @@ pub async fn load_bucket_scan_progress_for_admin(
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
|
||||
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline))
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, false))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) async fn load_initial_bucket_scan_progress(
|
||||
store: Arc<ECStore>,
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let deadline = tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT;
|
||||
let read_deadline = deadline - ADMIN_USAGE_INCARNATION_TIMEOUT / 4;
|
||||
tokio::time::timeout_at(deadline, load_progress(store, buckets, baseline, read_deadline, true))
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
@@ -50,6 +62,7 @@ async fn bucket_progress_sources(
|
||||
bucket: String,
|
||||
sets: Arc<Vec<Arc<SetDisks>>>,
|
||||
movement_generation: u64,
|
||||
initial_baseline: Option<&DataUsageInfo>,
|
||||
) -> BoxStream<'static, ProgressEvent> {
|
||||
let Some(incarnation) = store
|
||||
.bucket_incarnation_id_from_disk(&bucket)
|
||||
@@ -59,6 +72,19 @@ async fn bucket_progress_sources(
|
||||
else {
|
||||
return futures::stream::empty().boxed();
|
||||
};
|
||||
if initial_baseline.as_ref().is_some_and(|baseline| {
|
||||
baseline
|
||||
.usage_snapshot_noninitial_buckets
|
||||
.get(&bucket)
|
||||
.is_some_and(|previous| {
|
||||
uuid::Uuid::parse_str(previous)
|
||||
.ok()
|
||||
.is_none_or(|previous| previous.is_nil() || previous == incarnation)
|
||||
})
|
||||
|| !super::snapshot_view::initial_progress_allowed(baseline.buckets_usage.get(&bucket), incarnation)
|
||||
}) {
|
||||
return futures::stream::empty().boxed();
|
||||
}
|
||||
let incarnation = incarnation.to_string();
|
||||
let path = bucket_scan_progress_path(&bucket);
|
||||
futures::stream::iter(0..sets.len())
|
||||
@@ -124,6 +150,7 @@ async fn load_progress(
|
||||
buckets: &[String],
|
||||
baseline: &DataUsageInfo,
|
||||
read_deadline: tokio::time::Instant,
|
||||
initial_only: bool,
|
||||
) -> HashMap<String, BucketScanProgress> {
|
||||
let Some(epoch) = store.scanner_data_usage_publication_epoch().await else {
|
||||
return HashMap::new();
|
||||
@@ -145,8 +172,9 @@ async fn load_progress(
|
||||
}
|
||||
// Emit each validated source immediately. A bucket waiting for another
|
||||
// source must not hide its healthy sample behind a whole-bucket future.
|
||||
let initial_baseline = initial_only.then_some(baseline);
|
||||
let work = futures::stream::iter(buckets.iter().cloned())
|
||||
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation))
|
||||
.map(|bucket| bucket_progress_sources(store.clone(), bucket, sets.clone(), movement_generation, initial_baseline))
|
||||
.buffer_unordered(4)
|
||||
.flatten_unordered(4);
|
||||
let samples = collect_progress_until(read_deadline, work).await;
|
||||
@@ -206,6 +234,7 @@ mod tests {
|
||||
},
|
||||
objects: Some(objects),
|
||||
size: Some(objects * 11),
|
||||
blocker: None,
|
||||
};
|
||||
let partial: BoxStream<'static, ProgressEvent> = futures::stream::iter([
|
||||
futures::future::ready(("partial".into(), sample("partial", 0, 7, false))).boxed(),
|
||||
@@ -271,6 +300,7 @@ mod tests {
|
||||
stage: BucketScanStage::Scanning,
|
||||
objects: Some(7),
|
||||
size: Some(71),
|
||||
blocker: None,
|
||||
};
|
||||
(dirs, store, sample)
|
||||
}
|
||||
@@ -285,6 +315,171 @@ mod tests {
|
||||
.expect("persist display sample on its source set");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_snapshot_allows_initial_progress_but_preserves_complete_values() {
|
||||
let (_dirs, store, sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let mut baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(10)),
|
||||
scanner_epoch: Some(9),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
..Default::default()
|
||||
};
|
||||
let primary = "buckets/.usage.v2.json";
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("initial marker"))
|
||||
.await
|
||||
.expect("persist initial marker");
|
||||
let initial = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("initial view");
|
||||
assert!(initial.usage.buckets_usage.is_empty());
|
||||
assert_eq!(initial.initial_scan_progress["progress"].objects, Some(7));
|
||||
baseline.usage_snapshot_bootstrap_pending = false;
|
||||
baseline.usage_snapshot_complete = true;
|
||||
baseline.scanner_cycle = Some(10);
|
||||
let mut complete = BucketUsageInfo {
|
||||
size: 900,
|
||||
objects_count: 90,
|
||||
bucket_incarnation: Some(sample.bucket_incarnation.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
complete.certify(rustfs_data_usage::BucketUsageCertification {
|
||||
epoch: 9,
|
||||
cycle: 10,
|
||||
certified_at: baseline.last_update.expect("measurement time"),
|
||||
});
|
||||
baseline.buckets_usage.insert("progress".into(), complete);
|
||||
baseline.buckets_count = 1;
|
||||
baseline.calculate_totals();
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("complete snapshot"))
|
||||
.await
|
||||
.expect("persist complete snapshot");
|
||||
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("complete view");
|
||||
assert_eq!(view.usage.buckets_usage["progress"].objects_count, 90);
|
||||
assert!(view.initial_scan_progress.is_empty());
|
||||
baseline.usage_snapshot_bootstrap_pending = true;
|
||||
baseline.usage_snapshot_initial_bootstrap = false;
|
||||
baseline.usage_snapshot_complete = false;
|
||||
baseline.buckets_usage.clear();
|
||||
baseline.buckets_count = 0;
|
||||
baseline.calculate_totals();
|
||||
save_config(store.clone(), primary, serde_json::to_vec(&baseline).expect("recovery marker"))
|
||||
.await
|
||||
.expect("persist recovery marker");
|
||||
let recovered = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("recovery view");
|
||||
assert!(
|
||||
recovered.initial_scan_progress.is_empty(),
|
||||
"same incarnation does not become a first scan after recovery"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn noninitial_barrier_survives_a_missing_completed_bucket_sidecar() {
|
||||
let (_dirs, store, mut sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
scanner_epoch: Some(9),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_noninitial_buckets: HashMap::from([("progress".into(), sample.bucket_incarnation.clone())]),
|
||||
..Default::default()
|
||||
};
|
||||
save_config(
|
||||
store.clone(),
|
||||
"buckets/.usage.v2.json",
|
||||
serde_json::to_vec(&baseline).expect("history marker"),
|
||||
)
|
||||
.await
|
||||
.expect("persist history marker");
|
||||
let view = super::super::load_admin_usage_snapshot(store.clone(), &["progress".into()])
|
||||
.await
|
||||
.expect("bounded missing view");
|
||||
assert!(
|
||||
view.initial_scan_progress.is_empty(),
|
||||
"a lost sidecar cannot reopen initial-statistics fallback"
|
||||
);
|
||||
assert_eq!(view.unmeasured_buckets, ["progress"]);
|
||||
|
||||
// A freshly created incarnation with the same name has its own first scan.
|
||||
store
|
||||
.delete_bucket("progress", &Default::default())
|
||||
.await
|
||||
.expect("delete old bucket");
|
||||
store
|
||||
.make_bucket("progress", &Default::default())
|
||||
.await
|
||||
.expect("recreate bucket");
|
||||
let current = store
|
||||
.bucket_incarnation_id_from_disk("progress")
|
||||
.await
|
||||
.expect("new incarnation");
|
||||
assert_ne!(sample.bucket_incarnation, current.to_string());
|
||||
// Restore the historical marker to model a stale read after recreate.
|
||||
save_config(store.clone(), "buckets/.usage.v2.json", serde_json::to_vec(&baseline).unwrap())
|
||||
.await
|
||||
.expect("history of the previous incarnation");
|
||||
sample.bucket_incarnation = current.to_string();
|
||||
save(&store, &sample).await;
|
||||
let recreated = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("recreated view");
|
||||
assert!(recreated.usage.buckets_usage.is_empty());
|
||||
assert_eq!(recreated.initial_scan_progress["progress"].objects, Some(7));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn strict_snapshot_never_returns_a_persisted_observed_row_as_completed_usage() {
|
||||
let (_dirs, store, sample) = fixture().await;
|
||||
save(&store, &sample).await;
|
||||
let mut observed = BucketUsageInfo {
|
||||
objects_count: 90,
|
||||
size: 900,
|
||||
bucket_incarnation: Some(sample.bucket_incarnation),
|
||||
..Default::default()
|
||||
};
|
||||
observed.mark_observed();
|
||||
let mut baseline = DataUsageInfo {
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
scanner_epoch: Some(9),
|
||||
scanner_cycle: Some(10),
|
||||
usage_snapshot_complete: true,
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_pending_bucket_count: 1,
|
||||
usage_snapshot_pending_buckets: vec!["progress".into()],
|
||||
buckets_count: 1,
|
||||
buckets_usage: HashMap::from([("progress".into(), observed)]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(baseline.checked_calculate_totals());
|
||||
save_config(
|
||||
store.clone(),
|
||||
"buckets/.usage.v2.json",
|
||||
serde_json::to_vec(&baseline).expect("observed root"),
|
||||
)
|
||||
.await
|
||||
.expect("persist old pending root");
|
||||
let view = super::super::load_admin_usage_snapshot(store, &["progress".into()])
|
||||
.await
|
||||
.expect("strict view");
|
||||
assert!(view.usage.buckets_usage.is_empty());
|
||||
assert_eq!(view.unmeasured_buckets, ["progress"]);
|
||||
assert!(
|
||||
view.initial_scan_progress.is_empty(),
|
||||
"filtering an old row must not reopen initial fallback"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn display_progress_reloads_from_shared_storage_without_promoting_usage() {
|
||||
fn assert_send<T: Send>(value: T) -> T {
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
use super::*;
|
||||
use rustfs_data_usage::BucketScanProgress;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// Response-only view of persisted usage. Initial progress is never inserted
|
||||
/// into the authoritative map or used by quota admission.
|
||||
#[derive(Debug, serde::Serialize)]
|
||||
pub struct AdminUsageSnapshot {
|
||||
#[serde(flatten)]
|
||||
pub usage: DataUsageInfo,
|
||||
pub snapshot_view: bool,
|
||||
pub initial_scan_progress: HashMap<String, BucketScanProgress>,
|
||||
pub unmeasured_buckets: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) fn initial_progress_allowed(previous: Option<&BucketUsageInfo>, incarnation: uuid::Uuid) -> bool {
|
||||
if incarnation.is_nil() {
|
||||
return false;
|
||||
}
|
||||
match previous {
|
||||
None => true,
|
||||
Some(previous) => previous
|
||||
.bucket_incarnation
|
||||
.as_deref()
|
||||
.and_then(|value| uuid::Uuid::parse_str(value).ok())
|
||||
.filter(|previous| !previous.is_nil())
|
||||
.is_some_and(|previous| previous != incarnation),
|
||||
}
|
||||
}
|
||||
|
||||
fn initial_snapshot_available(raw: &DataUsageInfo, source: UsageSnapshotSource) -> bool {
|
||||
source == UsageSnapshotSource::Primary
|
||||
&& raw.usage_snapshot_initial_view_version == Some(1)
|
||||
&& if raw.usage_snapshot_bootstrap_pending {
|
||||
raw.usage_snapshot_initial_bootstrap && raw.has_usage_bootstrap_marker_shape()
|
||||
} else {
|
||||
raw.is_completed_usage_baseline()
|
||||
}
|
||||
}
|
||||
|
||||
/// Read complete persisted values before considering initial progress.
|
||||
///
|
||||
/// The caller supplies only authorized bucket names. Primary/backup failures
|
||||
/// propagate; a filtered or unreadable historical value is not a first scan.
|
||||
/// Progress reads are bounded and optional, and never trigger object listing.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns the persisted snapshot's read or decode error when neither copy
|
||||
/// supplies a usable baseline.
|
||||
pub async fn load_admin_usage_snapshot(store: Arc<ECStore>, buckets: &[String]) -> Result<AdminUsageSnapshot, Error> {
|
||||
let (raw, source) = load_data_usage_snapshot(store.clone()).await?;
|
||||
let certified = if source.is_authoritative() && (raw.is_completed_usage_baseline() || raw.has_usage_bootstrap_marker_shape())
|
||||
{
|
||||
load_certified_buckets(store.clone(), &raw).await
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
let history_available = certified.is_ok();
|
||||
let certified = certified.ok().flatten();
|
||||
let measured_names = buckets
|
||||
.iter()
|
||||
.filter(|bucket| {
|
||||
raw.buckets_usage.contains_key(*bucket)
|
||||
|| certified
|
||||
.as_ref()
|
||||
.is_some_and(|info| info.buckets_usage.contains_key(*bucket))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
let incarnations = current_admin_bucket_incarnations(
|
||||
store.clone(),
|
||||
measured_names,
|
||||
tokio::time::Instant::now() + ADMIN_USAGE_INCARNATION_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
// Check initial eligibility on unfiltered durable history. A timed-out or
|
||||
// unauthorized identity must never turn an existing row into a first scan.
|
||||
let mut initial_scan_progress = if history_available && initial_snapshot_available(&raw, source) {
|
||||
scan_progress::load_initial_bucket_scan_progress(store, buckets, &raw).await
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
let usage = project_completed_bucket_usage(raw, source, certified, &incarnations, buckets)?;
|
||||
initial_scan_progress.retain(|bucket, _| !usage.buckets_usage.contains_key(bucket));
|
||||
let mut unmeasured_buckets = buckets
|
||||
.iter()
|
||||
.filter(|bucket| !usage.buckets_usage.contains_key(*bucket))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
unmeasured_buckets.sort();
|
||||
unmeasured_buckets.dedup();
|
||||
Ok(AdminUsageSnapshot {
|
||||
usage,
|
||||
snapshot_view: true,
|
||||
initial_scan_progress,
|
||||
unmeasured_buckets,
|
||||
})
|
||||
}
|
||||
|
||||
/// Only a canonical complete root can vouch for a legacy row without an
|
||||
/// explicit certificate. A sidecar can vouch for a bucket independently of
|
||||
/// namespace completeness. Neither path admits observations or a memory overlay.
|
||||
fn project_completed_bucket_usage(
|
||||
mut usage: DataUsageInfo,
|
||||
source: UsageSnapshotSource,
|
||||
certified: Option<DataUsageInfo>,
|
||||
incarnations: &HashMap<String, String>,
|
||||
buckets: &[String],
|
||||
) -> Result<DataUsageInfo, Error> {
|
||||
use rustfs_data_usage::BucketUsageValueState::{Carried, Certified};
|
||||
let complete_root = source.is_authoritative() && usage.is_completed_usage_baseline();
|
||||
if !complete_root && !(source.is_authoritative() && usage.has_usage_bootstrap_marker_shape()) {
|
||||
return Ok(DataUsageInfo::default());
|
||||
}
|
||||
let allowed: HashSet<_> = buckets.iter().map(String::as_str).collect();
|
||||
let original_count = usage.buckets_usage.len();
|
||||
usage.buckets_usage.retain(|bucket, value| {
|
||||
incarnations
|
||||
.get(bucket)
|
||||
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
|
||||
&& complete_root
|
||||
&& match value.usage_value_state {
|
||||
Some(Certified | Carried) => value.usage_certification.is_some(),
|
||||
None => true,
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
let mut changed = usage.buckets_usage.len() != original_count;
|
||||
if let Some(certified) = certified {
|
||||
for (bucket, value) in certified.buckets_usage {
|
||||
if !incarnations
|
||||
.get(&bucket)
|
||||
.is_some_and(|id| value.bucket_incarnation.as_ref() == Some(id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(next) = value.usage_certification else { continue };
|
||||
let previous = usage.buckets_usage.get(&bucket).and_then(|value| value.usage_certification);
|
||||
if previous.is_none_or(|old| (next.epoch, next.cycle, next.certified_at) > (old.epoch, old.cycle, old.certified_at)) {
|
||||
usage.buckets_usage.insert(bucket, value);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Observations and legacy size-only maps cannot prove complete values for
|
||||
// the current incarnation. Never pass this derived view to quota admission.
|
||||
let pending_count = usage.usage_snapshot_pending_buckets.len();
|
||||
usage
|
||||
.usage_snapshot_pending_buckets
|
||||
.retain(|bucket| allowed.contains(bucket.as_str()));
|
||||
usage.usage_snapshot_pending_bucket_count =
|
||||
u64::try_from(usage.usage_snapshot_pending_buckets.len()).map_err(Error::other)?;
|
||||
changed |= pending_count != usage.usage_snapshot_pending_buckets.len()
|
||||
|| usage
|
||||
.bucket_sizes
|
||||
.keys()
|
||||
.any(|bucket| !usage.buckets_usage.contains_key(bucket))
|
||||
|| usage
|
||||
.usage_snapshot_bucket_observations
|
||||
.keys()
|
||||
.any(|bucket| !allowed.contains(bucket.as_str()));
|
||||
usage
|
||||
.usage_snapshot_noninitial_buckets
|
||||
.retain(|bucket, _| allowed.contains(bucket.as_str()));
|
||||
usage.usage_snapshot_bucket_observations.clear();
|
||||
refresh_completed_snapshot_totals(&mut usage, changed)?;
|
||||
Ok(usage)
|
||||
}
|
||||
|
||||
fn refresh_completed_snapshot_totals(usage: &mut DataUsageInfo, changed: bool) -> Result<(), Error> {
|
||||
if !usage.checked_calculate_totals() {
|
||||
return Err(Error::other("completed snapshot totals overflow"));
|
||||
}
|
||||
usage.buckets_count = u64::try_from(usage.buckets_usage.len()).map_err(Error::other)?;
|
||||
usage.bucket_sizes = usage
|
||||
.buckets_usage
|
||||
.iter()
|
||||
.map(|(name, bucket)| (name.clone(), bucket.size))
|
||||
.collect();
|
||||
if !changed {
|
||||
return Ok(());
|
||||
}
|
||||
usage.usage_snapshot_complete = false;
|
||||
usage.usage_snapshot_partial = true;
|
||||
usage.usage_snapshot_admin_projection = true;
|
||||
usage.usage_snapshot_converged = Some(false);
|
||||
usage.replication_info.clear();
|
||||
usage.tier_stats = None;
|
||||
usage.unknown_tier_stats = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_certified_buckets(store: Arc<ECStore>, baseline: &DataUsageInfo) -> Result<Option<DataUsageInfo>, Error> {
|
||||
let path = format!("buckets/{}", rustfs_data_usage::DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME);
|
||||
let bytes = match read_config_preserve_empty(store.clone(), &path).await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(Error::ConfigNotFound) => return Ok(None),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let info: DataUsageInfo = serde_json::from_slice(&bytes).map_err(|_| Error::other("invalid completed-bucket snapshot"))?;
|
||||
if !info.is_certified_buckets_snapshot() {
|
||||
return Err(Error::other("unsupported completed-bucket snapshot"));
|
||||
}
|
||||
if !info.certified_buckets_match_baseline(baseline) {
|
||||
return Ok(None);
|
||||
}
|
||||
let scope = info
|
||||
.usage_snapshot_certified_buckets
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::other("missing completed-bucket scope"))?;
|
||||
let movement = store.scanner_durable_data_movement_generation().await;
|
||||
if movement != Some(scope.movement_generation) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut sources = Vec::new();
|
||||
for set in store.all_set_disks() {
|
||||
let Some(disks) = set.format.erasure.sets.get(set.set_index) else { return Ok(None) };
|
||||
if set.format.id.is_nil() || disks.is_empty() || disks.iter().any(uuid::Uuid::is_nil) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(set.format.id.as_bytes());
|
||||
for disk in disks {
|
||||
digest.update(disk.as_bytes());
|
||||
}
|
||||
sources.push(rustfs_data_usage::CertifiedBucketsSource {
|
||||
pool_index: u64::try_from(set.pool_index).map_err(Error::other)?,
|
||||
set_index: u64::try_from(set.set_index).map_err(Error::other)?,
|
||||
layout: digest.finalize().into(),
|
||||
});
|
||||
}
|
||||
sources.sort_by_key(|source| (source.pool_index, source.set_index));
|
||||
if sources != scope.sources || store.scanner_durable_data_movement_generation().await != movement {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(info))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_projection_recalculates_all_totals_without_refreshing_time() {
|
||||
let measured_at = SystemTime::UNIX_EPOCH + Duration::from_secs(10);
|
||||
let mut usage = DataUsageInfo {
|
||||
last_update: Some(measured_at),
|
||||
usage_snapshot_complete: true,
|
||||
buckets_usage: HashMap::from([
|
||||
(
|
||||
"old".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 2,
|
||||
size: 20,
|
||||
versions_count: 4,
|
||||
delete_markers_count: 1,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"small".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 3,
|
||||
size: 30,
|
||||
versions_count: 5,
|
||||
delete_markers_count: 2,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
refresh_completed_snapshot_totals(&mut usage, true).expect("valid complete buckets");
|
||||
assert_eq!(
|
||||
(
|
||||
usage.buckets_count,
|
||||
usage.objects_total_count,
|
||||
usage.objects_total_size,
|
||||
usage.versions_total_count,
|
||||
usage.delete_markers_total_count
|
||||
),
|
||||
(2, 5, 50, 9, 3)
|
||||
);
|
||||
assert_eq!(usage.bucket_sizes, HashMap::from([("old".into(), 20), ("small".into(), 30)]));
|
||||
assert_eq!(usage.last_update, Some(measured_at));
|
||||
assert!(!usage.usage_snapshot_complete);
|
||||
assert!(usage.usage_snapshot_admin_projection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certified_row_requires_a_healthy_persisted_namespace_baseline() {
|
||||
let time = SystemTime::UNIX_EPOCH;
|
||||
let id = uuid::Uuid::from_u128(1).to_string();
|
||||
let mut row = BucketUsageInfo {
|
||||
bucket_incarnation: Some(id.clone()),
|
||||
size: 100,
|
||||
..Default::default()
|
||||
};
|
||||
row.certify(rustfs_data_usage::BucketUsageCertification {
|
||||
epoch: 0,
|
||||
cycle: 0,
|
||||
certified_at: time,
|
||||
});
|
||||
let raw = DataUsageInfo {
|
||||
last_update: Some(time),
|
||||
usage_snapshot_initial_view_version: Some(1),
|
||||
usage_snapshot_complete: true,
|
||||
buckets_usage: HashMap::from([("measured".into(), row)]),
|
||||
buckets_count: 1,
|
||||
objects_total_size: 100,
|
||||
..Default::default()
|
||||
};
|
||||
let current = HashMap::from([("measured".into(), id)]);
|
||||
for source in [UsageSnapshotSource::Primary, UsageSnapshotSource::Backup] {
|
||||
assert_eq!(
|
||||
project_completed_bucket_usage(raw.clone(), source, None, ¤t, &["measured".into()])
|
||||
.unwrap()
|
||||
.objects_total_size,
|
||||
100
|
||||
);
|
||||
}
|
||||
for invalid in [
|
||||
DataUsageInfo {
|
||||
usage_snapshot_complete: false,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_partial: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_observational: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_admin_projection: true,
|
||||
..raw.clone()
|
||||
},
|
||||
DataUsageInfo {
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_initial_bootstrap: true,
|
||||
..raw.clone()
|
||||
},
|
||||
] {
|
||||
assert!(!initial_snapshot_available(&invalid, UsageSnapshotSource::Primary));
|
||||
let view =
|
||||
project_completed_bucket_usage(invalid, UsageSnapshotSource::Primary, None, ¤t, &["measured".into()])
|
||||
.unwrap();
|
||||
assert!(view.buckets_usage.is_empty());
|
||||
assert_eq!(view.objects_total_size, 0);
|
||||
}
|
||||
let legacy =
|
||||
project_completed_bucket_usage(raw, UsageSnapshotSource::LegacyPrimary, None, ¤t, &["measured".into()])
|
||||
.unwrap();
|
||||
assert!(legacy.buckets_usage.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_bucket_snapshot_projection_rejects_counter_overflow() {
|
||||
let mut usage = DataUsageInfo {
|
||||
buckets_usage: HashMap::from([
|
||||
(
|
||||
"old".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: u64::MAX,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"small".into(),
|
||||
BucketUsageInfo {
|
||||
objects_count: 1,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(refresh_completed_snapshot_totals(&mut usage, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backup_and_recovery_cannot_turn_missing_history_into_first_statistics() {
|
||||
let mut raw = DataUsageInfo {
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
last_update: Some(SystemTime::UNIX_EPOCH),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
|
||||
raw.usage_snapshot_initial_bootstrap = true;
|
||||
raw.usage_snapshot_initial_view_version = Some(1);
|
||||
assert!(initial_snapshot_available(&raw, UsageSnapshotSource::Primary));
|
||||
for source in [
|
||||
UsageSnapshotSource::Backup,
|
||||
UsageSnapshotSource::LegacyPrimary,
|
||||
UsageSnapshotSource::LegacyBackup,
|
||||
UsageSnapshotSource::Missing,
|
||||
] {
|
||||
assert!(!initial_snapshot_available(&raw, source));
|
||||
}
|
||||
assert!(!initial_snapshot_available(&DataUsageInfo::default(), UsageSnapshotSource::Primary));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initial_progress_requires_absence_in_the_unfiltered_current_incarnation() {
|
||||
let incarnation = uuid::Uuid::from_u128(1);
|
||||
assert!(initial_progress_allowed(None, incarnation));
|
||||
let mut previous = BucketUsageInfo {
|
||||
bucket_incarnation: Some(incarnation.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
// Filtering this value, a new reader, or a leader handoff cannot make
|
||||
// the same persisted bucket a first scan again.
|
||||
previous.bucket_incarnation = None;
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some("invalid".into());
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some(uuid::Uuid::nil().to_string());
|
||||
assert!(!initial_progress_allowed(Some(&previous), incarnation));
|
||||
previous.bucket_incarnation = Some(uuid::Uuid::from_u128(2).to_string());
|
||||
assert!(initial_progress_allowed(Some(&previous), incarnation));
|
||||
assert!(!initial_progress_allowed(None, uuid::Uuid::nil()));
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ fn companion_cannot_backfill_quota_and_projection_is_rejected_at_storage_boundar
|
||||
let mut accidental_quota = HashMap::new();
|
||||
backfill_degraded_baseline_from_observed(&mut accidental_quota, &snapshot);
|
||||
assert!(accidental_quota.is_empty());
|
||||
assert!(reject_admin_usage_projection(&snapshot).is_err());
|
||||
assert!(reject_display_only_usage(&snapshot).is_err());
|
||||
let wire = serde_json::to_vec(&snapshot).expect("admin response remains serializable");
|
||||
assert!(parse_usage_snapshot(&wire).is_err(), "a serialized response is not a persisted snapshot");
|
||||
assert_eq!(
|
||||
@@ -378,7 +378,7 @@ async fn cached_canonical_admin_usage_rechecks_current_identity_without_peer_inv
|
||||
assert!(!second.bucket_sizes.contains_key(bucket));
|
||||
assert_eq!(second.usage_snapshot_converged, Some(false));
|
||||
assert!(second.usage_snapshot_admin_projection);
|
||||
assert!(reject_admin_usage_projection(&second).is_err());
|
||||
assert!(reject_display_only_usage(&second).is_err());
|
||||
assert!(parse_usage_snapshot(&serde_json::to_vec(&second).expect("encode display response")).is_err());
|
||||
assert_eq!(
|
||||
UsageSnapshot::new(second, false).bucket_usage_certification(bucket, new_identity),
|
||||
|
||||
@@ -1926,6 +1926,38 @@ impl LocalDiskWrapper {
|
||||
.map_err(DiskError::Io)
|
||||
}
|
||||
|
||||
pub(crate) async fn advance_background_delete_discovery(
|
||||
&self,
|
||||
volume: String,
|
||||
session: Option<super::local::DiscoverySession>,
|
||||
limit: u32,
|
||||
cancel: CancellationToken,
|
||||
) -> Result<(Vec<super::DeleteTransactionId>, Option<super::local::DiscoverySession>)> {
|
||||
self.check_scanner_handle()?;
|
||||
let retired = self.retirement_token();
|
||||
// A queued bucket lease must not occupy the only background disk slot.
|
||||
let lease = self.disk.lock_delete_discovery_bucket(&volume).await?;
|
||||
let disk = Arc::clone(&self.disk);
|
||||
super::with_background_disk_io(
|
||||
cancel.clone(),
|
||||
self.track_disk_health_with_op_timeout_action_and_mutation_with_io_permit(
|
||||
"discover_delete_transactions",
|
||||
|permit| async move {
|
||||
super::io_admission::spawn_blocking_with_disk_io_permit(permit, move || {
|
||||
let _lease = lease;
|
||||
disk.advance_background_delete_discovery(&volume, session, limit, &cancel, &retired)
|
||||
})
|
||||
.await
|
||||
.map_err(DiskError::other)?
|
||||
},
|
||||
Duration::ZERO,
|
||||
TimeoutHealthAction::IgnoreFailure,
|
||||
DiskMetricMutation::None,
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn get_object_path_if_local(&self, volume: &str, path: &str) -> crate::disk::error::Result<std::path::PathBuf> {
|
||||
self.disk.get_object_path(volume, path)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ use self::commit::lock_rename_commit_directories;
|
||||
|
||||
mod commit;
|
||||
pub(super) mod delete_recovery;
|
||||
pub(crate) use delete_recovery::DiscoverySession;
|
||||
mod delete_reserve;
|
||||
#[cfg(all(unix, test))]
|
||||
#[path = "fd_cache_tests.rs"]
|
||||
@@ -18064,7 +18065,7 @@ impl DiskAPI for LocalDisk {
|
||||
|
||||
#[tracing::instrument(level = "trace", skip_all)]
|
||||
async fn update_metadata(&self, volume: &str, path: &str, fi: FileInfo, opts: &UpdateMetadataOpts) -> Result<()> {
|
||||
let status_only = super::usage_watch::status_only_metadata_update(&fi, opts);
|
||||
let status_only_candidate = super::usage_watch::status_only_metadata_candidate(&fi, opts);
|
||||
multipart_staging::reject_native_control_write(&self.root, self.io_root(), volume, path)?;
|
||||
pool_meta_native::reject_raw_path(&self.root, volume, path)?;
|
||||
let object_path = self.get_object_path(volume, path)?;
|
||||
@@ -18084,7 +18085,9 @@ impl DiskAPI for LocalDisk {
|
||||
.await;
|
||||
}
|
||||
let source_owner = self.multipart_source_owner(volume, path, false, true, None).await?;
|
||||
let source_owner = if status_only {
|
||||
// A status-only candidate takes usage ownership below, once the stored
|
||||
// version shows whether the update changes anything usage observes.
|
||||
let source_owner = if status_only_candidate {
|
||||
source_owner
|
||||
} else {
|
||||
self.usage_watch_binding.owner(volume, source_owner)
|
||||
@@ -18117,6 +18120,8 @@ impl DiskAPI for LocalDisk {
|
||||
let replace_user_metadata = opts.replace_user_metadata;
|
||||
let has_version_id = fi.version_id.is_some();
|
||||
let publication_root = self.publication_root.clone();
|
||||
let usage_watch_binding = Arc::clone(&self.usage_watch_binding);
|
||||
let usage_bucket = volume.to_string();
|
||||
let lease = os::acquire_namespace_mutation_lease_with_owner(&xl_file_path, namespace_owner).await;
|
||||
return os::run_blocking_namespace_operation_with_sync(
|
||||
lease,
|
||||
@@ -18132,13 +18137,20 @@ impl DiskAPI for LocalDisk {
|
||||
if !FileMeta::is_xl2_v1_format(&buf) {
|
||||
return Ok(Err(DiskError::FileVersionNotFound));
|
||||
}
|
||||
let wbuf = match FileMeta::load(&buf).and_then(|mut xl_meta| {
|
||||
let (wbuf, status_only) = match FileMeta::load(&buf).and_then(|mut xl_meta| {
|
||||
let stored = status_only_candidate.then(|| xl_meta.clone());
|
||||
xl_meta.update_object_version_with_opts(fi, replace_user_metadata)?;
|
||||
xl_meta.marshal_msg()
|
||||
let status_only =
|
||||
stored.is_some_and(|stored| super::usage_watch::status_only_metadata_change(&stored, &xl_meta));
|
||||
Ok((xl_meta.marshal_msg()?, status_only))
|
||||
}) {
|
||||
Ok(wbuf) => wbuf,
|
||||
Ok(update) => update,
|
||||
Err(err) => return Ok(Err(err.into())),
|
||||
};
|
||||
// Held until the rename below has finished.
|
||||
let _usage_owner = (status_only_candidate && !status_only)
|
||||
.then(|| usage_watch_binding.owner(&usage_bucket, None))
|
||||
.flatten();
|
||||
if let Some(parent) = tmp_file_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
@@ -18176,9 +18188,16 @@ impl DiskAPI for LocalDisk {
|
||||
}
|
||||
|
||||
let mut xl_meta = FileMeta::load(buf.as_ref())?;
|
||||
let stored = status_only_candidate.then(|| xl_meta.clone());
|
||||
|
||||
xl_meta.update_object_version_with_opts(fi, opts.replace_user_metadata)?;
|
||||
|
||||
let namespace_owner = match stored {
|
||||
Some(stored) if !super::usage_watch::status_only_metadata_change(&stored, &xl_meta) => {
|
||||
self.usage_watch_binding.owner(volume, namespace_owner)
|
||||
}
|
||||
_ => namespace_owner,
|
||||
};
|
||||
let wbuf = xl_meta.marshal_msg()?;
|
||||
|
||||
return self
|
||||
|
||||
@@ -31,13 +31,26 @@ pub(super) const PREPARED: &str = "delete-prepared";
|
||||
pub(super) const TARGET: &str = "delete-target";
|
||||
pub(super) const FINISHED: &str = "delete-commit-finished";
|
||||
const MAX_METADATA: u64 = 64 * 1024 * 1024;
|
||||
struct DiscoverySession {
|
||||
#[cfg(target_os = "linux")]
|
||||
type DiscoveryEntries = rustix::fs::Dir;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
type DiscoveryEntries = std::fs::ReadDir;
|
||||
|
||||
#[cfg(any(test, not(target_os = "linux")))]
|
||||
fn open_discovery_entries(path: &Path) -> std::io::Result<DiscoveryEntries> {
|
||||
#[cfg(target_os = "linux")]
|
||||
return rustix::fs::Dir::new(open_dir_fd(path)?).map_err(std::io::Error::from);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
std::fs::read_dir(path)
|
||||
}
|
||||
|
||||
pub(crate) struct DiscoverySession {
|
||||
disk_root: PathBuf,
|
||||
volume: String,
|
||||
object: Option<String>,
|
||||
root: PathBuf,
|
||||
_mount: std::fs::File,
|
||||
frames: Vec<(String, std::fs::ReadDir)>,
|
||||
frames: Vec<(String, DiscoveryEntries)>,
|
||||
touched: Instant,
|
||||
#[cfg(test)]
|
||||
metadata_stats: Arc<std::sync::atomic::AtomicUsize>,
|
||||
@@ -52,6 +65,7 @@ const PLAIN_CHILDREN_PER_BUDGET_ENTRY: u32 = 64;
|
||||
/// Entries one step of the resumable (background) discovery may visit. The
|
||||
/// foreground bounded protocol has its own, larger per-call allowance.
|
||||
const DISCOVERY_STEP_ENTRIES: u32 = 4096;
|
||||
const BACKGROUND_DISCOVERY_SLICE: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Wall-clock allowance of one bounded discovery call: a third of the drive
|
||||
/// timeout that wraps the call (including its wait for a lane worker), capped at
|
||||
@@ -90,8 +104,23 @@ impl DiscoverySession {
|
||||
max_entries: u32,
|
||||
should_stop: &dyn Fn() -> bool,
|
||||
) -> std::io::Result<(Vec<DeleteTransactionId>, Option<Self>, u32)> {
|
||||
if should_stop() {
|
||||
return Ok((Vec::new(), Some(self), 0));
|
||||
}
|
||||
if self.frames.is_empty() {
|
||||
match std::fs::read_dir(&self.root) {
|
||||
#[cfg(target_os = "linux")]
|
||||
let entries = {
|
||||
use rustix::fs::{Mode, OFlags};
|
||||
let mut relative = PathBuf::from(&self.volume);
|
||||
if let Some(object) = &self.object {
|
||||
relative.push(object);
|
||||
}
|
||||
os::open_linux_relative(&self._mount, &relative, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty())
|
||||
.and_then(|fd| rustix::fs::Dir::new(fd).map_err(std::io::Error::from))
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let entries = open_discovery_entries(&self.root);
|
||||
match entries {
|
||||
Ok(entries) => self.frames.push((String::new(), entries)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {
|
||||
return Ok((Vec::new(), None, 0));
|
||||
@@ -99,15 +128,14 @@ impl DiscoverySession {
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
let limit = usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?;
|
||||
let mut transactions = BTreeSet::new();
|
||||
let mut seen_candidates = HashSet::new();
|
||||
let mut visited = 0u32;
|
||||
let mut skipped_by_name = 0u32;
|
||||
while !self.frames.is_empty()
|
||||
&& transactions.len() < usize::try_from(limit).map_err(|_| std::io::Error::from(ErrorKind::InvalidInput))?
|
||||
&& visited < max_entries
|
||||
&& !should_stop()
|
||||
{
|
||||
while !self.frames.is_empty() && transactions.len() < limit && visited < max_entries && !should_stop() {
|
||||
// A valid 1024-byte key can exceed 256 one-byte components.
|
||||
let can_descend = self.frames.len() < 1024;
|
||||
let (parent, entries) = self
|
||||
.frames
|
||||
.last_mut()
|
||||
@@ -119,11 +147,17 @@ impl DiscoverySession {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let name = entry
|
||||
.file_name()
|
||||
.into_string()
|
||||
.map_err(|_| std::io::Error::from(ErrorKind::InvalidData))?;
|
||||
if !safe_path(&name, false) || name.contains('/') {
|
||||
let name = entry.file_name();
|
||||
#[cfg(target_os = "linux")]
|
||||
if matches!(name.to_bytes(), b"." | b"..") {
|
||||
continue;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
let name = name.to_str().ok();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let name = name.to_str();
|
||||
let name = name.ok_or_else(|| std::io::Error::from(ErrorKind::InvalidData))?;
|
||||
if !safe_path(name, false) || name.contains('/') {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
// An object-scoped scan only ever descends into transaction (UUID)
|
||||
@@ -136,9 +170,9 @@ impl DiscoverySession {
|
||||
// folder prefix with many children, UUID-named or not, can complete.
|
||||
if self.object.is_some()
|
||||
&& if parent.is_empty() {
|
||||
!canonical_uuid(&name).is_some_and(|id| !id.is_nil())
|
||||
!canonical_uuid(name).is_some_and(|id| !id.is_nil())
|
||||
} else {
|
||||
!may_be_delete_evidence(&name)
|
||||
!may_be_delete_evidence(name)
|
||||
}
|
||||
{
|
||||
skipped_by_name += 1;
|
||||
@@ -148,115 +182,186 @@ impl DiscoverySession {
|
||||
continue;
|
||||
}
|
||||
visited += 1;
|
||||
if self.object.is_none() && !may_be_delete_evidence(&name) {
|
||||
let ft = match entry.file_type() {
|
||||
Ok(ft) => ft,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
#[cfg(target_os = "linux")]
|
||||
let is_dir = {
|
||||
use rustix::fs::{AtFlags, FileType, statat};
|
||||
|
||||
let kind = entry.file_type();
|
||||
#[cfg(test)]
|
||||
let kind = if FORCE_RAW_DIR_DT_UNKNOWN.with(std::cell::Cell::get) {
|
||||
FileType::Unknown
|
||||
} else {
|
||||
kind
|
||||
};
|
||||
if ft.is_symlink() {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
if !ft.is_dir() && !ft.is_file() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
if ft.is_file() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let relative = if parent.is_empty() {
|
||||
name.clone()
|
||||
} else {
|
||||
format!("{parent}/{name}")
|
||||
};
|
||||
let path = self.root.join(&relative);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
let kind = match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if !kind.is_dir() && !kind.is_file() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
if kind.is_file() {
|
||||
let bound = match self.object.as_deref() {
|
||||
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
|
||||
Some(_) => None,
|
||||
None => parent.rsplit_once('/'),
|
||||
let kind = if kind == FileType::Unknown {
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
match statat(entries.fd()?, entry.file_name(), AtFlags::SYMLINK_NOFOLLOW) {
|
||||
Ok(stat) => FileType::from_raw_mode(stat.st_mode),
|
||||
Err(rustix::io::Errno::NOENT) => continue,
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
} else {
|
||||
kind
|
||||
};
|
||||
if let Some((object, id)) = bound {
|
||||
let transaction =
|
||||
if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name.as_str()) {
|
||||
canonical_uuid(id).filter(|id| !id.is_nil())
|
||||
} else {
|
||||
[
|
||||
DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
]
|
||||
.iter()
|
||||
.find_map(|prefix| delete_transaction_marker_id(&name, prefix))
|
||||
};
|
||||
if let Some(transaction) = transaction {
|
||||
if !seen_candidates.insert((object.to_owned(), transaction)) {
|
||||
continue;
|
||||
}
|
||||
let physical = match self.object.as_ref() {
|
||||
Some(_) => self.root.clone(),
|
||||
None => self.root.join(object),
|
||||
};
|
||||
if name == STORAGE_FORMAT_FILE_BACKUP
|
||||
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let proof_root = physical.join(transaction.to_string());
|
||||
if self.object.is_some() {
|
||||
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
|
||||
transactions.insert((object.to_owned(), transaction));
|
||||
continue;
|
||||
}
|
||||
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
// Only a fully bound journal can name a logical
|
||||
// key. Other records remain discoverable by their
|
||||
// physical key for canonical inspection to reject.
|
||||
let record = match prepared {
|
||||
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
|
||||
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
|
||||
.map_err(std::io::Error::from)?
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
|
||||
.map(|receipt| receipt.journal),
|
||||
};
|
||||
let logical = record
|
||||
.filter(|journal| {
|
||||
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
|
||||
&& journal.volume == self.volume
|
||||
&& journal.transaction == transaction
|
||||
&& safe_path(&journal.object, false)
|
||||
&& match self.object.as_ref() {
|
||||
Some(scope) => scope == &journal.object,
|
||||
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
|
||||
}
|
||||
})
|
||||
.map_or_else(|| object.to_owned(), |journal| journal.object);
|
||||
transactions.insert((logical, transaction));
|
||||
match kind {
|
||||
FileType::Directory => true,
|
||||
FileType::RegularFile => false,
|
||||
FileType::Symlink => return Err(std::io::Error::from(DiskError::InvalidPath)),
|
||||
_ => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let is_dir = {
|
||||
if self.object.is_none() && !may_be_delete_evidence(name) {
|
||||
let kind = match entry.file_type() {
|
||||
Ok(kind) => kind,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if kind.is_file() {
|
||||
continue;
|
||||
}
|
||||
if kind.is_symlink() {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
if !kind.is_dir() {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(&name).is_some_and(|id| !id.is_nil())) {
|
||||
|
||||
let path = self.root.join(parent.as_str()).join(name);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.is_dir() => true,
|
||||
Ok(metadata) if metadata.is_file() => false,
|
||||
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
};
|
||||
|
||||
if is_dir {
|
||||
if self.object.is_some() && (!parent.is_empty() || !canonical_uuid(name).is_some_and(|id| !id.is_nil())) {
|
||||
continue;
|
||||
}
|
||||
// A valid 1024-byte key can exceed 256 one-byte path
|
||||
// components; allow its transaction/data directories too.
|
||||
if self.frames.len() >= 1024 {
|
||||
if !can_descend {
|
||||
return Err(std::io::Error::from(ErrorKind::InvalidData));
|
||||
}
|
||||
self.frames.push((relative, std::fs::read_dir(path)?));
|
||||
let relative = if parent.is_empty() {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{parent}/{name}")
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
let child = {
|
||||
use rustix::fs::{Mode, OFlags, openat};
|
||||
match openat(
|
||||
entries.fd()?,
|
||||
entry.file_name(),
|
||||
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
) {
|
||||
Ok(fd) => rustix::fs::Dir::new(fd).map_err(std::io::Error::from),
|
||||
Err(rustix::io::Errno::NOTDIR | rustix::io::Errno::LOOP) => {
|
||||
return Err(std::io::Error::from(DiskError::InvalidPath));
|
||||
}
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let child = open_discovery_entries(&self.root.join(&relative));
|
||||
match child {
|
||||
Ok(entries) => self.frames.push((relative, entries)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if !may_be_delete_evidence(name) {
|
||||
// Ordinary data and metadata files cannot contribute a recovery hint.
|
||||
continue;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// Keep canonical, live-path validation for the sparse proof candidates.
|
||||
let path = self.root.join(parent.as_str()).join(name);
|
||||
#[cfg(test)]
|
||||
self.metadata_stats.fetch_add(1, Ordering::Relaxed);
|
||||
reject_local_disk_symlink_components(&self.root, &path).map_err(std::io::Error::from)?;
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.is_file() => {}
|
||||
Ok(_) => return Err(std::io::Error::from(ErrorKind::InvalidData)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => continue,
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
let bound = match self.object.as_deref() {
|
||||
Some(object) if !parent.is_empty() && !parent.contains('/') => Some((object, parent.as_str())),
|
||||
Some(_) => None,
|
||||
None => parent.rsplit_once('/'),
|
||||
};
|
||||
if let Some((object, id)) = bound {
|
||||
let transaction = if [PREPARED, STORAGE_FORMAT_FILE_BACKUP, DELETE_QUORUM_COMMITTED_FILE].contains(&name) {
|
||||
canonical_uuid(id).filter(|id| !id.is_nil())
|
||||
} else {
|
||||
[
|
||||
DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RESERVED_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
RECOVERY_DELETE_DATA_DIR_MARKER_PREFIX,
|
||||
]
|
||||
.iter()
|
||||
.find_map(|prefix| delete_transaction_marker_id(name, prefix))
|
||||
};
|
||||
if let Some(transaction) = transaction {
|
||||
if !seen_candidates.insert((object.to_owned(), transaction)) {
|
||||
continue;
|
||||
}
|
||||
let physical = match self.object.as_ref() {
|
||||
Some(_) => self.root.clone(),
|
||||
None => self.root.join(object),
|
||||
};
|
||||
if name == STORAGE_FORMAT_FILE_BACKUP
|
||||
&& live_write_backup(&physical, transaction).map_err(std::io::Error::from)?
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let proof_root = physical.join(transaction.to_string());
|
||||
if self.object.is_some() {
|
||||
regular_file_exists(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
regular_file_exists(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE)).map_err(std::io::Error::from)?;
|
||||
transactions.insert((object.to_owned(), transaction));
|
||||
continue;
|
||||
}
|
||||
let prepared = regular_bytes(&proof_root.join(PREPARED)).map_err(std::io::Error::from)?;
|
||||
// Only a fully bound journal can name a logical
|
||||
// key. Other records remain discoverable by their
|
||||
// physical key for canonical inspection to reject.
|
||||
let record = match prepared {
|
||||
Some(bytes) => serde_json::from_slice::<DeleteRecoveryJournal>(&bytes).ok(),
|
||||
None => regular_bytes(&proof_root.join(DELETE_QUORUM_COMMITTED_FILE))
|
||||
.map_err(std::io::Error::from)?
|
||||
.filter(|bytes| !bytes.is_empty())
|
||||
.and_then(|bytes| parse_commit_receipt(&bytes).ok())
|
||||
.map(|receipt| receipt.journal),
|
||||
};
|
||||
let logical = record
|
||||
.filter(|journal| {
|
||||
journal.protocol_version == DELETE_RECOVERY_PROTOCOL_VERSION
|
||||
&& journal.volume == self.volume
|
||||
&& journal.transaction == transaction
|
||||
&& safe_path(&journal.object, false)
|
||||
&& match self.object.as_ref() {
|
||||
Some(scope) => scope == &journal.object,
|
||||
None => build_local_disk_object_path(&self.root, "", &journal.object).1 == physical,
|
||||
}
|
||||
})
|
||||
.map_or_else(|| object.to_owned(), |journal| journal.object);
|
||||
transactions.insert((logical, transaction));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,10 +379,9 @@ impl DiscoverySession {
|
||||
if !transactions.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(mut next) = next else {
|
||||
let Some(next) = next else {
|
||||
return Ok(false);
|
||||
};
|
||||
next.touched = Instant::now();
|
||||
self = next;
|
||||
}
|
||||
}
|
||||
@@ -1926,23 +2030,40 @@ impl LocalDisk {
|
||||
.await
|
||||
.map_err(to_file_error)?
|
||||
}
|
||||
/// Local maintenance may pause a page behind recovery backpressure. It
|
||||
/// retains only its own bounded set of cursors; remote callers still have
|
||||
/// the ordinary idle deadline and every resumed page rechecks mount identity.
|
||||
pub(crate) fn renew_delete_recovery_cursor(&self, volume: &str, cursor: &DeleteRecoveryCursor) -> bool {
|
||||
let mut sessions = DISCOVERY_SESSIONS.lock();
|
||||
let Some(session) = sessions.get_mut(&cursor.token) else {
|
||||
return false;
|
||||
};
|
||||
if session.disk_root != self.io_root()
|
||||
|| session.volume != volume
|
||||
|| session.object.is_some()
|
||||
|| session.touched.elapsed() > Duration::from_secs(300)
|
||||
{
|
||||
return false;
|
||||
pub(crate) async fn lock_delete_discovery_bucket(&self, volume: &str) -> Result<Arc<os::NamespaceMutationLease>> {
|
||||
if !safe_path(volume, false) || volume.contains('/') {
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
session.touched = Instant::now();
|
||||
true
|
||||
let path = build_local_disk_bucket_path(self.io_root(), volume);
|
||||
Ok(os::acquire_namespace_mutation_lease_with_owner(&path, None).await)
|
||||
}
|
||||
|
||||
pub(in crate::disk) fn advance_background_delete_discovery(
|
||||
&self,
|
||||
volume: &str,
|
||||
session: Option<DiscoverySession>,
|
||||
limit: u32,
|
||||
cancel: &tokio_util::sync::CancellationToken,
|
||||
retired: &tokio_util::sync::CancellationToken,
|
||||
) -> Result<(Vec<DeleteTransactionId>, Option<DiscoverySession>)> {
|
||||
if retired.is_cancelled() {
|
||||
return Err(DiskError::DiskNotFound);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Ok((Vec::new(), session));
|
||||
}
|
||||
let path = self.delete_discovery_path(volume, None)?;
|
||||
let session = match session {
|
||||
Some(session) => session,
|
||||
None => self.new_delete_discovery_session(volume, None, &path)?,
|
||||
};
|
||||
self.validate_delete_discovery_owner(&session)?;
|
||||
let deadline = Instant::now() + BACKGROUND_DISCOVERY_SLICE;
|
||||
let should_stop = || cancel.is_cancelled() || retired.is_cancelled() || Instant::now() >= deadline;
|
||||
let (transactions, next, _) = session
|
||||
.advance_bounded(limit, DISCOVERY_STEP_ENTRIES, &should_stop)
|
||||
.map_err(to_file_error)?;
|
||||
Ok((transactions, next))
|
||||
}
|
||||
|
||||
fn delete_discovery_path(&self, volume: &str, object: Option<&str>) -> Result<PathBuf> {
|
||||
@@ -1998,7 +2119,7 @@ impl LocalDisk {
|
||||
}
|
||||
|
||||
fn validate_delete_discovery_owner(&self, session: &DiscoverySession) -> Result<()> {
|
||||
if session.disk_root != self.io_root() || session.touched.elapsed() > Duration::from_secs(300) {
|
||||
if session.disk_root != self.io_root() {
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
@@ -2092,7 +2213,10 @@ impl LocalDisk {
|
||||
.lock()
|
||||
.remove(&cursor.token)
|
||||
.ok_or(DiskError::FileNotFound)?;
|
||||
if session.volume != volume || session.object.as_deref() != object {
|
||||
if session.volume != volume
|
||||
|| session.object.as_deref() != object
|
||||
|| session.touched.elapsed() > Duration::from_secs(300)
|
||||
{
|
||||
return Err(DiskError::InvalidPath);
|
||||
}
|
||||
(cursor.token, session)
|
||||
@@ -7740,10 +7864,6 @@ mod tests {
|
||||
.expect("bounded discovery continues");
|
||||
found.extend(page.transactions.into_iter().map(|id| (id.object, id.transaction)));
|
||||
cursor = page.next;
|
||||
if let Some(cursor) = cursor.as_ref() {
|
||||
assert!(!disk.renew_delete_recovery_cursor("different-bucket", cursor));
|
||||
assert!(disk.renew_delete_recovery_cursor("recovery", cursor));
|
||||
}
|
||||
if cursor.is_none() {
|
||||
break;
|
||||
}
|
||||
@@ -8324,8 +8444,8 @@ mod tests {
|
||||
// Seed a valid DFS continuation so this assertion is independent of
|
||||
// filesystem directory ordering: the large empty frame runs first.
|
||||
session.frames = vec![
|
||||
(transaction.to_string(), std::fs::read_dir(&proof).expect("later evidence frame")),
|
||||
(filler_id, std::fs::read_dir(&filler).expect("empty intermediate frame")),
|
||||
(transaction.to_string(), open_discovery_entries(&proof).expect("later evidence frame")),
|
||||
(filler_id, open_discovery_entries(&filler).expect("empty intermediate frame")),
|
||||
];
|
||||
assert!(
|
||||
session
|
||||
@@ -8932,6 +9052,23 @@ mod tests {
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let prefix = temp.path().join("recovery/prefix");
|
||||
fs::create_dir_all(prefix.join("key")).await.expect("object directory");
|
||||
fs::create_dir(outside.path().join("key"))
|
||||
.await
|
||||
.expect("outside object directory");
|
||||
let path = disk
|
||||
.delete_discovery_path("recovery", Some("prefix/key"))
|
||||
.expect("validated key path");
|
||||
let session = disk
|
||||
.new_delete_discovery_session("recovery", Some("prefix/key"), &path)
|
||||
.expect("unopened key session");
|
||||
fs::remove_dir_all(&prefix).await.expect("remove original prefix");
|
||||
symlink(outside.path(), &prefix).expect("replace a parent after validation");
|
||||
assert!(session.advance(16).is_err(), "the real root open must reject a replaced ancestor");
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(outside.path().join("sentinel"))
|
||||
.await
|
||||
@@ -8965,13 +9102,36 @@ mod tests {
|
||||
assert!(transactions.is_empty());
|
||||
assert!(next.is_none());
|
||||
let stats = stats_counter.load(Ordering::Relaxed);
|
||||
// fixture() pre-creates recovery/object (1 directory + 1 xl.meta); with 32 obj-XX + 32 data_dir directories,
|
||||
// only the 65 directories reach symlink_metadata, while all 65 regular files (xl.meta and part.1) are skipped
|
||||
// via DirEntry::file_type() with 0 stats.
|
||||
assert_eq!(
|
||||
stats, 65,
|
||||
"bucket-wide discovery must skip inert regular files without symlink_metadata stats"
|
||||
);
|
||||
// The fixture has 65 directories and 65 regular files. An ordinary
|
||||
// Linux walk uses d_type and opens directories relative to the parent FD.
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let expected = match open_discovery_entries(&bucket_root).expect("read dirents").find_map(|entry| {
|
||||
let entry = entry.expect("dirent");
|
||||
(!matches!(entry.file_name().to_bytes(), b"." | b"..")).then(|| entry.file_type())
|
||||
}) {
|
||||
Some(rustix::fs::FileType::Unknown) => 130,
|
||||
Some(_) => 0,
|
||||
None => panic!("the fixture contains directories"),
|
||||
};
|
||||
assert_eq!(stats, expected, "known directory types must skip path-based metadata checks");
|
||||
|
||||
let session = disk
|
||||
.new_delete_discovery_session("recovery", None, &disc_path)
|
||||
.expect("discovery session with unknown dirent types");
|
||||
let fallback_stats = Arc::clone(&session.metadata_stats);
|
||||
let result = FORCE_RAW_DIR_DT_UNKNOWN.with(|flag| {
|
||||
let previous = flag.replace(true);
|
||||
let result = session.advance(16);
|
||||
flag.set(previous);
|
||||
result
|
||||
});
|
||||
let (transactions, next) = result.expect("unknown directory types use no-follow statat");
|
||||
assert!(transactions.is_empty() && next.is_none());
|
||||
assert_eq!(fallback_stats.load(Ordering::Relaxed), 130, "one parent-relative stat per unknown entry");
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
assert_eq!(stats, 65, "the portable walk skips metadata checks for ordinary files");
|
||||
|
||||
// A symlink with an inert file name ("part.1") inside a bucket-wide walk must still fail closed with InvalidPath.
|
||||
let outside = tempfile::tempdir().expect("outside dir");
|
||||
|
||||
@@ -98,30 +98,81 @@ async fn usage_watch_stays_inflight_after_metadata_is_visible_and_waiter_is_canc
|
||||
);
|
||||
}
|
||||
|
||||
const REPLICATION_TARGET_ARN: &str = "arn:rustfs:replication::target:bucket";
|
||||
|
||||
/// Stores one version and returns it the way a status write-back starts: the
|
||||
/// whole version metadata read back from the disk.
|
||||
async fn stored_version(disk: &LocalDisk) -> FileInfo {
|
||||
let mut info =
|
||||
super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
|
||||
info.metadata.insert("etag".into(), "5d41402abc4b2a76b9719d911017c592".into());
|
||||
info.metadata.insert("content-type".into(), "application/octet-stream".into());
|
||||
let version_id = info.version_id.expect("fixture version id").to_string();
|
||||
disk.write_metadata("", "bucket", "object", info)
|
||||
.await
|
||||
.expect("initial counted version");
|
||||
disk.read_version("", "bucket", "object", &version_id, &ReadOptions::default())
|
||||
.await
|
||||
.expect("stored version")
|
||||
}
|
||||
|
||||
/// Mirrors what `put_object_metadata` hands the disk for a status write-back.
|
||||
fn apply_replication_writeback(fi: &mut FileInfo, status: &str) {
|
||||
insert_replication_writeback(&mut fi.metadata, status);
|
||||
fi.acknowledge_data_movement();
|
||||
}
|
||||
|
||||
fn insert_replication_writeback(metadata: &mut HashMap<String, String>, status: &str) {
|
||||
use rustfs_utils::http::metadata_compat::insert_str;
|
||||
use rustfs_utils::http::{
|
||||
SUFFIX_REPLICATION_RESET_ARN_PREFIX, SUFFIX_REPLICATION_STATUS, SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX,
|
||||
};
|
||||
insert_str(metadata, SUFFIX_REPLICATION_STATUS, format!("{REPLICATION_TARGET_ARN}={status};"));
|
||||
insert_str(
|
||||
metadata,
|
||||
&format!("{SUFFIX_REPLICATION_RESET_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
|
||||
"2026-01-01T00:00:00Z;reset".into(),
|
||||
);
|
||||
insert_str(
|
||||
metadata,
|
||||
&format!("{SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX}{REPLICATION_TARGET_ARN}"),
|
||||
"target-version".into(),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
let info = super::test::test_file_info("object", Uuid::new_v4(), Some(Uuid::new_v4()), Some(Bytes::from_static(b"payload")));
|
||||
disk.write_metadata("", "bucket", "object", info.clone())
|
||||
.await
|
||||
.expect("initial counted version");
|
||||
let info = stored_version(&disk).await;
|
||||
let before = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("idle watch");
|
||||
let mut status = info.clone();
|
||||
status.metadata.clear();
|
||||
rustfs_utils::http::metadata_compat::insert_str(
|
||||
&mut status.metadata,
|
||||
rustfs_utils::http::SUFFIX_REPLICATION_STATUS,
|
||||
"arn=COMPLETED;".into(),
|
||||
);
|
||||
disk.update_metadata("bucket", "object", status, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("status-class metadata update");
|
||||
// A write-back carries the whole version metadata, not only the status keys.
|
||||
for status in ["PENDING", "COMPLETED"] {
|
||||
let mut writeback = info.clone();
|
||||
apply_replication_writeback(&mut writeback, status);
|
||||
disk.update_metadata("bucket", "object", writeback, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("status-class metadata update");
|
||||
}
|
||||
let after = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("status result watch");
|
||||
assert!(after.unchanged_since(&before), "replication counters retain maintenance cadence");
|
||||
let stored = disk
|
||||
.read_version(
|
||||
"",
|
||||
"bucket",
|
||||
"object",
|
||||
&info.version_id.expect("version id").to_string(),
|
||||
&ReadOptions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("written status");
|
||||
assert_eq!(
|
||||
rustfs_utils::http::get_consistent_str(&stored.metadata, rustfs_utils::http::SUFFIX_REPLICATION_STATUS),
|
||||
Some(format!("{REPLICATION_TARGET_ARN}=COMPLETED;").as_str()),
|
||||
);
|
||||
let mut next = info;
|
||||
next.version_id = Some(Uuid::new_v4());
|
||||
disk.write_metadata("", "bucket", "object", next).await.expect("new version");
|
||||
@@ -132,6 +183,33 @@ async fn usage_watch_status_only_metadata_keeps_maintenance_semantics() {
|
||||
assert_eq!(changed.inflight, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_status_write_with_other_metadata_change_revokes_proof() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
let info = stored_version(&disk).await;
|
||||
let mut seeded = info.clone();
|
||||
apply_replication_writeback(&mut seeded, "PENDING");
|
||||
disk.update_metadata("bucket", "object", seeded.clone(), &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("seed status keys");
|
||||
let before = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("idle watch");
|
||||
// Status keys ride along, but the same update also rewrites user metadata.
|
||||
let mut tagged = seeded;
|
||||
apply_replication_writeback(&mut tagged, "COMPLETED");
|
||||
tagged.metadata.insert("x-amz-meta-owner".into(), "changed".into());
|
||||
disk.update_metadata("bucket", "object", tagged, &UpdateMetadataOpts::default())
|
||||
.await
|
||||
.expect("mixed metadata update");
|
||||
let after = registry
|
||||
.observe(Uuid::from_u128(1), &watch_request("bucket"))
|
||||
.expect("mixed update watch");
|
||||
assert!(after.revision > before.revision);
|
||||
assert!(!after.unchanged_since(&before), "a non-status change must revoke the proof");
|
||||
assert_eq!(after.inflight, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_watch_raw_live_stream_revokes_coverage_and_internal_staging_does_not() {
|
||||
let (_root, disk, registry) = fixture().await;
|
||||
|
||||
@@ -2728,18 +2728,25 @@ const DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 256;
|
||||
const MAX_FSYNC_WORKER_IDLE_SPIN_ITERS: usize = 1024;
|
||||
const FALLBACK_NAMESPACE_QUEUE_SHARDS: usize = 8;
|
||||
|
||||
const ENV_FSYNC_WORKERS_PER_DISK: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKERS_PER_DISK";
|
||||
const ENV_FSYNC_WORKER_IDLE_SPIN_ITERS: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKER_IDLE_SPIN_ITERS";
|
||||
const ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE: &str = "RUSTFS_EXPERIMENTAL_FSYNC_WORKER_KEEP_MULTIPLE_IDLE";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct FsyncWorkerIdlePolicy {
|
||||
struct FsyncWorkerPolicy {
|
||||
max_workers: usize,
|
||||
spin_iters: usize,
|
||||
keep_multiple_idle: bool,
|
||||
}
|
||||
|
||||
impl FsyncWorkerIdlePolicy {
|
||||
impl FsyncWorkerPolicy {
|
||||
fn from_env() -> Self {
|
||||
let max_workers = match rustfs_utils::get_env_usize(ENV_FSYNC_WORKERS_PER_DISK, MAX_FSYNC_WORKERS_PER_DISK) {
|
||||
4 => 4,
|
||||
_ => MAX_FSYNC_WORKERS_PER_DISK,
|
||||
};
|
||||
Self {
|
||||
max_workers,
|
||||
spin_iters: rustfs_utils::get_env_usize(ENV_FSYNC_WORKER_IDLE_SPIN_ITERS, DEFAULT_FSYNC_WORKER_IDLE_SPIN_ITERS)
|
||||
.min(MAX_FSYNC_WORKER_IDLE_SPIN_ITERS),
|
||||
keep_multiple_idle: rustfs_utils::get_env_bool(ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE, true),
|
||||
@@ -2748,7 +2755,7 @@ impl FsyncWorkerIdlePolicy {
|
||||
}
|
||||
|
||||
// Resolve once so each queue uses one policy throughout worker retirement and respawn.
|
||||
static FSYNC_WORKER_IDLE_POLICY: LazyLock<FsyncWorkerIdlePolicy> = LazyLock::new(FsyncWorkerIdlePolicy::from_env);
|
||||
static FSYNC_WORKER_POLICY: LazyLock<FsyncWorkerPolicy> = LazyLock::new(FsyncWorkerPolicy::from_env);
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum DiskBlockingLane {
|
||||
@@ -2788,7 +2795,7 @@ struct DiskBlockingQueueLane {
|
||||
|
||||
pub(crate) struct DiskBlockingQueue {
|
||||
lanes: [DiskBlockingQueueLane; 3],
|
||||
fsync_idle_policy: FsyncWorkerIdlePolicy,
|
||||
fsync_worker_policy: FsyncWorkerPolicy,
|
||||
#[cfg(test)]
|
||||
before_idle_spin: Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
|
||||
}
|
||||
@@ -2857,13 +2864,13 @@ impl Drop for DiskBlockingWorkerGuard {
|
||||
|
||||
impl DiskBlockingQueue {
|
||||
fn new() -> Arc<Self> {
|
||||
Self::with_fsync_idle_policy(*FSYNC_WORKER_IDLE_POLICY)
|
||||
Self::with_fsync_worker_policy(*FSYNC_WORKER_POLICY)
|
||||
}
|
||||
|
||||
fn with_fsync_idle_policy(fsync_idle_policy: FsyncWorkerIdlePolicy) -> Arc<Self> {
|
||||
fn with_fsync_worker_policy(fsync_worker_policy: FsyncWorkerPolicy) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
lanes: std::array::from_fn(|_| DiskBlockingQueueLane::default()),
|
||||
fsync_idle_policy,
|
||||
fsync_worker_policy,
|
||||
#[cfg(test)]
|
||||
before_idle_spin: Mutex::new(None),
|
||||
})
|
||||
@@ -2878,7 +2885,7 @@ impl DiskBlockingQueue {
|
||||
fn lane_max_workers(&self, lane: DiskBlockingLane) -> usize {
|
||||
match lane {
|
||||
DiskBlockingLane::Foreground | DiskBlockingLane::Isolated => MAX_NAMESPACE_WORKERS_PER_DISK,
|
||||
DiskBlockingLane::Fsync => MAX_FSYNC_WORKERS_PER_DISK,
|
||||
DiskBlockingLane::Fsync => self.fsync_worker_policy.max_workers,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2985,7 +2992,7 @@ impl DiskBlockingQueue {
|
||||
.ready
|
||||
.store(!state.jobs.is_empty(), std::sync::atomic::Ordering::Relaxed);
|
||||
if job.is_none() {
|
||||
if (lane != DiskBlockingLane::Fsync || !queue.fsync_idle_policy.keep_multiple_idle)
|
||||
if (lane != DiskBlockingLane::Fsync || !queue.fsync_worker_policy.keep_multiple_idle)
|
||||
&& state.idle_workers > 0
|
||||
{
|
||||
state.active_workers = state.active_workers.saturating_sub(1);
|
||||
@@ -3013,7 +3020,7 @@ impl DiskBlockingQueue {
|
||||
}
|
||||
}
|
||||
let spin_iters = if lane == DiskBlockingLane::Fsync {
|
||||
queue.fsync_idle_policy.spin_iters
|
||||
queue.fsync_worker_policy.spin_iters
|
||||
} else {
|
||||
WORKER_IDLE_SPIN_ITERS
|
||||
};
|
||||
@@ -6583,7 +6590,7 @@ fn linux_relative_path_has_invalid_component(relative: &Path) -> bool {
|
||||
/// Open the actual IO handle with the same containment policy as path validation.
|
||||
/// Older kernels retain fd-relative traversal; only ENOSYS enables the fallback.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn open_linux_relative(
|
||||
pub(in crate::disk) fn open_linux_relative(
|
||||
directory: &std::fs::File,
|
||||
relative: &Path,
|
||||
flags: rustix::fs::OFlags,
|
||||
@@ -14329,9 +14336,10 @@ mod tests {
|
||||
assert_eq!(completed, 257, "yielding must not discard hot-disk jobs");
|
||||
}
|
||||
|
||||
fn fsync_idle_test_policies() -> impl Iterator<Item = FsyncWorkerIdlePolicy> {
|
||||
fn fsync_idle_test_policies() -> impl Iterator<Item = FsyncWorkerPolicy> {
|
||||
[0, 256, 1024].into_iter().flat_map(|spin_iters| {
|
||||
[false, true].map(|keep_multiple_idle| FsyncWorkerIdlePolicy {
|
||||
[false, true].map(|keep_multiple_idle| FsyncWorkerPolicy {
|
||||
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
|
||||
spin_iters,
|
||||
keep_multiple_idle,
|
||||
})
|
||||
@@ -14352,13 +14360,15 @@ mod tests {
|
||||
] {
|
||||
temp_env::with_vars(
|
||||
[
|
||||
(ENV_FSYNC_WORKERS_PER_DISK, None),
|
||||
(ENV_FSYNC_WORKER_IDLE_SPIN_ITERS, spin_value),
|
||||
(ENV_FSYNC_WORKER_KEEP_MULTIPLE_IDLE, multiple_value),
|
||||
],
|
||||
|| {
|
||||
assert_eq!(
|
||||
FsyncWorkerIdlePolicy::from_env(),
|
||||
FsyncWorkerIdlePolicy {
|
||||
FsyncWorkerPolicy::from_env(),
|
||||
FsyncWorkerPolicy {
|
||||
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
|
||||
spin_iters: expected_spins,
|
||||
keep_multiple_idle: expected_multiple,
|
||||
},
|
||||
@@ -14369,12 +14379,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disk_blocking_queue_fsync_worker_limit_accepts_only_experiment_values() {
|
||||
for (input, expected) in [
|
||||
(None, 8),
|
||||
(Some("4"), 4),
|
||||
(Some("8"), 8),
|
||||
(Some("0"), 8),
|
||||
(Some("16"), 8),
|
||||
(Some("invalid"), 8),
|
||||
] {
|
||||
temp_env::with_var(ENV_FSYNC_WORKERS_PER_DISK, input, || {
|
||||
let queue = DiskBlockingQueue::with_fsync_worker_policy(FsyncWorkerPolicy::from_env());
|
||||
assert_eq!(queue.lane_max_workers(DiskBlockingLane::Fsync), expected, "input={input:?}");
|
||||
assert_eq!(queue.lane_max_workers(DiskBlockingLane::Foreground), MAX_NAMESPACE_WORKERS_PER_DISK);
|
||||
assert_eq!(queue.lane_max_workers(DiskBlockingLane::Isolated), MAX_NAMESPACE_WORKERS_PER_DISK);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn disk_blocking_queue_drains_bursts_across_worker_retirement() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
for policy in fsync_idle_test_policies() {
|
||||
for lane in [DiskBlockingLane::Foreground, DiskBlockingLane::Fsync] {
|
||||
let queue = DiskBlockingQueue::with_fsync_idle_policy(policy);
|
||||
let queue = DiskBlockingQueue::with_fsync_worker_policy(policy);
|
||||
let completed = Arc::new(AtomicUsize::new(0));
|
||||
for _ in 0..8 {
|
||||
let mut producers = tokio::task::JoinSet::new();
|
||||
@@ -14499,7 +14528,8 @@ mod tests {
|
||||
|
||||
for keep_multiple_idle in [false, true] {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
let queue = DiskBlockingQueue::with_fsync_idle_policy(FsyncWorkerIdlePolicy {
|
||||
let queue = DiskBlockingQueue::with_fsync_worker_policy(FsyncWorkerPolicy {
|
||||
max_workers: MAX_FSYNC_WORKERS_PER_DISK,
|
||||
spin_iters: 256,
|
||||
keep_multiple_idle,
|
||||
});
|
||||
@@ -14621,8 +14651,14 @@ mod tests {
|
||||
async fn disk_blocking_queue_fsync_lane_scales_workers_and_retires_idle() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
for policy in fsync_idle_test_policies() {
|
||||
let queue = DiskBlockingQueue::with_fsync_idle_policy(policy);
|
||||
for policy in fsync_idle_test_policies().flat_map(|idle_policy| {
|
||||
[4, MAX_FSYNC_WORKERS_PER_DISK].map(|max_workers| FsyncWorkerPolicy {
|
||||
max_workers,
|
||||
..idle_policy
|
||||
})
|
||||
}) {
|
||||
let max_workers = policy.max_workers;
|
||||
let queue = DiskBlockingQueue::with_fsync_worker_policy(policy);
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
let max_seen = Arc::new(AtomicUsize::new(0));
|
||||
let entered = Arc::new(AtomicUsize::new(0));
|
||||
@@ -14631,7 +14667,7 @@ mod tests {
|
||||
let (release_tx, _) = tokio::sync::broadcast::channel::<()>(1);
|
||||
|
||||
let mut handles = Vec::new();
|
||||
for i in 0..(MAX_FSYNC_WORKERS_PER_DISK + 4) {
|
||||
for i in 0..(max_workers + 4) {
|
||||
let q = Arc::clone(&queue);
|
||||
let active = Arc::clone(&active);
|
||||
let max_seen = Arc::clone(&max_seen);
|
||||
@@ -14648,12 +14684,12 @@ mod tests {
|
||||
let cur = active.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
max_seen.fetch_max(cur, Ordering::SeqCst);
|
||||
let ord = entered.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
if ord == MAX_FSYNC_WORKERS_PER_DISK
|
||||
if ord == max_workers
|
||||
&& let Some(tx) = all_entered_tx.lock().expect("lock completion sender").take()
|
||||
{
|
||||
let _ = tx.send(());
|
||||
}
|
||||
if ord <= MAX_FSYNC_WORKERS_PER_DISK {
|
||||
if ord <= max_workers {
|
||||
let _ = release_rx.blocking_recv();
|
||||
}
|
||||
active.fetch_sub(1, Ordering::SeqCst);
|
||||
@@ -14668,13 +14704,27 @@ mod tests {
|
||||
.await
|
||||
.expect("all fsync workers should enter within timeout")
|
||||
.expect("all_entered channel");
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
loop {
|
||||
{
|
||||
let state = queue.lane(DiskBlockingLane::Fsync).state.lock();
|
||||
assert_eq!(state.active_workers, max_workers);
|
||||
if state.jobs.len() == 4 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("all excess jobs must queue while the fsync workers are busy");
|
||||
let _ = release_tx.send(());
|
||||
for (i, handle) in handles.into_iter().enumerate() {
|
||||
assert_eq!(handle.await.expect("task join").expect("fsync job"), i);
|
||||
}
|
||||
assert_eq!(
|
||||
max_seen.load(Ordering::SeqCst),
|
||||
MAX_FSYNC_WORKERS_PER_DISK,
|
||||
max_workers,
|
||||
"fsync lane must run MAX_FSYNC_WORKERS_PER_DISK concurrent workers up to its configured bound"
|
||||
);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
|
||||
@@ -7,27 +7,61 @@
|
||||
use crate::runtime::usage_watch::{UsageWatchMutationGuard, UsageWatchRegistry};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
/// Existing-version replication status writes change neither size nor version
|
||||
/// membership. Replication aggregates keep their existing maintenance cadence.
|
||||
pub(crate) fn status_only_metadata_update(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
|
||||
fn replication_status_class_key(key: &str) -> bool {
|
||||
use rustfs_utils::http::*;
|
||||
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
|
||||
let suffix = suffix.to_ascii_lowercase();
|
||||
[
|
||||
SUFFIX_REPLICA_STATUS,
|
||||
SUFFIX_REPLICA_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_STATUS,
|
||||
SUFFIX_REPLICATION_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_GENERATION,
|
||||
SUFFIX_REPLICATION_RESET,
|
||||
SUFFIX_PURGESTATUS,
|
||||
]
|
||||
.contains(&suffix.as_str())
|
||||
// Per-target resync stamps and target-assigned version ids.
|
||||
|| suffix.starts_with(SUFFIX_REPLICATION_RESET_ARN_PREFIX)
|
||||
|| suffix.starts_with(SUFFIX_REPLICATION_TARGET_VERSION_ARN_PREFIX)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a metadata update may turn out to be status-only. Callers hand the
|
||||
/// disk the whole version metadata, so the keys alone cannot settle it; the
|
||||
/// decision is made by [`status_only_metadata_change`] against the stored
|
||||
/// version once it has been read under the mutation lease.
|
||||
pub(crate) fn status_only_metadata_candidate(fi: &rustfs_filemeta::FileInfo, opts: &super::UpdateMetadataOpts) -> bool {
|
||||
!opts.replace_user_metadata
|
||||
&& opts.transition_reconcile.is_none()
|
||||
&& !fi.metadata.is_empty()
|
||||
&& fi.metadata.keys().all(|key| {
|
||||
strip_internal_prefix_preserving_case(key).is_some_and(|suffix| {
|
||||
[
|
||||
SUFFIX_REPLICA_STATUS,
|
||||
SUFFIX_REPLICA_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_STATUS,
|
||||
SUFFIX_REPLICATION_TIMESTAMP,
|
||||
SUFFIX_REPLICATION_GENERATION,
|
||||
SUFFIX_REPLICATION_RESET,
|
||||
SUFFIX_PURGESTATUS,
|
||||
]
|
||||
.iter()
|
||||
.any(|known| suffix.eq_ignore_ascii_case(known))
|
||||
})
|
||||
&& fi.metadata.keys().any(|key| replication_status_class_key(key))
|
||||
}
|
||||
|
||||
/// Existing-version replication status writes change neither size nor version
|
||||
/// membership. Replication aggregates keep their existing maintenance cadence.
|
||||
///
|
||||
/// True only when every stored version is unchanged apart from replication
|
||||
/// status-class internal keys. Anything that cannot be compared counts as a
|
||||
/// usage-relevant change.
|
||||
pub(crate) fn status_only_metadata_change(before: &rustfs_filemeta::FileMeta, after: &rustfs_filemeta::FileMeta) -> bool {
|
||||
fn without_status_keys(version: &rustfs_filemeta::FileMetaShallowVersion) -> Option<rustfs_filemeta::FileMetaVersion> {
|
||||
let mut parsed = version.parse_version_meta().ok()?;
|
||||
if let Some(object) = parsed.object.as_mut() {
|
||||
// Metadata updates also stamp an empty data-movement
|
||||
// acknowledgement; only a non-empty marker carries state.
|
||||
object.meta_sys.retain(|key, value| {
|
||||
!replication_status_class_key(key)
|
||||
&& !(value.is_empty() && rustfs_utils::http::has_internal_suffix(key, rustfs_utils::http::SUFFIX_DATA_MOVED))
|
||||
});
|
||||
}
|
||||
Some(parsed)
|
||||
}
|
||||
before.versions.len() == after.versions.len()
|
||||
&& before.versions.iter().zip(&after.versions).all(|(old, new)| {
|
||||
old.meta == new.meta
|
||||
|| without_status_keys(old)
|
||||
.zip(without_status_keys(new))
|
||||
.is_some_and(|(old, new)| old == new)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1315,17 +1315,16 @@ impl Erasure {
|
||||
calc_shard_size(self.block_size, self.data_shards)
|
||||
}
|
||||
}
|
||||
/// Calculate the total erasure file size for a given original size.
|
||||
// Returns the final erasure size from the original size
|
||||
/// Calculate the logical shard file size before bitrot framing.
|
||||
pub fn shard_file_size(&self, total_length: i64) -> i64 {
|
||||
if total_length == 0 {
|
||||
return 0;
|
||||
}
|
||||
if total_length < 0 {
|
||||
if total_length <= 0 {
|
||||
return total_length;
|
||||
}
|
||||
let total_length = usize::try_from(total_length).unwrap_or(usize::MAX);
|
||||
i64::try_from(self.shard_file_size_bytes(total_length)).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
let total_length = total_length as usize;
|
||||
fn shard_file_size_bytes(&self, total_length: usize) -> usize {
|
||||
let shard_size_fn = if self.uses_legacy {
|
||||
calc_shard_size_legacy
|
||||
} else {
|
||||
@@ -1335,21 +1334,24 @@ impl Erasure {
|
||||
let num_shards = total_length / self.block_size;
|
||||
let last_block_size = total_length % self.block_size;
|
||||
let last_shard_size = shard_size_fn(last_block_size, self.data_shards);
|
||||
(num_shards * self.shard_size() + last_shard_size) as i64
|
||||
num_shards.saturating_mul(self.shard_size()).saturating_add(last_shard_size)
|
||||
}
|
||||
|
||||
/// Calculate the offset in the erasure file where reading begins.
|
||||
// Returns the offset in the erasure file where reading begins
|
||||
/// Return the exclusive logical shard offset for the requested object bytes.
|
||||
/// Only stripes touched by the range are included, clipped to the final partial stripe.
|
||||
/// An empty range ends at the start of its stripe.
|
||||
pub fn shard_file_offset(&self, start_offset: usize, length: usize, total_length: usize) -> usize {
|
||||
let shard_size = self.shard_size();
|
||||
let shard_file_size = self.shard_file_size(total_length as i64) as usize;
|
||||
let end_shard = (start_offset + length) / self.block_size;
|
||||
let mut till_offset = end_shard * shard_size + shard_size;
|
||||
if till_offset > shard_file_size {
|
||||
till_offset = shard_file_size;
|
||||
let end = start_offset.saturating_add(length).min(total_length);
|
||||
let end_stripe = if length == 0 {
|
||||
end / self.block_size
|
||||
} else {
|
||||
end.div_ceil(self.block_size)
|
||||
};
|
||||
if end_stripe <= total_length / self.block_size {
|
||||
end_stripe.saturating_mul(self.shard_size())
|
||||
} else {
|
||||
self.shard_file_size_bytes(total_length)
|
||||
}
|
||||
|
||||
till_offset
|
||||
}
|
||||
|
||||
/// Encode all data from a reader in blocks, calling an async callback for each encoded block.
|
||||
@@ -2830,14 +2832,19 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_shard_file_offset() {
|
||||
let erasure = Erasure::new(8, 8, 1024 * 1024);
|
||||
let offset = erasure.shard_file_offset(0, 86, 86);
|
||||
println!("offset={offset}");
|
||||
assert!(offset > 0);
|
||||
|
||||
let total_length = erasure.shard_file_size(86);
|
||||
println!("total_length={total_length}");
|
||||
assert!(total_length > 0);
|
||||
const BLOCK: usize = 256 * 1024;
|
||||
const TOTAL: usize = 3 * BLOCK + 19;
|
||||
for legacy in [false, true] {
|
||||
let erasure = Erasure::try_new_with_options(3, 3, BLOCK, legacy).expect("supported erasure layout");
|
||||
let shard_size = erasure.shard_size();
|
||||
let tail = if legacy { 8 } else { 7 };
|
||||
assert_eq!(erasure.shard_file_offset(0, 0, TOTAL), 0);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 1, 0, TOTAL), shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 7, TOTAL), 2 * shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(BLOCK + 7, BLOCK - 6, TOTAL), 3 * shard_size);
|
||||
assert_eq!(erasure.shard_file_offset(3 * BLOCK, 1, TOTAL), 3 * shard_size + tail);
|
||||
assert_eq!(erasure.shard_file_offset(0, TOTAL, TOTAL), 3 * shard_size + tail);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -213,11 +213,9 @@ fn buffer_local_shard_stream(reader: ShardReader, length: usize) -> disk::error:
|
||||
// enlarge that reservation and allocate a second, unaccounted buffer.
|
||||
return Ok(ShardReader::Stream(Box::new(reader.take(limit))));
|
||||
}
|
||||
// Small layout stripes otherwise dispatch a blocking file read per frame.
|
||||
// Short ranges keep direct reads: the caller's conservative stream span
|
||||
// can include an extra stripe beyond the final requested block. Long
|
||||
// streams stay bounded to that span; prefetched frames still authenticate
|
||||
// individually when consumed by the bitrot reader.
|
||||
// Buffer long reads of small frames to avoid a blocking dispatch per frame.
|
||||
// Prefetch stays within the requested span, and each frame authenticates
|
||||
// when consumed by the bitrot reader.
|
||||
Ok(ShardReader::Stream(Box::new(tokio::io::BufReader::with_capacity(
|
||||
256 * 1024,
|
||||
reader.take(limit),
|
||||
@@ -1135,15 +1133,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_local_shard_stream_does_not_prefetch_conservative_short_range_tail() {
|
||||
async fn buffered_local_shard_stream_keeps_short_range_reads_direct() {
|
||||
const BLOCK: usize = 256 * 1024;
|
||||
const SHARD: usize = BLOCK / 2;
|
||||
let algo = HashAlgorithm::HighwayHash256S;
|
||||
let erasure = crate::erasure::coding::Erasure::new(2, 2, BLOCK);
|
||||
// An aligned 1 MiB Range consumes four data-shard frames, while the
|
||||
// existing reader planner conservatively opens five logical shards.
|
||||
let logical_window = erasure.shard_file_offset(0, 4 * BLOCK, 6 * BLOCK);
|
||||
assert_eq!(logical_window, 5 * SHARD);
|
||||
// A short stream may be consumed only in part before cancellation.
|
||||
let logical_window = 5 * SHARD;
|
||||
let (_, wire_window) = adjust_shard_read_params(0, logical_window, SHARD, &algo);
|
||||
let payload = vec![73; SHARD];
|
||||
let mut encoded = Vec::new();
|
||||
@@ -1152,10 +1147,7 @@ mod tests {
|
||||
for _ in 0..4 {
|
||||
writer.write(&payload).await.expect("encode requested range frames");
|
||||
}
|
||||
writer
|
||||
.write(&vec![99; SHARD])
|
||||
.await
|
||||
.expect("encode unrequested conservative tail frame");
|
||||
writer.write(&vec![99; SHARD]).await.expect("encode unread tail frame");
|
||||
}
|
||||
assert_eq!(encoded.len(), wire_window);
|
||||
let reads = Arc::new(AtomicUsize::new(0));
|
||||
@@ -1168,7 +1160,7 @@ mod tests {
|
||||
})),
|
||||
wire_window,
|
||||
)
|
||||
.expect("open conservative short range stream");
|
||||
.expect("open short range stream");
|
||||
let mut reader = BitrotReader::new(source, SHARD, algo.clone(), false);
|
||||
let mut output = Vec::new();
|
||||
for _ in 0..4 {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use crate::disk::{DiskAPI, DiskStore};
|
||||
use crate::disk::{DiskAPI, DiskStore, FileReader};
|
||||
use crate::erasure::codec::shard_buf::ShardBytes;
|
||||
use bytes::Bytes;
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
@@ -539,19 +539,28 @@ pub(crate) struct PartProofReader {
|
||||
sources: Vec<(DiskStore, String)>,
|
||||
volume: String,
|
||||
inline: Option<Bytes>,
|
||||
read_end: Option<u32>,
|
||||
cached: Mutex<ProofCache>,
|
||||
}
|
||||
|
||||
struct ProofWindow {
|
||||
next: u32,
|
||||
end: u32,
|
||||
reader: FileReader,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProofCache {
|
||||
records: std::collections::VecDeque<(u32, Bytes)>,
|
||||
preferred: usize,
|
||||
window: Option<ProofWindow>,
|
||||
}
|
||||
|
||||
// The root is checked against the complete descriptor during authentication.
|
||||
// A cache hit must carry the same geometry, part number, size and stripe count.
|
||||
type VerifiedStripeKey = (PartIntegrity, u32);
|
||||
const MAX_SHARED_CACHE_STRIPES: u32 = 4;
|
||||
const PROOF_WINDOW_STRIPES: u32 = 16;
|
||||
|
||||
static VERIFIED_STRIPE_RECORDS: std::sync::LazyLock<parking_lot::Mutex<std::collections::HashMap<VerifiedStripeKey, Bytes>>> =
|
||||
std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
|
||||
@@ -607,6 +616,7 @@ impl PartProofReader {
|
||||
disks: &[Option<DiskStore>],
|
||||
volume: &str,
|
||||
object: &str,
|
||||
read_end: Option<u32>,
|
||||
) -> io::Result<Arc<Self>> {
|
||||
part.validate().map_err(|_| corrupt())?;
|
||||
let mut sources = Vec::with_capacity(disks.len());
|
||||
@@ -648,6 +658,7 @@ impl PartProofReader {
|
||||
sources,
|
||||
volume: volume.to_owned(),
|
||||
inline,
|
||||
read_end,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
}))
|
||||
}
|
||||
@@ -655,6 +666,10 @@ impl PartProofReader {
|
||||
pub(crate) async fn record(&self, stripe: u32) -> io::Result<Bytes> {
|
||||
let offset = self.part.record_offset(stripe).map_err(|_| corrupt())?;
|
||||
let size = self.part.record_size();
|
||||
let end = self.read_end.unwrap_or(self.part.stripes).min(self.part.stripes);
|
||||
if stripe >= end {
|
||||
return Err(corrupt());
|
||||
}
|
||||
// Inline records are immutable and authenticated at construction.
|
||||
if let Some(inline) = &self.inline {
|
||||
return Ok(inline.slice(offset..offset + size));
|
||||
@@ -672,8 +687,17 @@ impl PartProofReader {
|
||||
let record = if let Some(record) = shared {
|
||||
record
|
||||
} else {
|
||||
let (replica, record) = self.read_verified_record(stripe, offset, size, cached.preferred).await?;
|
||||
let window = cached.window.take().filter(|window| window.next == stripe);
|
||||
let end = if share {
|
||||
stripe + 1
|
||||
} else {
|
||||
end.min(stripe.saturating_add(PROOF_WINDOW_STRIPES))
|
||||
};
|
||||
let (replica, record, next_window) = self
|
||||
.read_verified_record(stripe, offset, size, end, cached.preferred, window)
|
||||
.await?;
|
||||
cached.preferred = replica;
|
||||
cached.window = next_window;
|
||||
if share {
|
||||
put_verified_stripe_record(&self.part, stripe, record.clone());
|
||||
}
|
||||
@@ -691,38 +715,81 @@ impl PartProofReader {
|
||||
stripe: u32,
|
||||
offset: usize,
|
||||
size: usize,
|
||||
end: u32,
|
||||
preferred: usize,
|
||||
) -> io::Result<(usize, Bytes)> {
|
||||
window: Option<ProofWindow>,
|
||||
) -> io::Result<(usize, Bytes, Option<ProofWindow>)> {
|
||||
if self.sources.is_empty() {
|
||||
return Err(corrupt());
|
||||
}
|
||||
let read = |index: usize| async move {
|
||||
let read = |index: usize, window: Option<ProofWindow>| async move {
|
||||
let (disk, path) = &self.sources[index];
|
||||
tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||
let mut reader = disk
|
||||
.read_file_stream(&self.volume, path, offset, size)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let open = async |end: u32, bytes: &mut [u8]| {
|
||||
let count = usize::try_from(end - stripe).map_err(|_| corrupt())?;
|
||||
let length = size.checked_mul(count).ok_or_else(corrupt)?;
|
||||
#[cfg(test)]
|
||||
crate::set_disk::disk_call_counters::record_proof_stream_open(path, index);
|
||||
let reader = disk
|
||||
.read_file_stream(&self.volume, path, offset, length)
|
||||
.await
|
||||
.map_err(crate::disk::error::terminal_read_error_to_io)?;
|
||||
let mut reader = if count > 1 && disk.is_local() {
|
||||
Box::new(tokio::io::BufReader::with_capacity(length, reader)) as FileReader
|
||||
} else {
|
||||
reader
|
||||
};
|
||||
reader.read_exact(bytes).await?;
|
||||
io::Result::Ok(reader)
|
||||
};
|
||||
let mut bytes = vec![0; size];
|
||||
reader.read_exact(&mut bytes).await?;
|
||||
let next = stripe + 1;
|
||||
let continued = window.is_some();
|
||||
let (end, result) = if let Some(mut window) = window {
|
||||
let result = window.reader.read_exact(&mut bytes).await.map(|_| window.reader);
|
||||
(window.end, result)
|
||||
} else {
|
||||
(end, open(end, &mut bytes).await)
|
||||
};
|
||||
let (end, reader) = match result {
|
||||
Ok(reader) => (end, reader),
|
||||
// A truncated window or broken continuation can leave the
|
||||
// current record readable through a fresh exact request.
|
||||
Err(error)
|
||||
if (continued || end > next)
|
||||
&& !matches!(error.kind(), io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied) =>
|
||||
{
|
||||
(next, open(next, &mut bytes).await?)
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
self.part.verify_record(stripe, &bytes).map_err(|_| corrupt())?;
|
||||
io::Result::Ok((index, Bytes::from(bytes)))
|
||||
let window = (next < end).then_some(ProofWindow { next, end, reader });
|
||||
io::Result::Ok((index, Bytes::from(bytes), window))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))?
|
||||
};
|
||||
let mut pending = FuturesUnordered::new();
|
||||
pending.push(read(preferred));
|
||||
tokio::select! {
|
||||
result = pending.next() => {
|
||||
if let Some(Ok(Ok(record))) = result {
|
||||
return Ok(record);
|
||||
let primary = read(preferred, window);
|
||||
tokio::pin!(primary);
|
||||
let mut primary_pending = match tokio::time::timeout(std::time::Duration::from_millis(50), primary.as_mut()).await {
|
||||
Ok(Ok(record)) => return Ok(record),
|
||||
Ok(_) => false,
|
||||
Err(_) => true,
|
||||
};
|
||||
let mut replicas: FuturesUnordered<_> = (0..self.sources.len())
|
||||
.filter(|&index| index != preferred)
|
||||
.map(|index| read(index, None))
|
||||
.collect();
|
||||
while primary_pending || !replicas.is_empty() {
|
||||
let result = tokio::select! {
|
||||
result = &mut primary, if primary_pending => {
|
||||
primary_pending = false;
|
||||
result
|
||||
}
|
||||
}
|
||||
() = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}
|
||||
}
|
||||
pending.extend((0..self.sources.len()).filter(|&index| index != preferred).map(read));
|
||||
while let Some(result) = pending.next().await {
|
||||
if let Ok(Ok(record)) = result {
|
||||
Some(result) = replicas.next() => result,
|
||||
};
|
||||
if let Ok(record) = result {
|
||||
return Ok(record);
|
||||
}
|
||||
}
|
||||
@@ -842,7 +909,7 @@ pub(crate) async fn verify_deep_parts(
|
||||
let read_timeout = crate::disk::disk_store::get_object_disk_read_timeout();
|
||||
for (part_index, part) in expected.parts.iter().enumerate() {
|
||||
let commitment = part.integrity.as_ref().ok_or(DiskError::FileCorrupt)?;
|
||||
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object).map_err(DiskError::from)?;
|
||||
let proof = PartProofReader::new(commitment.clone(), files, disks, volume, object, None).map_err(DiskError::from)?;
|
||||
if commitment.stripes == 0 && commitment.root != commitment.root_digest(&commitment.padding_digest(0)) {
|
||||
return Err(DiskError::FileCorrupt);
|
||||
}
|
||||
@@ -982,6 +1049,7 @@ pub(crate) async fn restore_proof_replicas(
|
||||
sources: disks.iter().flatten().map(|disk| (disk.clone(), path.clone())).collect(),
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let prepared = PreparedIntegrity::copy_from(&proof).await.map_err(DiskError::from)?;
|
||||
@@ -1066,6 +1134,7 @@ mod tests {
|
||||
sources: vec![],
|
||||
volume: "bucket".to_owned(),
|
||||
inline: Some(bytes),
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
});
|
||||
let mut verifier = ShardVerifier::new(proof, 0, 0, None).expect("verifier");
|
||||
@@ -1086,6 +1155,7 @@ mod tests {
|
||||
let proof = PartProofReader {
|
||||
part: prepared.part,
|
||||
inline: Some(index),
|
||||
read_end: None,
|
||||
sources: Vec::new(),
|
||||
volume: String::new(),
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
@@ -1143,14 +1213,14 @@ mod tests {
|
||||
let mut shortened = part.clone();
|
||||
shortened.size = 8;
|
||||
shortened.stripes = 1;
|
||||
let mismatched_reader =
|
||||
PartProofReader::new(shortened, &[], &[], "bucket", "object").expect("the altered descriptor is structurally valid");
|
||||
let mismatched_reader = PartProofReader::new(shortened, &[], &[], "bucket", "object", None)
|
||||
.expect("the altered descriptor is structurally valid");
|
||||
assert!(
|
||||
mismatched_reader.verify(0, 0, shards[0]).await.is_err(),
|
||||
"a matching generation and root must not admit a shortened part"
|
||||
);
|
||||
|
||||
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object").expect("matching descriptor");
|
||||
let cached_reader = PartProofReader::new(part.clone(), &[], &[], "bucket", "object", None).expect("matching descriptor");
|
||||
cached_reader.verify(0, 0, shards[0]).await.expect("cached verify");
|
||||
invalidate_verified_stripe_records(part.generation);
|
||||
assert!(get_verified_stripe_record(&part, 0).is_none());
|
||||
@@ -1174,6 +1244,7 @@ mod tests {
|
||||
sources: Vec::new(),
|
||||
volume: "bucket".to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
});
|
||||
|
||||
@@ -1194,6 +1265,128 @@ mod tests {
|
||||
assert!(err.to_string().contains("shard integrity verification failed"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proof_stream_reuses_bounded_windows_and_recovers_from_damaged_replicas() {
|
||||
use crate::set_disk::disk_call_counters;
|
||||
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
|
||||
let disks = store.pools[0].disk_set[0].get_local_disks().await;
|
||||
let volume = "proof-window";
|
||||
let path = "part.integrity";
|
||||
let mut builder = IntegrityBuilder::new(IntegrityLayout::new(1, 1, 8, false).expect("layout"), 1).expect("builder");
|
||||
for _ in 0..20 {
|
||||
builder.push([b"abcdefgh".as_slice(); 2].into_iter()).await.expect("stripe");
|
||||
}
|
||||
let prepared = builder.finish(160).await.expect("index");
|
||||
let bytes = prepared.inline_bytes().expect("small proof index");
|
||||
let part = prepared.part;
|
||||
let sources: Vec<_> = disks.into_iter().flatten().map(|disk| (disk, path.to_owned())).collect();
|
||||
assert_eq!(sources.len(), 2);
|
||||
for (disk, path) in &sources {
|
||||
disk.make_volume(volume).await.expect("create volume");
|
||||
disk.write_all(volume, path, bytes.clone())
|
||||
.await
|
||||
.expect("write full proof index");
|
||||
}
|
||||
|
||||
let proof = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: vec![sources[0].clone()],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: Some(19),
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let calls = disk_call_counters::observe(path);
|
||||
for stripe in 2..19 {
|
||||
proof.verify(stripe, 0, b"abcdefgh").await.expect("verify requested stripe");
|
||||
}
|
||||
assert!(proof.cached.lock().await.window.is_none(), "the range ends inside the part");
|
||||
assert!(proof.record(19).await.is_err(), "the request must not fetch a stripe outside its range");
|
||||
assert_eq!(calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN), 2, "17 stripes need two streams");
|
||||
drop(calls);
|
||||
|
||||
let (mut stalled_writer, stalled_reader) = tokio::io::duplex(64);
|
||||
let hedged = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: sources.clone(),
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache {
|
||||
window: Some(ProofWindow {
|
||||
next: 2,
|
||||
end: 18,
|
||||
reader: Box::new(stalled_reader),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
hedged
|
||||
.verify(2, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("a healthy replica must replace a stalled continuation");
|
||||
assert_eq!(hedged.cached.lock().await.preferred, 1);
|
||||
assert_eq!(
|
||||
stalled_writer
|
||||
.write_u8(0)
|
||||
.await
|
||||
.expect_err("the losing continuation must be dropped")
|
||||
.kind(),
|
||||
io::ErrorKind::BrokenPipe
|
||||
);
|
||||
|
||||
let missing_path = "missing-part.integrity";
|
||||
let missing = PartProofReader {
|
||||
part: part.clone(),
|
||||
sources: vec![(sources[0].0.clone(), missing_path.to_owned())],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
let calls = disk_call_counters::observe(missing_path);
|
||||
assert!(missing.record(2).await.is_err(), "a missing sidecar cannot authenticate the record");
|
||||
assert_eq!(
|
||||
calls.total(disk_call_counters::KIND_PROOF_STREAM_OPEN),
|
||||
1,
|
||||
"a shorter read cannot open a missing file"
|
||||
);
|
||||
drop(calls);
|
||||
|
||||
let short_end = part.record_offset(4).expect("end of shortened index");
|
||||
let corrupt_offset = part.record_offset(3).expect("record offset");
|
||||
let mut damaged = bytes[..short_end].to_vec();
|
||||
damaged[corrupt_offset] ^= 1;
|
||||
sources[0]
|
||||
.0
|
||||
.write_all(volume, path, Bytes::from(damaged))
|
||||
.await
|
||||
.expect("damage preferred replica");
|
||||
let degraded = PartProofReader {
|
||||
part,
|
||||
sources: vec![sources[0].clone()],
|
||||
volume: volume.to_owned(),
|
||||
inline: None,
|
||||
read_end: None,
|
||||
cached: Mutex::new(ProofCache::default()),
|
||||
};
|
||||
degraded
|
||||
.verify(2, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("intact record in a truncated replica");
|
||||
{
|
||||
let cached = degraded.cached.lock().await;
|
||||
assert_eq!(cached.preferred, 0, "a truncated suffix must not reject a valid requested record");
|
||||
assert!(cached.window.is_none());
|
||||
}
|
||||
let degraded = PartProofReader { sources, ..degraded };
|
||||
degraded
|
||||
.verify(3, 0, b"abcdefgh")
|
||||
.await
|
||||
.expect("recover the corrupt record from another replica");
|
||||
assert_eq!(degraded.cached.lock().await.preferred, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spilled_index_write_verify_and_restore_proof_replicas_round_trip() {
|
||||
let (_dirs, store) = crate::services::rebalance::test_store_with_persisted_rebalance_meta(Default::default()).await;
|
||||
|
||||
@@ -26,6 +26,10 @@ use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use tokio::sync::{Mutex, Notify, OwnedRwLockReadGuard};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Internal metadata suffix preserving an object's initial logical body revision
|
||||
/// across pool data movement (`rebalance` / `decommission`).
|
||||
pub const LOGICAL_BODY_REVISION_SUFFIX: &str = "logical-body-revision-v1";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NamespaceLockFence {
|
||||
signals: Arc<Vec<Arc<rustfs_lock::distributed_lock::LockLostSignal>>>,
|
||||
@@ -1643,6 +1647,14 @@ impl ObjectOptions {
|
||||
self.version_id.is_some() || !self.versioned || self.version_suspended
|
||||
}
|
||||
|
||||
/// Version slot replaced by a PUT. A fresh named version has no predecessor.
|
||||
pub(crate) fn replaced_version_id(&self) -> crate::error::Result<Option<Uuid>> {
|
||||
if let Some(id) = self.version_id.as_deref() {
|
||||
return Ok(Some(Uuid::parse_str(id)?));
|
||||
}
|
||||
Ok(self.overwrites_existing_version().then(Uuid::nil))
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn add_namespace_lock_lost_signal(&mut self, signal: Arc<rustfs_lock::distributed_lock::LockLostSignal>) {
|
||||
#[cfg(test)]
|
||||
@@ -1745,6 +1757,10 @@ impl ObjectOptions {
|
||||
.unwrap_or(ReplicationStatusType::Empty)
|
||||
}
|
||||
|
||||
pub(crate) fn is_inbound_multipart_replica(&self) -> bool {
|
||||
self.replication_request || self.delete_marker_replication_status() == ReplicationStatusType::Replica
|
||||
}
|
||||
|
||||
pub fn put_replication_state(&self) -> ReplicationState {
|
||||
if self
|
||||
.delete_replication
|
||||
@@ -1883,6 +1899,8 @@ pub struct ObjectInfo {
|
||||
/// published by the same upload. Callers must not repeat quota, replication,
|
||||
/// lifecycle, or object-created side effects for that response.
|
||||
pub multipart_completion_replayed: bool,
|
||||
/// Logical usage observed under the object locks for this PUT.
|
||||
pub put_usage: Option<crate::data_usage::PutUsageReceipt>,
|
||||
/// Previous current version's size observed during `rename_data` commit.
|
||||
pub backfilled_old_current_size: Option<crate::disk::OldCurrentSize>,
|
||||
/// Persisted EC block size of a local version, projected from its erasure
|
||||
@@ -1933,6 +1951,7 @@ impl Default for ObjectInfo {
|
||||
replication_decision: String::new(),
|
||||
checksum: None,
|
||||
multipart_completion_replayed: false,
|
||||
put_usage: None,
|
||||
backfilled_old_current_size: None,
|
||||
ec_block_size: None,
|
||||
}
|
||||
@@ -1978,6 +1997,7 @@ impl Clone for ObjectInfo {
|
||||
replication_decision: self.replication_decision.clone(),
|
||||
checksum: self.checksum.clone(),
|
||||
multipart_completion_replayed: self.multipart_completion_replayed,
|
||||
put_usage: self.put_usage,
|
||||
backfilled_old_current_size: self.backfilled_old_current_size,
|
||||
ec_block_size: self.ec_block_size,
|
||||
expires: self.expires,
|
||||
@@ -2298,6 +2318,16 @@ impl ObjectInfo {
|
||||
.unwrap_or_else(|_| self.size.max(0))
|
||||
}
|
||||
|
||||
/// Logical body revision preserved across pool data movement (`rebalance` /
|
||||
/// `decommission`), falling back to physical `data_dir` when no internal
|
||||
/// logical revision marker is present.
|
||||
pub fn logical_body_revision(&self) -> Option<Uuid> {
|
||||
rustfs_utils::http::get_consistent_str(&self.user_defined, LOGICAL_BODY_REVISION_SUFFIX)
|
||||
.and_then(|value| Uuid::parse_str(value.trim()).ok())
|
||||
.filter(|id| !id.is_nil())
|
||||
.or_else(|| self.data_dir.filter(|id| !id.is_nil()))
|
||||
}
|
||||
|
||||
pub fn from_file_info(fi: &FileInfo, bucket: &str, object: &str, versioned: bool) -> ObjectInfo {
|
||||
let mut version_id = fi.version_id;
|
||||
|
||||
|
||||
@@ -22,22 +22,27 @@ use std::time::Duration;
|
||||
///
|
||||
/// Callers cannot fabricate a guard without acquiring its namespace lock.
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// ```compile_fail,E0451
|
||||
/// use rustfs_ecstore::api::object::WriteCommitGuard;
|
||||
/// use std::sync::Arc;
|
||||
///
|
||||
/// let guard = WriteCommitGuard {
|
||||
/// bucket: "bucket".into(),
|
||||
/// object: "object".into(),
|
||||
/// guards: Arc::new(Vec::new()),
|
||||
/// };
|
||||
/// fn fabricate(guard: Arc<rustfs_lock::NamespaceLockGuard>) -> WriteCommitGuard {
|
||||
/// WriteCommitGuard { bucket: "bucket".into(), object: "object".into(), guard, backend: None }
|
||||
/// }
|
||||
/// ```
|
||||
#[doc(hidden)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WriteCommitGuard {
|
||||
bucket: Arc<str>,
|
||||
object: Arc<str>,
|
||||
guards: Arc<Vec<Arc<rustfs_lock::NamespaceLockGuard>>>,
|
||||
guard: Arc<rustfs_lock::NamespaceLockGuard>,
|
||||
backend: Option<BorrowedWriteBackend>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum BorrowedWriteBackend {
|
||||
Object(rustfs_lock::namespace::WriteLockBackend),
|
||||
Version,
|
||||
}
|
||||
|
||||
impl WriteCommitGuard {
|
||||
@@ -46,27 +51,42 @@ impl WriteCommitGuard {
|
||||
lock: &rustfs_lock::NamespaceLockWrapper,
|
||||
timeout: Duration,
|
||||
) -> std::result::Result<Self, rustfs_lock::LockError> {
|
||||
let guard = Arc::new(lock.get_write_lock(timeout).await?);
|
||||
let guard = Arc::new(lock.get_write_lock_extending(timeout, &[]).await?);
|
||||
let key = lock.resource();
|
||||
Ok(Self::from_guard(guard, &key.bucket, &key.object))
|
||||
let mut owner = Self::from_guard(guard, &key.bucket, &key.object);
|
||||
owner.backend = Some(if key.version.is_none() {
|
||||
BorrowedWriteBackend::Object(lock.write_backend())
|
||||
} else {
|
||||
BorrowedWriteBackend::Version
|
||||
});
|
||||
Ok(owner)
|
||||
}
|
||||
|
||||
pub(crate) fn from_guard(guard: Arc<rustfs_lock::NamespaceLockGuard>, bucket: &str, object: &str) -> Self {
|
||||
Self {
|
||||
bucket: bucket.into(),
|
||||
object: object_name_disk_identity(object).as_ref().into(),
|
||||
guards: Arc::new(vec![guard]),
|
||||
guard,
|
||||
backend: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the loss signal of the namespace owner retained by acquisition.
|
||||
#[doc(hidden)]
|
||||
pub fn lock_lost_signal(&self) -> Option<Arc<rustfs_lock::distributed_lock::LockLostSignal>> {
|
||||
self.guards.first().and_then(|guard| guard.lock_lost_signal())
|
||||
self.guard.lock_lost_signal()
|
||||
}
|
||||
|
||||
pub fn is_lock_lost(&self) -> bool {
|
||||
self.guards.iter().any(|guard| guard.is_lock_lost() || guard.is_released())
|
||||
self.guard.is_lock_lost() || self.guard.is_released()
|
||||
}
|
||||
|
||||
fn owners_for(guards: &[Self], bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
guards
|
||||
.iter()
|
||||
.filter(|guard| guard.matches(bucket, object))
|
||||
.map(|guard| Arc::clone(&guard.guard))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Namespace locks key the disk identity of the name (see `new_ns_lock`),
|
||||
@@ -150,6 +170,13 @@ impl WriteCommitContext {
|
||||
matches!(self, Self::Borrowed(_))
|
||||
}
|
||||
|
||||
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
match self {
|
||||
Self::Borrowed(guards) => WriteCommitGuard::owners_for(guards, bucket, object),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_lock_lost(&self) -> bool {
|
||||
matches!(self, Self::Borrowed(guards) if guards.iter().any(WriteCommitGuard::is_lock_lost))
|
||||
}
|
||||
@@ -160,24 +187,62 @@ impl WriteCommitContext {
|
||||
}
|
||||
|
||||
impl ObjectOptions {
|
||||
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
|
||||
for owner in guard.guards.iter() {
|
||||
self.add_namespace_lock_guard(owner);
|
||||
pub(crate) fn borrowed_write_guards(&self, bucket: &str, object: &str) -> Vec<Arc<rustfs_lock::NamespaceLockGuard>> {
|
||||
match self.write_lock_context.as_ref().map(|context| &context.mode) {
|
||||
Some(WriteLockMode::Borrowed(guards)) => WriteCommitGuard::owners_for(guards, bucket, object),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn borrows_fixed_write_lock(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
lock: &rustfs_lock::NamespaceLockWrapper,
|
||||
) -> Result<bool> {
|
||||
let Some(WriteLockContext {
|
||||
mode: WriteLockMode::Borrowed(guards),
|
||||
}) = self.write_lock_context.as_ref()
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let mut borrowed = false;
|
||||
for guard in guards.iter().filter(|guard| guard.matches(bucket, object)) {
|
||||
if let Some(backend) = &guard.backend {
|
||||
if !matches!(backend, BorrowedWriteBackend::Object(held) if held.matches(lock)) {
|
||||
return Err(Error::InvalidArgument(
|
||||
bucket.to_owned(),
|
||||
object.to_owned(),
|
||||
"borrowed write guard does not own the fixed object namespace".to_owned(),
|
||||
));
|
||||
}
|
||||
if guard.is_lock_lost() {
|
||||
return Err(Error::NamespaceLockQuorumUnavailable {
|
||||
mode: "put_object_outer_lock",
|
||||
bucket: bucket.to_owned(),
|
||||
object: object.to_owned(),
|
||||
required: 1,
|
||||
achieved: 0,
|
||||
});
|
||||
}
|
||||
borrowed = true;
|
||||
}
|
||||
}
|
||||
Ok(borrowed)
|
||||
}
|
||||
|
||||
pub fn add_write_commit_guard(&mut self, guard: &WriteCommitGuard) {
|
||||
self.add_namespace_lock_guard(&guard.guard);
|
||||
let mut guards = match self.write_lock_context.as_ref() {
|
||||
Some(WriteLockContext {
|
||||
mode: WriteLockMode::Borrowed(existing),
|
||||
}) => existing.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if let Some(existing) = guards.iter_mut().find(|held| held.matches(&guard.bucket, &guard.object)) {
|
||||
let owners = Arc::make_mut(&mut existing.guards);
|
||||
for owner in guard.guards.iter() {
|
||||
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
|
||||
owners.push(Arc::clone(owner));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if !guards
|
||||
.iter()
|
||||
.any(|held| Arc::ptr_eq(&held.guard, &guard.guard) && held.matches(&guard.bucket, &guard.object))
|
||||
{
|
||||
guards.push(guard.clone());
|
||||
}
|
||||
self.no_lock = true;
|
||||
|
||||
@@ -207,13 +207,16 @@ impl ListReadBudget {
|
||||
}
|
||||
}
|
||||
|
||||
fn weight(&self, fanout: usize) -> usize {
|
||||
// Admit a full walk even when its fanout exceeds the configured budget.
|
||||
fanout.max(1).min(self.capacity)
|
||||
}
|
||||
|
||||
async fn acquire(&self, fanout: usize) -> Result<Option<Arc<OwnedSemaphorePermit>>, tokio::sync::AcquireError> {
|
||||
if self.capacity == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
// A single walk must remain admissible even when the topology exceeds
|
||||
// the configured budget. Tokio accepts at most u32::MAX in one grant.
|
||||
let weight = u32::try_from(fanout.max(1).min(self.capacity)).unwrap_or(u32::MAX);
|
||||
let weight = u32::try_from(self.weight(fanout)).unwrap_or(u32::MAX);
|
||||
self.permits
|
||||
.clone()
|
||||
.acquire_many_owned(weight)
|
||||
@@ -420,6 +423,8 @@ pub struct InstanceContext {
|
||||
/// caller (for example, an S3 client disconnect) cannot stop them between
|
||||
/// their on-disk steps. Shutdown waits for them after the HTTP drain.
|
||||
detached_mutations: TaskTracker,
|
||||
/// Limits v1 settlements that may outlive a successful object response.
|
||||
pub(crate) v1_quota_settlement_slots: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl InstanceContext {
|
||||
@@ -491,6 +496,12 @@ impl InstanceContext {
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn list_read_budget_has_capacity(&self, fanout: usize) -> Option<bool> {
|
||||
self.list_read_budget
|
||||
.get()
|
||||
.map(|budget| budget.permits.available_permits() >= budget.weight(fanout))
|
||||
}
|
||||
|
||||
/// Build a context bound to a specific lock manager.
|
||||
///
|
||||
/// [`bootstrap_ctx`] uses this to alias the process-global lock manager so
|
||||
@@ -553,6 +564,7 @@ impl InstanceContext {
|
||||
transition_transaction_recovery_stores: std::sync::Mutex::new(HashSet::new()),
|
||||
tier_delete_journal_recovery_wakeup: tokio::sync::Notify::new(),
|
||||
detached_mutations: TaskTracker::new(),
|
||||
v1_quota_settlement_slots: Arc::new(Semaphore::new(64)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -576,6 +588,14 @@ impl InstanceContext {
|
||||
/// the mutation, together with the locks and guards it owns, never stops
|
||||
/// between two of its on-disk steps because its caller went away.
|
||||
pub(crate) async fn run_detached_mutation<F>(&self, mutation: F) -> Result<F::Output, tokio::task::JoinError>
|
||||
where
|
||||
F: std::future::Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
{
|
||||
self.spawn_detached_mutation(mutation).await
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_detached_mutation<F>(&self, mutation: F) -> tokio::task::JoinHandle<F::Output>
|
||||
where
|
||||
F: std::future::Future + Send + 'static,
|
||||
F::Output: Send + 'static,
|
||||
@@ -590,7 +610,7 @@ impl InstanceContext {
|
||||
let context = rustfs_io_metrics::s3_http_metrics::current_s3_http_operation_context();
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
let mutation = rustfs_io_metrics::s3_http_metrics::with_s3_http_operation_context(context, mutation);
|
||||
self.detached_mutations.spawn(mutation.in_current_span()).await
|
||||
self.detached_mutations.spawn(mutation.in_current_span())
|
||||
}
|
||||
|
||||
/// Wait up to `timeout` for every detached mutation to finish. Returns
|
||||
@@ -1575,8 +1595,16 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_read_budget_zero_preserves_unbounded_configuration() {
|
||||
let budget = ListReadBudget::new(0);
|
||||
assert!(budget.acquire(usize::MAX).await.expect("disabled budget").is_none());
|
||||
let ctx = InstanceContext::new();
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(1), None);
|
||||
ctx.list_read_budget.set(ListReadBudget::new(0)).expect("fresh context");
|
||||
assert!(
|
||||
ctx.acquire_list_read_budget(usize::MAX)
|
||||
.await
|
||||
.expect("disabled budget")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(usize::MAX), Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1611,6 +1639,8 @@ mod tests {
|
||||
let other = InstanceContext::new();
|
||||
other.list_read_budget.set(ListReadBudget::new(4)).expect("fresh context");
|
||||
let held = first.acquire_list_read_budget(4).await.expect("first context");
|
||||
assert_eq!(same.list_read_budget_has_capacity(4), Some(false));
|
||||
assert_eq!(other.list_read_budget_has_capacity(4), Some(true));
|
||||
let mut waiter = std::pin::pin!(same.acquire_list_read_budget(1));
|
||||
assert!(futures::poll!(&mut waiter).is_pending());
|
||||
assert!(
|
||||
@@ -1622,6 +1652,18 @@ mod tests {
|
||||
);
|
||||
drop(held);
|
||||
assert!(waiter.await.expect("shared context resumed").is_some());
|
||||
assert_eq!(same.list_read_budget_has_capacity(4), Some(true));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_read_budget_reports_capacity_for_the_requested_fanout() {
|
||||
let ctx = InstanceContext::new();
|
||||
ctx.list_read_budget.set(ListReadBudget::new(64)).expect("fresh context");
|
||||
let held = ctx.acquire_list_read_budget(48).await.expect("first walk");
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(16), Some(true));
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(false));
|
||||
drop(held);
|
||||
assert_eq!(ctx.list_read_budget_has_capacity(48), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -833,11 +833,13 @@ impl BitrotReaderSetup {
|
||||
disks: &[Option<DiskStore>],
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
first_stripe: usize,
|
||||
stripes: std::ops::Range<usize>,
|
||||
) -> std::io::Result<()> {
|
||||
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
|
||||
let Some(expected) = expected else { return Ok(()) };
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
|
||||
let first_stripe = stripes.start;
|
||||
let end_stripe = u32::try_from(stripes.end).map_err(std::io::Error::other)?;
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(end_stripe))?;
|
||||
for (index, reader) in self.readers.iter_mut().enumerate() {
|
||||
if let Some(reader) = reader {
|
||||
let advanced = self.deferred_stripe_handles[index]
|
||||
@@ -7971,7 +7973,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
pub(crate) fn evaluate_write_precondition(
|
||||
oi: Result<ObjectInfo>,
|
||||
oi: Result<impl std::borrow::Borrow<ObjectInfo>>,
|
||||
http_preconditions: &HTTPPreconditions,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
@@ -7979,6 +7981,7 @@ impl SetDisks {
|
||||
) -> Option<StorageError> {
|
||||
match oi {
|
||||
Ok(oi) => {
|
||||
let oi = oi.borrow();
|
||||
// Ordinary writes may proceed past a top-level delete marker;
|
||||
// data movement and guarded internal writes must preserve it.
|
||||
if oi.delete_marker {
|
||||
@@ -7992,8 +7995,8 @@ impl SetDisks {
|
||||
object,
|
||||
);
|
||||
}
|
||||
if should_prevent_write(&oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
|
||||
&& !crate::data_movement::can_replace_stale_data_movement_target(&oi, opts)
|
||||
if should_prevent_write(oi, http_preconditions.if_none_match_value(), http_preconditions.if_match_value())
|
||||
&& !crate::data_movement::can_replace_stale_data_movement_target(oi, opts)
|
||||
{
|
||||
return Some(StorageError::PreconditionFailed);
|
||||
}
|
||||
@@ -8380,6 +8383,7 @@ pub(crate) mod disk_call_counters {
|
||||
pub const KIND_METADATA_SLOWTAIL_FAULT: &str = "metadata_slowtail_fault";
|
||||
pub const KIND_INLINE_SHARD_OPEN: &str = "inline_shard_open";
|
||||
pub const KIND_DISK_SHARD_OPEN: &str = "disk_shard_open";
|
||||
pub const KIND_PROOF_STREAM_OPEN: &str = "proof_stream_open";
|
||||
/// Body verification, direct shard assembly, and erasure decoder entry points.
|
||||
pub const KIND_BODY_DECODE: &str = "body_decode";
|
||||
|
||||
@@ -8453,6 +8457,10 @@ pub(crate) mod disk_call_counters {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_proof_stream_open(path: &str, replica: usize) {
|
||||
record(path, KIND_PROOF_STREAM_OPEN, replica);
|
||||
}
|
||||
|
||||
/// RAII scope that observes call counts for a single `object`. Counts recorded
|
||||
/// while the scope is alive — including those recorded inside spawned tasks —
|
||||
/// are queryable; the scope clears its own counts on drop.
|
||||
|
||||
@@ -46,7 +46,7 @@ struct FileInfoQuorumKey {
|
||||
|
||||
impl SetDisks {
|
||||
/// Read one key's complete version stack without enumerating its parent.
|
||||
pub(crate) async fn read_object_versions_for_lifecycle(
|
||||
pub(crate) async fn read_object_version_history(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
|
||||
@@ -138,6 +138,7 @@ use rustfs_io_metrics::{
|
||||
use rustfs_lock::LockClient;
|
||||
#[cfg(test)]
|
||||
use rustfs_lock::LockManager;
|
||||
use rustfs_lock::distributed_lock::same_write_voters;
|
||||
use rustfs_lock::fast_lock::types::LockResult;
|
||||
use rustfs_lock::{FastLockGuard, NamespaceLock, NamespaceLockGuard, NamespaceLockWrapper, ObjectKey};
|
||||
use rustfs_madmin::heal_commands::{HealDriveInfo, HealResultItem, Infos};
|
||||
@@ -507,9 +508,12 @@ fn release_materialized_read_lock(bucket: &str, object: &str, read_lock_guard: O
|
||||
drop(read_lock_guard);
|
||||
}
|
||||
|
||||
const MULTIPART_GENERATED_VERSION_SUFFIX: &str = "multipart-generated-version-id";
|
||||
|
||||
pub(crate) fn strip_internal_multipart_metadata(metadata: &mut HashMap<String, String>) {
|
||||
metadata.remove(RUSTFS_MULTIPART_BUCKET_KEY);
|
||||
metadata.remove(RUSTFS_MULTIPART_OBJECT_KEY);
|
||||
rustfs_utils::http::metadata_compat::remove_str(metadata, MULTIPART_GENERATED_VERSION_SUFFIX);
|
||||
rustfs_utils::http::metadata_compat::remove_str(metadata, SUFFIX_BUCKET_INCARNATION_ID);
|
||||
}
|
||||
|
||||
@@ -4955,17 +4959,6 @@ pub(crate) fn same_distributed_lock_domain(left: &[Arc<dyn LockClient>], right:
|
||||
.all(|right_client| left.iter().any(|left_client| Arc::ptr_eq(left_client, right_client)))
|
||||
}
|
||||
|
||||
// Reusing a held writer additionally requires the same quorum, so repeated
|
||||
// clients must not give different weight to an otherwise identical domain.
|
||||
fn same_distributed_lock_quorum(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
|
||||
!left.is_empty()
|
||||
&& left.len() == right.len()
|
||||
&& left.iter().all(|client| {
|
||||
left.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
|
||||
&& right.iter().filter(|other| Arc::ptr_eq(client, other)).count() == 1
|
||||
})
|
||||
}
|
||||
|
||||
const ERASURE_CACHE_MAX_ENTRIES: usize = 32;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
@@ -5952,7 +5945,7 @@ impl SetDisks {
|
||||
(false, false) => Arc::ptr_eq(&self.local_lock_manager, &other.local_lock_manager),
|
||||
// Distributed lock clients receive the raw ObjectKey; the pool
|
||||
// namespace is not part of the key stored by their backends.
|
||||
(true, true) => same_distributed_lock_quorum(&self.lockers, &other.lockers),
|
||||
(true, true) => same_write_voters(&self.lockers, &other.lockers),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -10484,13 +10477,10 @@ mod tests {
|
||||
let a: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
let b: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
let c: Arc<dyn LockClient> = Arc::new(LocalClient::with_manager(Arc::new(rustfs_lock::GlobalLockManager::new())));
|
||||
assert!(same_distributed_lock_quorum(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
|
||||
assert!(!same_distributed_lock_quorum(&[a.clone(), b.clone()], &[a.clone(), c]));
|
||||
assert!(!same_distributed_lock_quorum(
|
||||
&[a.clone(), a.clone(), b.clone()],
|
||||
&[a.clone(), b.clone(), b]
|
||||
));
|
||||
assert!(!same_distributed_lock_quorum(&[], &[]));
|
||||
assert!(same_write_voters(&[a.clone(), b.clone()], &[b.clone(), a.clone()]));
|
||||
assert!(!same_write_voters(&[a.clone(), b.clone()], &[a.clone(), c]));
|
||||
assert!(!same_write_voters(&[a.clone(), a.clone(), b.clone()], &[a.clone(), b.clone(), b]));
|
||||
assert!(!same_write_voters(&[], &[]));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -22,7 +22,8 @@ use crate::disk::{
|
||||
};
|
||||
use crate::error::StorageError;
|
||||
use crate::set_disk::SetDisks;
|
||||
use futures::future::join_all;
|
||||
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
|
||||
use futures::future::{join_all, try_join_all};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
@@ -599,6 +600,98 @@ fn causal_transaction_order(states: &BTreeMap<Uuid, Vec<DeleteRecoveryInspection
|
||||
}
|
||||
|
||||
impl SetDisks {
|
||||
/// With the lifecycle fence held by the caller, check the exact set without
|
||||
/// repairing payloads or settling delete transactions.
|
||||
pub(crate) async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> crate::error::Result<bool> {
|
||||
let first = {
|
||||
let disks = self.disks.read().await;
|
||||
disks
|
||||
.iter()
|
||||
.flatten()
|
||||
.find(|disk| disk.is_local())
|
||||
.or_else(|| disks.iter().flatten().next())
|
||||
.cloned()
|
||||
};
|
||||
let Some(first) = first else {
|
||||
return Ok(false);
|
||||
};
|
||||
let missing = async |disk: &DiskStore| match disk
|
||||
.read_version("", bucket, object, "", &crate::disk::ReadOptions::default())
|
||||
.await
|
||||
{
|
||||
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound) => Ok(true),
|
||||
Ok(_) => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
if !missing(&first).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
// Lock order matches delete recovery and multi-pool decommission:
|
||||
// lifecycle, fixed/target raw object, decommission capacity, transaction, then inventory validation.
|
||||
let (fixed_guard, object_guard, capacity_guard) = if let Some(store) = capacity_store {
|
||||
Box::pin(async {
|
||||
let (fixed_guard, target_guard) = store.acquire_external_read_namespace(bucket, object, self).await?;
|
||||
let capacity_guard = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
crate::error::Result::Ok((Some(fixed_guard), target_guard, Some(capacity_guard)))
|
||||
})
|
||||
.await?
|
||||
} else {
|
||||
let namespace = self.new_ns_lock(bucket, object).await?;
|
||||
let object_guard = namespace.get_read_lock(crate::set_disk::get_lock_acquire_timeout()).await?;
|
||||
(None, Some(object_guard), None)
|
||||
};
|
||||
let transaction_guard = self.acquire_delete_transaction_lock(bucket, object).await?;
|
||||
let disks = self.get_disks_internal().await;
|
||||
if disks.len() != self.set_drive_count || disks.iter().any(Option::is_none) {
|
||||
return Ok(false);
|
||||
}
|
||||
// The fast rejection is a hint. Read every member under both locks
|
||||
// before accepting a candidate absence.
|
||||
if try_join_all(disks.iter().flatten().map(missing)).await?.contains(&false) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// A recoverable transaction or legacy backup can restore the object.
|
||||
// Require complete, empty discovery on every disk. No inspection or
|
||||
// settlement is needed for this read-only path.
|
||||
let budget = crate::object_api::DeleteRecoveryWorkBudget::for_disks(disks.len());
|
||||
let transactions = try_join_all(
|
||||
disks
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|disk| discover_bounded(disk, bucket, object, &budget)),
|
||||
)
|
||||
.await?;
|
||||
if transactions.iter().any(|transactions| !transactions.is_empty()) {
|
||||
return Ok(false);
|
||||
}
|
||||
// Do not hold the registry read guard across RPC or disk I/O. A
|
||||
// topology writer may have replaced a member while the probe ran.
|
||||
let current = self.disks.read().await;
|
||||
let namespace_alive = fixed_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
|
||||
&& object_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost())
|
||||
&& capacity_guard.as_ref().is_none_or(|guard| !guard.is_lock_lost());
|
||||
Ok(current.len() == disks.len()
|
||||
&& current.iter().zip(&disks).all(|(current, probed)| {
|
||||
current
|
||||
.as_ref()
|
||||
.zip(probed.as_ref())
|
||||
.is_some_and(|(current, probed)| Arc::ptr_eq(current, probed))
|
||||
})
|
||||
&& namespace_alive
|
||||
&& !transaction_guard.is_lock_lost())
|
||||
}
|
||||
|
||||
/// Publication follows the ordinary metadata quorum. Once a publication is
|
||||
/// attempted, response loss must never trigger blind rollback.
|
||||
pub(in crate::set_disk) async fn publish_delete_commit(
|
||||
@@ -2632,6 +2725,9 @@ mod tests {
|
||||
for shape in ["live-backup", "foreign", "partial-history", "damaged-data", "causal-cycle"] {
|
||||
let bucket = "recover-marker-source-guards";
|
||||
let (dirs, store) = isolated_store_over_temp_disks().await;
|
||||
store.pools[0].stop_endpoint_monitor_for_test().await;
|
||||
store.background_cancel_token().expect("fixture background token").cancel();
|
||||
tokio::task::yield_now().await;
|
||||
init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
store
|
||||
.make_bucket(
|
||||
@@ -2652,7 +2748,7 @@ mod tests {
|
||||
set.disks.write().await[3] = None;
|
||||
let payload = vec![72; 1024 * 1024];
|
||||
let source = put(&store, bucket, &payload, true).await.unwrap();
|
||||
store
|
||||
let marker = store
|
||||
.delete_object(
|
||||
bucket,
|
||||
"object",
|
||||
@@ -2663,6 +2759,17 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.expect("publish marker while one member lacks the source version");
|
||||
let marker_id = marker.version_id.expect("the delete marker has a version ID");
|
||||
for absent in [source, marker_id] {
|
||||
assert_eq!(
|
||||
disks[3]
|
||||
.read_version("", bucket, "object", &absent.to_string(), &ReadOptions::default())
|
||||
.await
|
||||
.expect_err("the disconnected member must lack the source and marker"),
|
||||
DiskError::FileVersionNotFound,
|
||||
"{shape}: unexpected result reading version {absent}"
|
||||
);
|
||||
}
|
||||
set.disks.write().await[3] = Some(disks[3].clone());
|
||||
let mut first_info = disks[3]
|
||||
.read_version("", bucket, "object", &first.to_string(), &ReadOptions::default())
|
||||
@@ -2695,7 +2802,14 @@ mod tests {
|
||||
DeleteOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
.expect("remove the oldest member of the returning disk's history");
|
||||
assert_eq!(
|
||||
disks[3]
|
||||
.read_version("", bucket, "object", &oldest.to_string(), &ReadOptions::default())
|
||||
.await
|
||||
.expect_err("the returning disk's history must be incomplete before heal"),
|
||||
DiskError::FileVersionNotFound
|
||||
);
|
||||
}
|
||||
"damaged-data" => {
|
||||
// Three metadata sources meet write quorum, but corrupting
|
||||
|
||||
@@ -31,11 +31,37 @@ use std::sync::Arc;
|
||||
#[path = "heal_lock_wait_tests.rs"]
|
||||
mod heal_lock_wait_tests;
|
||||
|
||||
struct ExternalHealCommit {
|
||||
namespace: Option<crate::store::ObjectLockDiagGuard>,
|
||||
capacity: rustfs_lock::NamespaceLockGuard,
|
||||
}
|
||||
|
||||
impl ExternalHealCommit {
|
||||
fn is_lock_lost(&self) -> bool {
|
||||
self.capacity.is_lock_lost() || self.namespace.as_ref().is_some_and(|owner| owner.is_lock_lost())
|
||||
}
|
||||
}
|
||||
|
||||
enum ReadRepairWriteGuard {
|
||||
Set(Box<ObjectLockDiagGuard>),
|
||||
External(Arc<ExternalHealCommit>),
|
||||
}
|
||||
|
||||
impl ReadRepairWriteGuard {
|
||||
fn is_lock_lost(&self) -> bool {
|
||||
match self {
|
||||
Self::Set(guard) => guard.is_lock_lost(),
|
||||
Self::External(guard) => guard.is_lock_lost(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct ExplicitVersionHeal<'a> {
|
||||
opts: &'a HealOpts,
|
||||
allow_regeneration: bool,
|
||||
preserve_unrepairable: bool,
|
||||
capacity_store: Option<&'a crate::store::ECStore>,
|
||||
commit_fence: Option<&'a (dyn Fn() -> bool + Sync)>,
|
||||
namespace_owner: Option<&'a Arc<dyn Send + Sync>>,
|
||||
retirement: Option<&'a MarkerRetirementContext<'a>>,
|
||||
@@ -938,6 +964,7 @@ impl SetDisks {
|
||||
opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: None,
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -1023,6 +1050,29 @@ impl SetDisks {
|
||||
.with_attempt(attempt))
|
||||
}
|
||||
|
||||
async fn admit_external_heal_commit(
|
||||
&self,
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
no_lock: bool,
|
||||
) -> Result<Arc<ExternalHealCommit>> {
|
||||
let namespace = if no_lock {
|
||||
None
|
||||
} else {
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_target_lock_attempted();
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
};
|
||||
let capacity = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
Ok(Arc::new(ExternalHealCommit { namespace, capacity }))
|
||||
}
|
||||
|
||||
async fn acquire_revalidated_read_repair_commit_lock(
|
||||
&self,
|
||||
disks: &[Option<DiskStore>],
|
||||
@@ -1030,14 +1080,24 @@ impl SetDisks {
|
||||
object: &str,
|
||||
version_id: &str,
|
||||
expected_fingerprint: ReadRepairCommitFingerprint,
|
||||
) -> disk::error::Result<Option<ObjectLockDiagGuard>> {
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> disk::error::Result<Option<ReadRepairWriteGuard>> {
|
||||
#[cfg(test)]
|
||||
pause_read_repair(bucket, object, ReadRepairPausePhase::Commit).await;
|
||||
|
||||
let write_lock_wait_start = std::time::Instant::now();
|
||||
let guard = self
|
||||
.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
|
||||
.await?;
|
||||
let guard = if let Some(store) = capacity_store {
|
||||
ReadRepairWriteGuard::External(
|
||||
self.admit_external_heal_commit(store, bucket, object, false)
|
||||
.await
|
||||
.map_err(|error| error.narrow_to_disk().unwrap_or_else(DiskError::other))?,
|
||||
)
|
||||
} else {
|
||||
ReadRepairWriteGuard::Set(Box::new(
|
||||
self.acquire_heal_object_lock(bucket, object, version_id, HealObjectLockKind::Write, "read_repair_commit")
|
||||
.await?,
|
||||
))
|
||||
};
|
||||
let write_lock_wait_ms = u64::try_from(write_lock_wait_start.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||
|
||||
let revalidation_start = std::time::Instant::now();
|
||||
@@ -1088,6 +1148,7 @@ impl SetDisks {
|
||||
opts,
|
||||
allow_regeneration: allow_explicit_version_regen,
|
||||
preserve_unrepairable,
|
||||
capacity_store,
|
||||
commit_fence,
|
||||
namespace_owner,
|
||||
retirement,
|
||||
@@ -1813,7 +1874,14 @@ impl SetDisks {
|
||||
.integrity
|
||||
.as_ref()
|
||||
.map(|part| {
|
||||
PartProofReader::new(part.clone(), &parts_metadata, &latest_disks, bucket, object)
|
||||
PartProofReader::new(
|
||||
part.clone(),
|
||||
&parts_metadata,
|
||||
&latest_disks,
|
||||
bucket,
|
||||
object,
|
||||
None,
|
||||
)
|
||||
})
|
||||
.transpose()?;
|
||||
// Cover the complete encoded shard, including a logical
|
||||
@@ -2060,6 +2128,7 @@ impl SetDisks {
|
||||
object,
|
||||
version_id,
|
||||
expected_fingerprint,
|
||||
capacity_store,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -3730,6 +3799,7 @@ impl SetDisks {
|
||||
opts: &opts,
|
||||
allow_regeneration: false,
|
||||
preserve_unrepairable: true,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(can_commit),
|
||||
namespace_owner,
|
||||
retirement: None,
|
||||
@@ -3767,6 +3837,21 @@ impl SetDisks {
|
||||
opts: &HealOpts,
|
||||
absence: &mut Option<HealedObjectAbsence>,
|
||||
proof: AbsenceProofRequest<'_>,
|
||||
) -> Result<(HealResultItem, Option<Error>)> {
|
||||
self.heal_object_for_store(bucket, object, version_id, opts, absence, proof, None)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn heal_object_for_store(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
version_id: &str,
|
||||
opts: &HealOpts,
|
||||
absence: &mut Option<HealedObjectAbsence>,
|
||||
proof: AbsenceProofRequest<'_>,
|
||||
capacity_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<(HealResultItem, Option<Error>)> {
|
||||
*absence = None;
|
||||
if opts.read_repair && !opts.no_lock && !opts.dry_run && !opts.remove && !has_suffix(object, SLASH_SEPARATOR) {
|
||||
@@ -3775,6 +3860,15 @@ impl SetDisks {
|
||||
// peer cannot hold an exclusive write lock across read-repair timeouts
|
||||
// and stall foreground bucket reads), without performing destructive
|
||||
// cleanup or producing an authoritative absence proof.
|
||||
if let Some(store) = capacity_store {
|
||||
let probe = store
|
||||
.acquire_external_decommission_capacity_fence(
|
||||
&[self.pool_index],
|
||||
crate::core::pools::DecommissionCapacityAdmission::Heal,
|
||||
)
|
||||
.await?;
|
||||
drop(probe);
|
||||
}
|
||||
let can_commit = || proof.retirement.is_none_or(|context| !context.lifecycle_guard.is_lock_lost());
|
||||
let mut read_opts = *opts;
|
||||
loop {
|
||||
@@ -3787,6 +3881,7 @@ impl SetDisks {
|
||||
opts: &read_opts,
|
||||
allow_regeneration: false,
|
||||
preserve_unrepairable: true,
|
||||
capacity_store,
|
||||
commit_fence: Some(&can_commit),
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -3806,7 +3901,22 @@ impl SetDisks {
|
||||
return Ok((result, error.map(Into::into)));
|
||||
}
|
||||
}
|
||||
let _write_lock_guard = if !opts.no_lock {
|
||||
let external = match capacity_store {
|
||||
Some(store) => {
|
||||
let guard = self.admit_external_heal_commit(store, bucket, object, opts.no_lock).await?;
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_operation_started(store.id);
|
||||
Some(guard)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let _write_lock_guard = if let Some(external) = &external {
|
||||
external
|
||||
.namespace
|
||||
.as_ref()
|
||||
.and_then(|guard| guard.target_write_guard())
|
||||
.cloned()
|
||||
} else if !opts.no_lock {
|
||||
let ns_lock = self
|
||||
.new_ns_lock(bucket, object)
|
||||
.await
|
||||
@@ -3842,7 +3952,8 @@ impl SetDisks {
|
||||
None
|
||||
};
|
||||
let locks_lost = || {
|
||||
_write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|
||||
external.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _write_lock_guard.as_deref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| transaction_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
};
|
||||
let mut recovery_removed_version = false;
|
||||
@@ -4004,7 +4115,7 @@ impl SetDisks {
|
||||
let commit_fence = || !locks_lost();
|
||||
let namespace_owner = _write_lock_guard
|
||||
.as_ref()
|
||||
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone())) as Arc<dyn Send + Sync>);
|
||||
.map(|guard| Arc::new((Arc::clone(guard), transaction_guard.clone(), external.clone())) as Arc<dyn Send + Sync>);
|
||||
let (result, err) = pin_object_heal_future(|| {
|
||||
self.heal_object_with_explicit_version_regen(
|
||||
bucket,
|
||||
@@ -4014,6 +4125,7 @@ impl SetDisks {
|
||||
opts: &inner_opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&commit_fence),
|
||||
namespace_owner: namespace_owner.as_ref(),
|
||||
retirement: proof.retirement,
|
||||
@@ -4038,6 +4150,7 @@ impl SetDisks {
|
||||
opts: &inner_opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&commit_fence),
|
||||
namespace_owner: namespace_owner.as_ref(),
|
||||
retirement: proof.retirement,
|
||||
@@ -6893,6 +7006,7 @@ mod heal_result_report_tests {
|
||||
opts: &opts,
|
||||
allow_regeneration: true,
|
||||
preserve_unrepairable: false,
|
||||
capacity_store: None,
|
||||
commit_fence: Some(&can_commit),
|
||||
namespace_owner: None,
|
||||
retirement: None,
|
||||
@@ -11340,6 +11454,50 @@ mod heal_result_report_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn multipool_read_repair_stages_with_shared_ownership() {
|
||||
let (_dirs, store, _peer) = crate::services::rebalance::test_two_pool_stores(None).await;
|
||||
let bucket = "multipool-shared-read-repair";
|
||||
let key = "entry";
|
||||
store.make_bucket(bucket, &MakeBucketOptions::default()).await.unwrap();
|
||||
let target = store.pools[1].get_disks_by_key(key);
|
||||
let seeded = target
|
||||
.put_object(bucket, key, &mut PutObjReader::from_vec(b"body".to_vec()), &ObjectOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let (_pause, started, release) = ReadRepairPauseScope::install_at(bucket, key, super::ReadRepairPausePhase::Data);
|
||||
let repair = tokio::spawn(async move {
|
||||
store
|
||||
.heal_object_with_proof(
|
||||
bucket,
|
||||
key,
|
||||
"",
|
||||
&HealOpts {
|
||||
pool: Some(1),
|
||||
read_repair: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
});
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), started.notified())
|
||||
.await
|
||||
.expect("enter read repair under the shared object lock");
|
||||
let visible = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(2),
|
||||
target.get_object_info(bucket, key, &ObjectOptions::default()),
|
||||
)
|
||||
.await
|
||||
.expect("read while repair is staging")
|
||||
.unwrap();
|
||||
assert_eq!(visible.etag, seeded.etag);
|
||||
release.notify_one();
|
||||
let outcome = repair.await.unwrap().unwrap();
|
||||
assert!(outcome.error.is_none());
|
||||
assert!(outcome.absence.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn read_repair_storage_entry_keeps_readers_available_during_reconstruction() {
|
||||
@@ -11954,7 +12112,12 @@ mod shard_identity_tests {
|
||||
..options.clone()
|
||||
};
|
||||
let range_start = size / 5 + 17;
|
||||
let range_end = size / 2 + 99;
|
||||
let block_size = target_meta[0].erasure.block_size;
|
||||
let range_end = if size > 2 * block_size {
|
||||
2 * block_size - 1
|
||||
} else {
|
||||
size / 2 + 99
|
||||
};
|
||||
for (range, expected_body, options) in [
|
||||
(None, expected.as_slice(), &options),
|
||||
(
|
||||
@@ -12035,6 +12198,97 @@ mod shard_identity_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_aligned_range_reads_before_truncated_suffix() {
|
||||
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(6, 0, 3).await;
|
||||
let bucket = "protected-range-boundary";
|
||||
let object = "truncated-suffix";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("create fixture bucket");
|
||||
}
|
||||
let mut expected = vec![0; 3 * 1024 * 1024 + 17];
|
||||
for (index, block) in expected.chunks_mut(4096).enumerate() {
|
||||
block.fill(u8::try_from(index % 251).expect("fixture byte"));
|
||||
}
|
||||
let options = ObjectOptions {
|
||||
shard_integrity_write_mode: Some(crate::object_api::ShardIntegrityWriteMode::Protected),
|
||||
no_lock: true,
|
||||
versioned: true,
|
||||
suppress_read_repair: true,
|
||||
..Default::default()
|
||||
};
|
||||
set.put_object(bucket, object, &mut PutObjReader::from_vec(expected.clone()), &options)
|
||||
.await
|
||||
.expect("write protected fixture");
|
||||
|
||||
let mut read_range = None;
|
||||
for (disk, dir) in disks.iter().zip(&dirs) {
|
||||
let info = disk
|
||||
.read_version("", bucket, object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("read committed version");
|
||||
let part = info.parts[0].integrity.as_ref().expect("independent commitment");
|
||||
assert!(part.stripes > 2);
|
||||
let codec = crate::erasure::coding::Erasure::try_new_with_options(
|
||||
info.erasure.data_blocks,
|
||||
info.erasure.parity_blocks,
|
||||
info.erasure.block_size,
|
||||
info.uses_legacy_checksum,
|
||||
)
|
||||
.expect("committed layout");
|
||||
let range = codec.block_size + 7..2 * codec.block_size;
|
||||
let hash_size = info.erasure.get_checksum_info(1).algorithm.size();
|
||||
let valid_len = u64::try_from(2 * (codec.shard_size() + hash_size)).expect("test shard length");
|
||||
let path = dir
|
||||
.path()
|
||||
.join(bucket)
|
||||
.join(object)
|
||||
.join(info.data_dir.expect("external part").to_string())
|
||||
.join("part.1");
|
||||
tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.await
|
||||
.expect("open committed shard")
|
||||
.set_len(valid_len)
|
||||
.await
|
||||
.expect("remove only the unrequested suffix");
|
||||
read_range = Some(range);
|
||||
}
|
||||
let range = read_range.expect("fixture has disks");
|
||||
let mut reader = set
|
||||
.get_object_reader(
|
||||
bucket,
|
||||
object,
|
||||
Some(HTTPRangeSpec {
|
||||
start: i64::try_from(range.start).expect("fixture range start"),
|
||||
end: i64::try_from(range.end - 1).expect("fixture range end"),
|
||||
is_suffix_length: false,
|
||||
}),
|
||||
Default::default(),
|
||||
&options,
|
||||
)
|
||||
.await
|
||||
.expect("aligned protected Range must ignore the truncated suffix");
|
||||
let mut body = Vec::new();
|
||||
reader
|
||||
.stream
|
||||
.read_to_end(&mut body)
|
||||
.await
|
||||
.expect("read the verified aligned range");
|
||||
assert_eq!(body, expected[range]);
|
||||
|
||||
if let Ok(mut full) = set
|
||||
.get_object_reader(bucket, object, None, Default::default(), &options)
|
||||
.await
|
||||
{
|
||||
assert!(
|
||||
full.stream.read_to_end(&mut Vec::new()).await.is_err(),
|
||||
"a full GET must reject the truncated object"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_inline_donor_repair_and_late_external_get() {
|
||||
let (dirs, disks, set) = hermetic_set_disks_for_pool_with_default_parity_isolated(4, 0, 2).await;
|
||||
|
||||
@@ -33,22 +33,22 @@ use super::super::{
|
||||
Arc, Bytes, CompletePart, Cursor, DATA_MOVEMENT_MULTIPART_PREFIX, DiskError, DiskStore, EVENT_SET_DISK_MULTIPART, Error,
|
||||
FileInfo, FileMeta, GLOBAL_MIN_PART_SIZE, HashAlgorithm, HashMap, HashReader, HashSet, HealChannelPriority, Instant,
|
||||
LOG_COMPONENT_ECSTORE, LOG_SUBSYSTEM_SET_DISK, ListMultipartsInfo, ListPartsInfo, MAX_PARTS_COUNT,
|
||||
MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA, MULTIPART_WRITE_QUORUM_WRITER_SETUP,
|
||||
MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence, OBJECT_OP_IGNORED_ERRS, ObjectInfo,
|
||||
ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo, PutObjReader, RUSTFS_META_MULTIPART_BUCKET,
|
||||
RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY, Result, SLASH_SEPARATOR,
|
||||
SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID, SUFFIX_COMPRESSION_SIZE,
|
||||
SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID, SUFFIX_RESTORE_WORKER_LOCK, SetDisks,
|
||||
SmallWritePath, StorageError, Uuid, WriteLayout, check_object_lock_for_deletion_with_state,
|
||||
classify_multipart_part_write_path, coding, complete_multipart_part_error, complete_multipart_part_error_result,
|
||||
complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug, disk, error,
|
||||
file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str, is_err_object_not_found,
|
||||
is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure, multipart_part_logical_size,
|
||||
parts_after_marker, path_join_buf, prepare_complete_multipart_parts, record_compression_total_memory,
|
||||
record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs, remove_header_map,
|
||||
replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout, restore_commit_operation_id_from_metadata,
|
||||
restore_operation_id_from_metadata, should_persist_encryption_original_size, strip_internal_multipart_metadata,
|
||||
to_object_err, warn,
|
||||
MULTIPART_GENERATED_VERSION_SUFFIX, MULTIPART_WRITE_QUORUM_RENAME_PART, MULTIPART_WRITE_QUORUM_UPLOAD_METADATA,
|
||||
MULTIPART_WRITE_QUORUM_WRITER_SETUP, MultipartInfo, MultipartUploadResult, MultipartWriteQuorumContext, NamespaceLockFence,
|
||||
OBJECT_OP_IGNORED_ERRS, ObjectInfo, ObjectLockDiagGuard, ObjectOptions, ObjectPartInfo, OffsetDateTime, PartInfo,
|
||||
PutObjReader, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET, RUSTFS_MULTIPART_BUCKET_KEY, RUSTFS_MULTIPART_OBJECT_KEY,
|
||||
Result, SLASH_SEPARATOR, SUFFIX_ACTUAL_OBJECT_SIZE_CAP, SUFFIX_ACTUAL_SIZE, SUFFIX_BUCKET_INCARNATION_ID,
|
||||
SUFFIX_COMPRESSION_SIZE, SUFFIX_REPLICATION_SSEC_CRC, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID,
|
||||
SUFFIX_RESTORE_WORKER_LOCK, SetDisks, SmallWritePath, StorageError, Uuid, WriteLayout,
|
||||
check_object_lock_for_deletion_with_state, classify_multipart_part_write_path, coding, complete_multipart_part_error,
|
||||
complete_multipart_part_error_result, complete_part_checksum, contains_key_str, create_bitrot_writer_with_orig_volume, debug,
|
||||
disk, error, file_info_is_valid_for_metadata, get_complete_multipart_md5, get_header_map, get_str, insert_str,
|
||||
is_err_object_not_found, is_err_version_not_found, is_min_allowed_part_size, log_multipart_write_quorum_failure,
|
||||
multipart_part_logical_size, parts_after_marker, path_join_buf, prepare_complete_multipart_parts,
|
||||
record_compression_total_memory, record_multipart_write_quorum_failure, reduce_read_quorum_errs, reduce_write_quorum_errs,
|
||||
remove_header_map, replication_write_may_pass_worm_gate_with_inbound_metadata, resolve_write_layout,
|
||||
restore_commit_operation_id_from_metadata, restore_operation_id_from_metadata, should_persist_encryption_original_size,
|
||||
strip_internal_multipart_metadata, to_object_err, warn,
|
||||
};
|
||||
use super::bitrot_self_verify::{
|
||||
BitrotSelfVerifyTarget, WrittenBitrotShards, drop_failed_writer_disks, verify_written_bitrot_shards,
|
||||
@@ -62,6 +62,7 @@ use super::object::{
|
||||
use crate::api::config::storageclass;
|
||||
use crate::bucket::metadata_sys::ObjectLockConfigState;
|
||||
use crate::bucket::quota::reservation;
|
||||
#[cfg(test)]
|
||||
use crate::bucket::replication::ReplicationStatusType;
|
||||
use crate::crash_inject::{self, CrashPoint};
|
||||
#[cfg(test)]
|
||||
@@ -905,6 +906,8 @@ pub enum MultipartCommitPause {
|
||||
PutPartAfterRename,
|
||||
AbortBeforeDelete,
|
||||
AbortAfterDelete,
|
||||
#[cfg(test)]
|
||||
BeforeConditionalNamespace,
|
||||
BeforeLockLost,
|
||||
BeforeQuotaRename,
|
||||
BeforeTransactionEpochVerify,
|
||||
@@ -2816,7 +2819,7 @@ impl SetDisks {
|
||||
};
|
||||
Ok(Some((file_info, object)))
|
||||
})();
|
||||
let (file_info, object) = match decoded {
|
||||
let (mut file_info, object) = match decoded {
|
||||
Ok(Some(decoded)) => decoded,
|
||||
Ok(None) => return Ok(None),
|
||||
// Deterministic damage (undecodable metadata that still
|
||||
@@ -2853,7 +2856,11 @@ impl SetDisks {
|
||||
object,
|
||||
upload_id: runtime_sources::deployment_upload_id(raw_upload_id),
|
||||
initiated,
|
||||
..Default::default()
|
||||
user_defined: file_info
|
||||
.metadata
|
||||
.remove_entry(metadata_keys::STORAGE_CLASS)
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}))
|
||||
}
|
||||
})
|
||||
@@ -4244,6 +4251,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_PART_CHECKSUMS);
|
||||
if !opts.data_movement {
|
||||
rustfs_utils::http::remove_str(&mut user_defined, rustfs_utils::http::SUFFIX_DATA_MOVEMENT_UPLOAD);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
}
|
||||
rustfs_utils::http::metadata_compat::remove_str(
|
||||
&mut user_defined,
|
||||
@@ -4293,18 +4301,19 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
}
|
||||
|
||||
fi.version_id = if let Some(vid) = &opts.version_id {
|
||||
Some(Uuid::parse_str(vid)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if opts.versioned && opts.version_id.is_none() {
|
||||
fi.version_id = Some(Uuid::new_v4());
|
||||
}
|
||||
|
||||
let data_dir = Uuid::new_v4();
|
||||
fi.data_dir = Some(data_dir);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX);
|
||||
fi.version_id = match &opts.version_id {
|
||||
Some(id) => Some(Uuid::parse_str(id)?),
|
||||
None if opts.versioned => {
|
||||
let id = Uuid::new_v4();
|
||||
insert_str(&mut user_defined, MULTIPART_GENERATED_VERSION_SUFFIX, format!("{data_dir}/{id}"));
|
||||
Some(id)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
if crate::object_api::legacy_encrypted_range_seek_enabled()
|
||||
&& !opts.no_lock
|
||||
&& should_persist_encryption_original_size(&user_defined)
|
||||
@@ -4486,7 +4495,6 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
result
|
||||
}
|
||||
|
||||
// complete_multipart_upload finished
|
||||
#[tracing::instrument(level = "trace", skip(self))]
|
||||
async fn complete_multipart_upload(
|
||||
self: Arc<Self>,
|
||||
@@ -4495,6 +4503,21 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
upload_id: &str,
|
||||
uploaded_parts: Vec<CompletePart>,
|
||||
opts: &ObjectOptions,
|
||||
) -> Result<ObjectInfo> {
|
||||
self.complete_multipart_upload_with_store(bucket, object, upload_id, uploaded_parts, opts, None)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl SetDisks {
|
||||
pub(crate) async fn complete_multipart_upload_with_store(
|
||||
self: Arc<Self>,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
upload_id: &str,
|
||||
uploaded_parts: Vec<CompletePart>,
|
||||
opts: &ObjectOptions,
|
||||
multipool_store: Option<&crate::store::ECStore>,
|
||||
) -> Result<ObjectInfo> {
|
||||
crate::hp_guard!("SetDisks::complete_multipart_upload");
|
||||
let write_context = WriteCommitContext::from_options(opts, bucket, object, false)?;
|
||||
@@ -4504,8 +4527,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let range_seek_rollout_enabled =
|
||||
crate::object_api::legacy_encrypted_range_seek_enabled() && write_context.acquires_namespace();
|
||||
let mut object_lock_guard = None;
|
||||
let mut decommission_object_lock_guard = None;
|
||||
let mut decommission_target_lock_covered = false;
|
||||
let mut store_object_guards: Option<Arc<[crate::store::ObjectLockDiagGuard]>> = None;
|
||||
let has_lost_store_lock =
|
||||
|guards: &[crate::store::ObjectLockDiagGuard]| guards.iter().any(crate::store::ObjectLockDiagGuard::is_lock_lost);
|
||||
let mut decommission_capacity_guard = None;
|
||||
|
||||
// Lock order: lifecycle -> metadata transaction -> object namespace -> upload.
|
||||
@@ -4526,44 +4550,62 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
opts
|
||||
};
|
||||
|
||||
if opts.http_preconditions.is_some() {
|
||||
if write_context.acquires_namespace() {
|
||||
object_lock_guard = Some(
|
||||
self.acquire_write_lock_diag("complete_multipart_upload_precondition", bucket, object)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(err) = self.check_write_precondition(bucket, object, opts).await {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
// Conditional publication requires namespace locking. Ordinary writes retain
|
||||
// the selected set's namespace when deployment-wide locking is disabled.
|
||||
let multipool_locks =
|
||||
multipool_store.filter(|_| opts.http_preconditions.is_some() || !self.ctx.lock_manager().is_disabled());
|
||||
let target_covered = if let Some(store) = multipool_locks.or(opts.decommission_capacity_admission.as_deref()) {
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
|
||||
}
|
||||
let (object_guard, target_lock_covered, capacity_guard) = store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
!write_context.acquires_namespace() || object_lock_guard.is_some(),
|
||||
DecommissionCapacityAdmission::ExistingMultipart,
|
||||
)
|
||||
.await?;
|
||||
decommission_object_lock_guard = object_guard;
|
||||
decommission_target_lock_covered = target_lock_covered;
|
||||
decommission_capacity_guard = capacity_guard;
|
||||
}
|
||||
if write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered {
|
||||
if multipool_locks.is_some() {
|
||||
#[cfg(test)]
|
||||
if opts.http_preconditions.is_some() {
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeConditionalNamespace).await;
|
||||
}
|
||||
store_object_guards = Some(
|
||||
Box::pin(store.acquire_physical_object_write_locks(
|
||||
"complete_multipart_upload_commit",
|
||||
bucket,
|
||||
object,
|
||||
write_context.borrowed_write_guards(bucket, object),
|
||||
))
|
||||
.await?
|
||||
.into(),
|
||||
);
|
||||
true
|
||||
} else if write_context.acquires_namespace() {
|
||||
let guard = store.acquire_external_commit_namespace(bucket, object, &self).await?;
|
||||
store_object_guards = Some(Arc::new([guard]));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if write_context.acquires_namespace() && !target_covered {
|
||||
object_lock_guard = Some(
|
||||
self.acquire_write_lock_diag("complete_multipart_upload_commit", bucket, object)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
let conditional_current = match multipool_store {
|
||||
Some(store) if opts.http_preconditions.is_some() => {
|
||||
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
|
||||
}
|
||||
Some(_) => None,
|
||||
None => {
|
||||
if opts.http_preconditions.is_some()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
let mut upload_guard = self
|
||||
.acquire_multipart_upload_write_lock("complete_multipart_upload_commit", bucket, object, upload_id, opts)
|
||||
.await?;
|
||||
@@ -4705,6 +4747,13 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
ensure_multipart_bucket_lifecycle_lock_held(bucket, object, opts)?;
|
||||
}
|
||||
let source_condition = capture_source_condition(bucket, object, &upload_id_path, &fi, Uuid::new_v4())?;
|
||||
// A marker copied from a prior object cannot establish how this upload's version was assigned.
|
||||
let generated_version = get_consistent_str(&fi.metadata, MULTIPART_GENERATED_VERSION_SUFFIX).and_then(|marker| {
|
||||
source_condition
|
||||
.lineage
|
||||
.original_version_id
|
||||
.filter(|id| marker == format!("{}/{id}", source_condition.lineage.original_data_dir))
|
||||
});
|
||||
let preserved_encrypted_etag = preserves_staged_encrypted_etag_proof(&fi, opts, expected_restore_operation_id);
|
||||
let upload_data_dir = source_condition.lineage.original_data_dir.to_string();
|
||||
// The source generation remains in the captured precondition. Its
|
||||
@@ -4730,9 +4779,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
// and heterogeneous replication clients can send an authorized
|
||||
// REPLICA status on Complete without repeating the source-request
|
||||
// marker, so either authenticated parser result is sufficient.
|
||||
let authorized_inbound_replica =
|
||||
opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica;
|
||||
if !authorized_inbound_replica {
|
||||
if !opts.is_inbound_multipart_replica() {
|
||||
fi.metadata
|
||||
.retain(|key, _| !key.eq_ignore_ascii_case(metadata_keys::REPLICATION_STATUS));
|
||||
for suffix in [
|
||||
@@ -4795,8 +4842,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
// source's null version, so its completion keeps the null version,
|
||||
// exactly like the single-PUT path (rustfs/rustfs#8747). Any other
|
||||
// completion in a versioned bucket gets a concrete version.
|
||||
let replicated_null_version = fi.version_id.is_none_or(|version_id| version_id.is_nil())
|
||||
&& (opts.replication_request || opts.delete_marker_replication_status() == ReplicationStatusType::Replica);
|
||||
let replicated_null_version =
|
||||
fi.version_id.is_none_or(|version_id| version_id.is_nil()) && opts.is_inbound_multipart_replica();
|
||||
if opts.restore_copyback {
|
||||
require_multipart_restore_target(opts, fi.version_id)?;
|
||||
} else if opts.versioned && replicated_null_version {
|
||||
@@ -4816,6 +4863,23 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
} else {
|
||||
fi.version_id = None;
|
||||
}
|
||||
let predecessors = match multipool_store {
|
||||
Some(store) => {
|
||||
let current = if opts.http_preconditions.is_some() {
|
||||
conditional_current
|
||||
} else {
|
||||
// An unconditional replay returns before it needs the current head.
|
||||
Box::pin(store.read_current_for_put(bucket, object, opts)).await?
|
||||
};
|
||||
// A version already visible under this UUID is an overwrite, even
|
||||
// if Create generated it. Legacy uploads can also name a historical version.
|
||||
let target = fi.version_id.unwrap_or_default();
|
||||
let matches_head = current.as_ref().is_some_and(|info| info.version_id == Some(target));
|
||||
let replaced = (matches_head || Some(target) != generated_version).then_some(target);
|
||||
Some(Box::pin(store.resolve_put_predecessors(bucket, object, opts, current, replaced)).await?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let write_quorum = fi.write_quorum(self.default_write_quorum());
|
||||
let read_quorum = fi.read_quorum(self.default_read_quorum());
|
||||
|
||||
@@ -5232,6 +5296,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM);
|
||||
fi.metadata.remove(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE);
|
||||
strip_internal_multipart_metadata(&mut fi.metadata);
|
||||
if !opts.data_movement {
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
}
|
||||
if opts.restore_copyback {
|
||||
insert_str(
|
||||
&mut fi.metadata,
|
||||
@@ -5248,7 +5315,11 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
fi.size = object_size as i64;
|
||||
fi.mod_time = opts.mod_time;
|
||||
if fi.mod_time.is_none() {
|
||||
fi.mod_time = Some(OffsetDateTime::now_utc());
|
||||
let now = OffsetDateTime::now_utc();
|
||||
fi.mod_time = Some(match &predecessors {
|
||||
Some(predecessors) => predecessors.commit_time(now)?,
|
||||
None => now,
|
||||
});
|
||||
}
|
||||
|
||||
// etag
|
||||
@@ -5327,11 +5398,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
// other read failures must leave the upload retryable rather than
|
||||
// committing inbound metadata without the LWW check.
|
||||
//
|
||||
// The same read enforces the commit-time WORM gate on the staged
|
||||
// `fi.version_id`, which the completion request does not name. An
|
||||
// ordinary upload stages a fresh UUID and finds no version here;
|
||||
// `opts.restore_copyback` and `opts.data_movement` run their stricter
|
||||
// checks below.
|
||||
// Create can name the version to replace without repeating it at Complete.
|
||||
// Reuse the locked cross-pool predecessor when available. Replication
|
||||
// judges the destination set's version and metadata together.
|
||||
let snapshot_state = opts.object_lock_config_snapshot.as_deref().map(|snapshot| snapshot.state());
|
||||
let need_worm_lookup = !opts.data_movement
|
||||
&& !opts.restore_copyback
|
||||
@@ -5342,28 +5411,35 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if (need_worm_lookup || replication_lww_applicable)
|
||||
&& let Some(version_id) = target_version_id
|
||||
{
|
||||
match self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(existing) => {
|
||||
let local;
|
||||
let existing = match &predecessors {
|
||||
Some(predecessors) => Ok(predecessors.replaced().filter(|info| !info.delete_marker)),
|
||||
None => {
|
||||
local = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
local.as_ref().map(Some).map_err(Clone::clone)
|
||||
}
|
||||
};
|
||||
match existing {
|
||||
Ok(Some(existing)) => {
|
||||
if !opts.data_movement && !opts.restore_copyback && !crate::bucket::utils::is_meta_bucketname(bucket) {
|
||||
let effective_state = snapshot_state.unwrap_or(&ObjectLockConfigState::ConfirmedAbsent);
|
||||
if check_object_lock_for_deletion_with_state(effective_state, &existing, false)?.is_some() {
|
||||
if check_object_lock_for_deletion_with_state(effective_state, existing, false)?.is_some() {
|
||||
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
|
||||
effective_state,
|
||||
&existing,
|
||||
existing,
|
||||
opts,
|
||||
&fi.metadata,
|
||||
)? {
|
||||
@@ -5397,9 +5473,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
#[cfg(test)]
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5458,7 +5532,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
|
||||
drop(object_lock_guard.take());
|
||||
drop(decommission_object_lock_guard.take());
|
||||
drop(store_object_guards.take());
|
||||
drop(decommission_capacity_guard.take());
|
||||
if let Err(err) = self
|
||||
.delete_all_with_quorum(RUSTFS_META_MULTIPART_BUCKET, &upload_id_path, write_quorum)
|
||||
@@ -5484,10 +5558,11 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
}
|
||||
if replication_lww_applicable {
|
||||
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(&existing);
|
||||
let stored = crate::set_disk::ops::object::stored_replication_category_metadata(existing);
|
||||
crate::set_disk::ops::object::merge_replication_metadata_lww(&mut fi.metadata, &stored, opts);
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
// A null delete marker has no protected payload to replace.
|
||||
Err(StorageError::MethodNotAllowed) if version_id.is_nil() => {}
|
||||
// Version absent: a fresh version id or the first replication
|
||||
@@ -5545,9 +5620,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
#[cfg(test)]
|
||||
pause_multipart_commit(bucket, object, MultipartCommitPause::BeforeLockLost).await;
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5659,9 +5732,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
}
|
||||
}
|
||||
if object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "complete_multipart_upload_commit",
|
||||
@@ -5699,7 +5770,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
// Recheck decommission capacity only after those locks, and retain the
|
||||
// guard through the durable rename below.
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
&& let Some(store) = multipool_store.or(opts.decommission_capacity_admission.as_deref())
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
store
|
||||
@@ -5736,9 +5807,12 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
copy_publication_controls(&fi.metadata, &mut metadata.metadata)?;
|
||||
}
|
||||
|
||||
let put_usage = predecessors.as_deref().map(|previous| previous.usage_receipt()).transpose()?;
|
||||
let quota_old_size = if quota_context.is_enforced() {
|
||||
if opts.data_movement {
|
||||
quota_new_size
|
||||
} else if let Some(usage) = &put_usage {
|
||||
usage.replaced_size()
|
||||
} else {
|
||||
reservation::replaced_logical_size(&self, bucket, object, opts).await?
|
||||
}
|
||||
@@ -5807,7 +5881,8 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let commit_capacity_scope_token = opts.capacity_scope_token;
|
||||
let commit_object_lock_guard = object_lock_guard.take().map(Arc::new);
|
||||
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
|
||||
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take().map(Arc::new);
|
||||
let commit_store_object_guards = store_object_guards;
|
||||
let multipool_publication = multipool_locks.is_some();
|
||||
let commit_decommission_capacity_guard = decommission_capacity_guard.take().map(Arc::new);
|
||||
// CompleteMultipartUpload is an S3 publication boundary: after a
|
||||
// successful response, the object must be immediately readable and
|
||||
@@ -5820,7 +5895,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let write_context = Arc::new(write_context);
|
||||
let mut _object_lock_guard = commit_object_lock_guard;
|
||||
let _object_lock_config_snapshot = commit_object_lock_config_snapshot;
|
||||
let mut _decommission_object_lock_guard = commit_decommission_object_lock_guard;
|
||||
let mut _store_object_guards = commit_store_object_guards;
|
||||
let mut _upload_guard = upload_guard.map(Arc::new);
|
||||
let mut _decommission_capacity_guard = commit_decommission_capacity_guard;
|
||||
let mut quota_reservation = quota_reservation;
|
||||
@@ -5850,9 +5925,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if quota_reservation.is_lock_lost()
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| commit_namespace_lock_fence
|
||||
.as_ref()
|
||||
@@ -5904,9 +5977,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
if quota_reservation.is_lock_lost()
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _store_object_guards.as_deref().is_some_and(has_lost_store_lock)
|
||||
|| _upload_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| commit_namespace_lock_fence
|
||||
.as_ref()
|
||||
@@ -5954,7 +6025,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let multipart_commit_owner = crate::set_disk::core::io_primitives::MultipartLogicalGuards::new((
|
||||
write_context.clone(),
|
||||
_object_lock_guard.clone(),
|
||||
_decommission_object_lock_guard.clone(),
|
||||
_store_object_guards.clone(),
|
||||
_upload_guard.clone(),
|
||||
_decommission_capacity_guard.clone(),
|
||||
commit_namespace_lock_fence.clone(),
|
||||
@@ -6069,6 +6140,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
.await;
|
||||
|
||||
drop(_object_lock_guard.take()); // release the object lock before multipart cleanup IO.
|
||||
if multipool_publication {
|
||||
drop(_store_object_guards.take());
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pause_multipart_commit(&commit_bucket, &commit_object, MultipartCommitPause::AfterObjectPublication).await;
|
||||
@@ -6132,6 +6206,7 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
|
||||
let mut obj_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
|
||||
obj_info.backfilled_old_current_size = old_current_size;
|
||||
obj_info.put_usage = put_usage;
|
||||
Ok(obj_info)
|
||||
};
|
||||
|
||||
|
||||
@@ -4699,7 +4699,7 @@ impl SetDisks {
|
||||
data: &mut PutObjReader,
|
||||
opts: &ObjectOptions,
|
||||
) -> Result<(ObjectInfo, Option<OldCurrentSize>)> {
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None)
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None, None)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -4718,10 +4718,23 @@ impl SetDisks {
|
||||
// The owned publication capability supplies the exact target write
|
||||
// domain at commit time; the generic PUT path must not reacquire it.
|
||||
opts.no_lock = true;
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, &opts, Some(publication_fence))
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, &opts, Some(publication_fence), None)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Stage the stream locally, then resolve the logical predecessor under the cross-pool publication locks.
|
||||
pub(crate) fn put_object_in_store<'a>(
|
||||
&'a self,
|
||||
bucket: &'a str,
|
||||
object: &'a str,
|
||||
data: &'a mut PutObjReader,
|
||||
opts: &'a ObjectOptions,
|
||||
store: &'a ECStore,
|
||||
use_multipool_predecessors: bool,
|
||||
) -> impl Future<Output = Result<(ObjectInfo, Option<OldCurrentSize>)>> + Send + 'a {
|
||||
self.put_object_with_old_current_size_boxed(bucket, object, data, opts, None, Some((store, use_multipool_predecessors)))
|
||||
}
|
||||
|
||||
fn put_object_with_old_current_size_boxed<'a>(
|
||||
&'a self,
|
||||
bucket: &'a str,
|
||||
@@ -4729,8 +4742,9 @@ impl SetDisks {
|
||||
data: &'a mut PutObjReader,
|
||||
opts: &'a ObjectOptions,
|
||||
publication_fence: Option<RemoteTuplePublicationFence>,
|
||||
commit_store: Option<(&'a ECStore, bool)>,
|
||||
) -> impl Future<Output = Result<(ObjectInfo, Option<OldCurrentSize>)>> + Send + 'a {
|
||||
Box::pin(self.put_object_with_old_current_size_inner(bucket, object, data, opts, publication_fence))
|
||||
Box::pin(self.put_object_with_old_current_size_inner(bucket, object, data, opts, publication_fence, commit_store))
|
||||
}
|
||||
|
||||
async fn put_object_with_old_current_size_inner(
|
||||
@@ -4740,8 +4754,15 @@ impl SetDisks {
|
||||
data: &mut PutObjReader,
|
||||
opts: &ObjectOptions,
|
||||
mut publication_fence: Option<RemoteTuplePublicationFence>,
|
||||
commit_store: Option<(&ECStore, bool)>,
|
||||
) -> Result<(ObjectInfo, Option<OldCurrentSize>)> {
|
||||
let write_context = WriteCommitContext::from_options(opts, bucket, object, publication_fence.is_some())?;
|
||||
let store = commit_store.map(|(store, _)| store);
|
||||
let multipool_store = commit_store.and_then(|(store, check)| check.then_some(store));
|
||||
let capacity_store = match store {
|
||||
Some(store) => (!store.single_pool()).then_some(store),
|
||||
None => opts.decommission_capacity_admission.as_deref(),
|
||||
};
|
||||
let protect_write = opts.shard_integrity_write_enabled();
|
||||
let source_bucket_incarnation_id = match opts.expected_bucket_incarnation_id {
|
||||
Some(incarnation_id) => Some(incarnation_id),
|
||||
@@ -4789,21 +4810,21 @@ impl SetDisks {
|
||||
let disks = self.get_disks_internal().await;
|
||||
|
||||
let mut object_lock_guard = None;
|
||||
let mut decommission_object_lock_guard = None;
|
||||
let mut decommission_target_lock_covered = false;
|
||||
let mut decommission_object_lock_guard: Vec<crate::store::ObjectLockDiagGuard> = Vec::new();
|
||||
let mut decommission_capacity_guard = None;
|
||||
let mut bucket_lifecycle_guard = None;
|
||||
let mut publication_commit_guard: Option<RemoteTuplePublicationCommitGuard> = None;
|
||||
|
||||
// This pre-body check is advisory fast-fail only: the authoritative
|
||||
// precondition evaluation happens under the commit namespace lock
|
||||
// below, so the namespace write lock must NOT be taken here — holding
|
||||
// it across client-paced body ingestion starves concurrent reads of
|
||||
// the same object into lock-timeout 503s (rustfs/backlog#2074).
|
||||
// Data movement skips the advisory read: its staleness predicate is
|
||||
// only meaningful at commit time.
|
||||
// only meaningful at commit time. Multi-pool conditional
|
||||
// PUTs run a cross-pool advisory check in ECStore before pool selection.
|
||||
if opts.http_preconditions.is_some()
|
||||
&& !opts.data_movement
|
||||
&& multipool_store.is_none()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
@@ -4892,6 +4913,9 @@ impl SetDisks {
|
||||
&mut user_defined,
|
||||
crate::object_api::ENCRYPTED_FRAME_LAYOUT_FIXED8K_SUFFIX,
|
||||
);
|
||||
if !opts.data_movement {
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX);
|
||||
}
|
||||
if crate::io_support::rio::encryption_frame_v2_enabled()
|
||||
&& !opts.preserve_ciphertext
|
||||
&& !opts.data_movement
|
||||
@@ -5421,7 +5445,14 @@ impl SetDisks {
|
||||
deferred_commit_opts = opts.clone();
|
||||
let expected = source_bucket_incarnation_id
|
||||
.ok_or_else(|| Error::other("destructive PUT is missing its bucket incarnation"))?;
|
||||
let store = metadata_sys::object_store_in(&self.ctx).await?;
|
||||
let initialized_store;
|
||||
let store = match store {
|
||||
Some(store) => store,
|
||||
None => {
|
||||
initialized_store = metadata_sys::object_store_in(&self.ctx).await?;
|
||||
&initialized_store
|
||||
}
|
||||
};
|
||||
let snapshot = match opts.bucket_lifecycle_lock_fence.as_ref() {
|
||||
Some(fence) => store.object_lock_config_snapshot_under_lifecycle_fence(bucket, fence).await?,
|
||||
None => store.object_lock_config_snapshot_for_single_put(bucket).await?,
|
||||
@@ -5433,7 +5464,7 @@ impl SetDisks {
|
||||
deferred_commit_opts.object_lock_config_snapshot = Some(snapshot);
|
||||
deferred_commit_opts.defer_put_object_lock_snapshot = false;
|
||||
&deferred_commit_opts
|
||||
} else if opts.decommission_capacity_admission.is_some()
|
||||
} else if capacity_store.is_some()
|
||||
&& write_context.acquires_namespace()
|
||||
&& metadata_sys::needs_commit_metadata_snapshot(&self.ctx, bucket, opts)
|
||||
{
|
||||
@@ -5451,36 +5482,31 @@ impl SetDisks {
|
||||
opts
|
||||
};
|
||||
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
|
||||
}
|
||||
let (object_guard, target_lock_covered, capacity_guard) = store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
!write_context.acquires_namespace() || object_lock_guard.is_some(),
|
||||
DecommissionCapacityAdmission::Mutation,
|
||||
)
|
||||
.await?;
|
||||
decommission_object_lock_guard = object_guard;
|
||||
decommission_target_lock_covered = target_lock_covered;
|
||||
decommission_capacity_guard = capacity_guard;
|
||||
let multipool_locks = multipool_store.filter(|_| !self.ctx.lock_manager().is_disabled());
|
||||
#[cfg(test)]
|
||||
if let Some(store) = capacity_store {
|
||||
crate::core::pools::notify_decommission_external_object_commit_phase_started(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_commit_phase_release(store.id).await;
|
||||
}
|
||||
if publication_fence.is_some()
|
||||
|| (write_context.acquires_namespace() && object_lock_guard.is_none() && !decommission_target_lock_covered)
|
||||
if multipool_locks.is_some()
|
||||
|| publication_fence.is_some()
|
||||
|| (write_context.acquires_namespace() && object_lock_guard.is_none())
|
||||
{
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
pause_put_object_commit(bucket, object, PutObjectCommitPause::BeforeNamespace).await;
|
||||
if let Some(expected_incarnation_id) = source_bucket_incarnation_id
|
||||
&& opts.bucket_lifecycle_lock_fence.is_none()
|
||||
{
|
||||
let initialized_store;
|
||||
let store = match store {
|
||||
Some(store) => store,
|
||||
None => {
|
||||
initialized_store = metadata_sys::object_store_in(&self.ctx).await?;
|
||||
&initialized_store
|
||||
}
|
||||
};
|
||||
bucket_lifecycle_guard = Some(
|
||||
metadata_sys::object_store_in(&self.ctx)
|
||||
.await?
|
||||
store
|
||||
.acquire_bucket_incarnation_fence(bucket, expected_incarnation_id)
|
||||
.await?,
|
||||
);
|
||||
@@ -5503,8 +5529,27 @@ impl SetDisks {
|
||||
.await?;
|
||||
opts = &pre_lock_commit_opts;
|
||||
}
|
||||
if let Some(fence) = publication_fence.take() {
|
||||
if let Some(store) = multipool_locks {
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
notify_put_object_commit_namespace_pending(bucket, object);
|
||||
decommission_object_lock_guard = Box::pin(store.acquire_physical_object_write_locks(
|
||||
"put_object_commit",
|
||||
bucket,
|
||||
object,
|
||||
write_context.borrowed_write_guards(bucket, object),
|
||||
))
|
||||
.await?;
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
notify_put_object_commit_namespace_acquired(bucket, object);
|
||||
} else if let Some(fence) = publication_fence.take() {
|
||||
publication_commit_guard = Some(fence.into_commit_guard(self.pool_index, bucket, object).await?);
|
||||
} else if let Some(store) = capacity_store {
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
notify_put_object_commit_namespace_pending(bucket, object);
|
||||
decommission_object_lock_guard
|
||||
.push(Box::pin(store.acquire_external_commit_namespace(bucket, object, self)).await?);
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
notify_put_object_commit_namespace_acquired(bucket, object);
|
||||
} else {
|
||||
#[cfg(any(test, feature = "test-util"))]
|
||||
{
|
||||
@@ -5527,11 +5572,16 @@ impl SetDisks {
|
||||
let namespace_lock_acquired_to_commit_ready_started = rustfs_io_metrics::put_stage_timer();
|
||||
let commit_ready_precondition_and_timestamp_started = rustfs_io_metrics::put_stage_timer();
|
||||
|
||||
if opts.http_preconditions.is_some()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
let put_predecessors = if let Some(store) = multipool_store {
|
||||
Some(Box::pin(store.multipool_put_predecessors(bucket, object, opts)).await?)
|
||||
} else {
|
||||
if opts.http_preconditions.is_some()
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
None
|
||||
};
|
||||
|
||||
if bucket == RUSTFS_META_BUCKET
|
||||
&& object == "pool.bin"
|
||||
@@ -5595,7 +5645,11 @@ impl SetDisks {
|
||||
// the same object. Internal callers with an explicit timestamp keep
|
||||
// their supplied value.
|
||||
if opts.mod_time.is_none() {
|
||||
let commit_time = Some(OffsetDateTime::now_utc());
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let commit_time = Some(match &put_predecessors {
|
||||
Some(predecessors) => predecessors.commit_time(now)?,
|
||||
None => now,
|
||||
});
|
||||
for pfi in &mut parts_metadatas {
|
||||
pfi.mod_time = commit_time;
|
||||
for part in &mut pfi.parts {
|
||||
@@ -5610,26 +5664,27 @@ impl SetDisks {
|
||||
|
||||
if let Some(expected) = opts.expected_current_version_id.as_deref() {
|
||||
let expected_version_lookup_started = rustfs_io_metrics::put_stage_timer();
|
||||
let current = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
if is_err_object_not_found(&err) || is_err_version_not_found(&err) {
|
||||
StorageError::PreconditionFailed
|
||||
} else {
|
||||
err
|
||||
}
|
||||
})?;
|
||||
if current.version_id.map(|version| version.to_string()).as_deref() != Some(expected) {
|
||||
let current_version = match &put_predecessors {
|
||||
Some(predecessors) => predecessors.current().and_then(|info| info.version_id),
|
||||
None => match self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(info) => info.version_id,
|
||||
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => None,
|
||||
Err(err) => return Err(err),
|
||||
},
|
||||
};
|
||||
if current_version.map(|version| version.to_string()).as_deref() != Some(expected) {
|
||||
return Err(StorageError::PreconditionFailed);
|
||||
}
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
@@ -5655,22 +5710,29 @@ impl SetDisks {
|
||||
&& !is_meta_bucketname(bucket)
|
||||
{
|
||||
let explicit_version_lookup_started = rustfs_io_metrics::put_stage_timer();
|
||||
let current = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_string()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let local;
|
||||
let current = match &put_predecessors {
|
||||
Some(predecessors) => Ok(predecessors.replaced()),
|
||||
None => {
|
||||
local = self
|
||||
.get_object_info(
|
||||
bucket,
|
||||
object,
|
||||
&ObjectOptions {
|
||||
version_id: Some(version_id.to_owned()),
|
||||
no_lock: true,
|
||||
metadata_cache_safe: false,
|
||||
versioned: opts.versioned,
|
||||
version_suspended: opts.version_suspended,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
local.as_ref().map(Some).map_err(Clone::clone)
|
||||
}
|
||||
};
|
||||
match current {
|
||||
Ok(existing) => {
|
||||
Ok(Some(existing)) => {
|
||||
let object_lock_config = opts
|
||||
.object_lock_config_snapshot
|
||||
.as_deref()
|
||||
@@ -5683,12 +5745,12 @@ impl SetDisks {
|
||||
// stay immutable: commit only the LWW-judged metadata
|
||||
// categories via `update_object_meta_with_opts`.
|
||||
let is_locked =
|
||||
check_object_lock_for_deletion_with_state(object_lock_config.state(), &existing, false)?.is_some();
|
||||
check_object_lock_for_deletion_with_state(object_lock_config.state(), existing, false)?.is_some();
|
||||
if is_locked {
|
||||
let inbound_metadata = &parts_metadatas[response_metadata_slot].metadata;
|
||||
if !replication_write_may_pass_worm_gate_with_inbound_metadata(
|
||||
object_lock_config.state(),
|
||||
&existing,
|
||||
existing,
|
||||
opts,
|
||||
inbound_metadata,
|
||||
)? {
|
||||
@@ -5763,8 +5825,8 @@ impl SetDisks {
|
||||
});
|
||||
}
|
||||
if decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
.iter()
|
||||
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "put_object_external_namespace",
|
||||
@@ -5820,7 +5882,7 @@ impl SetDisks {
|
||||
// more recently on this site is kept instead of being
|
||||
// overwritten by the inbound replication metadata.
|
||||
if replication_lww_applicable(opts) {
|
||||
let stored = stored_replication_category_metadata(&existing);
|
||||
let stored = stored_replication_category_metadata(existing);
|
||||
let mut merged = parts_metadatas[response_metadata_slot].metadata.clone();
|
||||
if merge_replication_metadata_lww(&mut merged, &stored, opts) {
|
||||
for (pfi, disk) in parts_metadatas.iter_mut().zip(shuffle_disks.iter()) {
|
||||
@@ -5831,6 +5893,7 @@ impl SetDisks {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
// A null delete marker has no protected payload to replace.
|
||||
Err(StorageError::MethodNotAllowed) if version_id == Uuid::nil().to_string() => {}
|
||||
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {}
|
||||
@@ -5897,14 +5960,17 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
let decommission_capacity_fence_started = rustfs_io_metrics::put_stage_timer();
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
if let Some(store) = capacity_store {
|
||||
decommission_capacity_guard = Some(
|
||||
store
|
||||
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
|
||||
.await?,
|
||||
);
|
||||
#[cfg(test)]
|
||||
{
|
||||
crate::core::pools::notify_decommission_external_object_capacity_probe_acquired(store.id);
|
||||
crate::core::pools::wait_for_decommission_external_object_capacity_probe_release(store.id).await;
|
||||
}
|
||||
}
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_READY_DECOMMISSION_CAPACITY_FENCE,
|
||||
@@ -5916,8 +5982,8 @@ impl SetDisks {
|
||||
// against the decommission capacity ledger; holding this guard
|
||||
// through rename_data keeps the namespace -> capacity order.
|
||||
if decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
.iter()
|
||||
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|
||||
{
|
||||
return Err(StorageError::NamespaceLockQuorumUnavailable {
|
||||
mode: "put_object_external_namespace",
|
||||
@@ -6027,6 +6093,10 @@ impl SetDisks {
|
||||
);
|
||||
|
||||
let quota_reserve_started = rustfs_io_metrics::put_stage_timer();
|
||||
let put_usage = put_predecessors
|
||||
.as_deref()
|
||||
.map(|previous| previous.usage_receipt())
|
||||
.transpose()?;
|
||||
let (quota_old_size, quota_new_size) = if quota_context.is_enforced() {
|
||||
let new_size = match replication_quota_size {
|
||||
Some(size) => size,
|
||||
@@ -6036,6 +6106,8 @@ impl SetDisks {
|
||||
};
|
||||
let old_size = if opts.data_movement {
|
||||
new_size
|
||||
} else if let Some(usage) = &put_usage {
|
||||
usage.replaced_size()
|
||||
} else {
|
||||
reservation::replaced_logical_size(self, bucket, object, opts).await?
|
||||
};
|
||||
@@ -6086,7 +6158,7 @@ impl SetDisks {
|
||||
let commit_tmp_dir = tmp_dir.clone();
|
||||
let commit_rollback_receipt = rollback_receipt.clone();
|
||||
let commit_object_lock_guard = object_lock_guard.take();
|
||||
let commit_decommission_object_lock_guard = decommission_object_lock_guard.take();
|
||||
let commit_decommission_object_lock_guard = std::mem::take(&mut decommission_object_lock_guard);
|
||||
let commit_publication_guard = publication_commit_guard.take();
|
||||
let commit_bucket_lifecycle_guard = bucket_lifecycle_guard.take();
|
||||
let commit_object_lock_config_snapshot = opts.object_lock_config_snapshot.clone();
|
||||
@@ -6098,7 +6170,7 @@ impl SetDisks {
|
||||
// remote leases.
|
||||
let commit_owns_namespace_guard = write_context.has_borrowed_owner()
|
||||
|| commit_object_lock_guard.is_some()
|
||||
|| commit_decommission_object_lock_guard.is_some()
|
||||
|| !commit_decommission_object_lock_guard.is_empty()
|
||||
|| commit_publication_guard.is_some();
|
||||
let commit_write_completion = opts.write_completion;
|
||||
let bound_rename_dispatch = commit_write_completion == crate::object_api::WriteCompletion::TailDrained
|
||||
@@ -6183,8 +6255,8 @@ impl SetDisks {
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
.iter()
|
||||
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|
||||
|| _publication_guard
|
||||
.as_ref()
|
||||
.is_some_and(RemoteTuplePublicationCommitGuard::is_lock_lost)
|
||||
@@ -6257,8 +6329,8 @@ impl SetDisks {
|
||||
|| write_context.is_lock_lost()
|
||||
|| _object_lock_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| _decommission_object_lock_guard
|
||||
.as_ref()
|
||||
.is_some_and(|guard| guard.is_lock_lost())
|
||||
.iter()
|
||||
.any(crate::store::ObjectLockDiagGuard::is_lock_lost)
|
||||
|| _publication_guard
|
||||
.as_ref()
|
||||
.is_some_and(RemoteTuplePublicationCommitGuard::is_lock_lost)
|
||||
@@ -6499,7 +6571,7 @@ impl SetDisks {
|
||||
let publication_guard = _publication_guard.take();
|
||||
let bucket_lifecycle_guard = _bucket_lifecycle_guard.take();
|
||||
let object_lock_config_snapshot = _object_lock_config_snapshot.take();
|
||||
let decommission_object_lock_guard = _decommission_object_lock_guard.take();
|
||||
let decommission_object_lock_guard = std::mem::take(&mut _decommission_object_lock_guard);
|
||||
let decommission_capacity_guard = _decommission_capacity_guard.take();
|
||||
let cleanup_bucket = commit_bucket.clone();
|
||||
let cleanup_object = commit_object.clone();
|
||||
@@ -6996,7 +7068,8 @@ impl SetDisks {
|
||||
|
||||
let completion = repair_result.map(|()| {
|
||||
let object_info_build_started = rustfs_io_metrics::put_stage_timer();
|
||||
let object_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
|
||||
let mut object_info = ObjectInfo::from_file_info(&fi, &commit_bucket, &commit_object, commit_is_versioned);
|
||||
object_info.put_usage = put_usage;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
rustfs_io_metrics::PUT_STAGE_PUT_OBJECT_COMMIT_NAMESPACE_LOCK_HELD_OBJECT_INFO_BUILD,
|
||||
object_info_build_started,
|
||||
@@ -10809,6 +10882,21 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
};
|
||||
let mut replacement_metadata = (*src_info.user_defined).clone();
|
||||
rustfs_filemeta::shard_integrity::clear_integrity_metadata(&mut replacement_metadata);
|
||||
rustfs_utils::http::metadata_compat::remove_str(
|
||||
&mut replacement_metadata,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
);
|
||||
if !src_info.version_only
|
||||
&& let Some(value) =
|
||||
rustfs_utils::http::get_consistent_str(&fi.metadata, crate::object_api::LOGICAL_BODY_REVISION_SUFFIX)
|
||||
.filter(|val| Uuid::parse_str(val.trim()).ok().is_some_and(|id| !id.is_nil()))
|
||||
{
|
||||
rustfs_utils::http::insert_str(
|
||||
&mut replacement_metadata,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
value.to_owned(),
|
||||
);
|
||||
}
|
||||
if src_info.version_only {
|
||||
// Shared shard files retain the selected version's persisted framing.
|
||||
let suffix = crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX;
|
||||
@@ -11335,7 +11423,7 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
// Only a concrete generation with a different identity is stale.
|
||||
if let Some(expected) = dobj.expected_identity
|
||||
&& (gerr.is_none() || matches!(gerr.as_ref(), Some(StorageError::MethodNotAllowed)))
|
||||
&& (goi.data_dir != expected.data_dir
|
||||
&& ((goi.data_dir != expected.data_dir && goi.logical_body_revision() != expected.data_dir)
|
||||
|| goi.mod_time != expected.mod_time
|
||||
|| goi.delete_marker != expected.delete_marker)
|
||||
{
|
||||
|
||||
@@ -1550,7 +1550,7 @@ impl SetDisks {
|
||||
.await?;
|
||||
if let Some(expected) = part.integrity.as_ref() {
|
||||
use crate::io_support::shard_integrity::{PartProofReader, ShardVerifier};
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object)?;
|
||||
let proof = PartProofReader::new(expected.clone(), files, disks, bucket, object, Some(1))?;
|
||||
for (index, reader) in readers.iter_mut().enumerate() {
|
||||
if let Some(reader) = reader {
|
||||
reader.set_integrity(ShardVerifier::new(Arc::clone(&proof), index, 0, None)?)?;
|
||||
@@ -1618,7 +1618,7 @@ impl SetDisks {
|
||||
erasure.data_shards,
|
||||
)
|
||||
.await;
|
||||
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0)?;
|
||||
reader_setup.bind_integrity(part.integrity.as_ref(), files_ref, disks_ref, bucket, object, 0..1)?;
|
||||
let reader_setup_elapsed = reader_setup_stage_start.elapsed();
|
||||
rustfs_io_metrics::record_get_object_shard_reader_setup_duration(reader_setup_elapsed.as_secs_f64());
|
||||
rustfs_io_metrics::record_get_object_stage_duration_by_size(
|
||||
@@ -2987,8 +2987,9 @@ impl SetDisks {
|
||||
let frame_size = read_frame_size_for_file_info(fi, erasure)?;
|
||||
let checksum_algo = part_checksum_algorithm(fi, part_number);
|
||||
let use_mmap_read = object_mmap_read_enabled();
|
||||
let shard_size = erasure.shard_size();
|
||||
let till_offset = erasure.shard_file_offset(part_offset, part_length, part_size);
|
||||
let read_offset = (part_offset / erasure.block_size) * erasure.shard_size();
|
||||
let read_offset = (part_offset / erasure.block_size) * shard_size;
|
||||
let read_length = till_offset.saturating_sub(read_offset);
|
||||
|
||||
let stage_metrics_enabled = rustfs_io_metrics::get_stage_metrics_enabled();
|
||||
@@ -3008,7 +3009,7 @@ impl SetDisks {
|
||||
part_number,
|
||||
read_offset,
|
||||
read_length,
|
||||
erasure.shard_size(),
|
||||
shard_size,
|
||||
frame_size,
|
||||
checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
@@ -3030,7 +3031,14 @@ impl SetDisks {
|
||||
.iter()
|
||||
.find(|part| part.number == part_number)
|
||||
.and_then(|part| part.integrity.as_ref());
|
||||
reader_setup.bind_integrity(expected, files, disks, bucket, object, part_offset / erasure.block_size)?;
|
||||
reader_setup.bind_integrity(
|
||||
expected,
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
object,
|
||||
read_offset / shard_size..till_offset.div_ceil(shard_size),
|
||||
)?;
|
||||
record_get_stage_duration_if_enabled(metrics_path, GET_STAGE_READER_SETUP, reader_setup_stage_start);
|
||||
|
||||
let available_shards = reader_setup.available_shards();
|
||||
@@ -3482,7 +3490,14 @@ async fn setup_multipart_part_readers(
|
||||
)
|
||||
.await;
|
||||
if setup
|
||||
.bind_integrity(spec.integrity.as_ref(), files, disks, bucket, object, spec.read_offset / shard_size)
|
||||
.bind_integrity(
|
||||
spec.integrity.as_ref(),
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
object,
|
||||
spec.read_offset / shard_size..spec.read_offset.saturating_add(spec.read_length).div_ceil(shard_size),
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
setup = BitrotReaderSetup::new(disks.len());
|
||||
|
||||
@@ -169,21 +169,13 @@ impl SetDisks {
|
||||
.clone()
|
||||
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
|
||||
let version_id = expected.version_id.map(|v| v.to_string());
|
||||
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
opts.no_lock,
|
||||
DecommissionCapacityAdmission::Mutation,
|
||||
)
|
||||
.await?
|
||||
let decommission_object_lock_guard =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
} else {
|
||||
(None, false, None)
|
||||
None
|
||||
};
|
||||
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
|
||||
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
|
||||
Some(
|
||||
self.acquire_write_lock_diag("restore_finalize_metadata", bucket, object)
|
||||
.await?,
|
||||
@@ -191,15 +183,15 @@ impl SetDisks {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
Some(
|
||||
store
|
||||
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let read_opts = ObjectOptions {
|
||||
version_id,
|
||||
versioned: opts.versioned,
|
||||
@@ -286,21 +278,13 @@ impl SetDisks {
|
||||
.clone()
|
||||
.unwrap_or_else(|| get_raw_etag(obj_info.user_defined.as_ref()));
|
||||
let version_id = expected.version_id.map(|v| v.to_string());
|
||||
let (decommission_object_lock_guard, decommission_target_lock_covered, mut decommission_capacity_guard) =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
store
|
||||
.acquire_external_decommission_commit_guards(
|
||||
self.pool_index,
|
||||
bucket,
|
||||
object,
|
||||
opts.no_lock,
|
||||
DecommissionCapacityAdmission::Mutation,
|
||||
)
|
||||
.await?
|
||||
let decommission_object_lock_guard =
|
||||
if let Some(store) = opts.decommission_capacity_admission.as_ref().filter(|_| !opts.no_lock) {
|
||||
Some(store.acquire_external_commit_namespace(bucket, object, self).await?)
|
||||
} else {
|
||||
(None, false, None)
|
||||
None
|
||||
};
|
||||
let lock_guard = if !opts.no_lock && !decommission_target_lock_covered {
|
||||
let lock_guard = if !opts.no_lock && decommission_object_lock_guard.is_none() {
|
||||
Some(
|
||||
self.acquire_write_lock_diag("restore_cleanup_metadata", bucket, object)
|
||||
.await?,
|
||||
@@ -308,15 +292,15 @@ impl SetDisks {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if decommission_capacity_guard.is_none()
|
||||
&& let Some(store) = opts.decommission_capacity_admission.as_ref()
|
||||
{
|
||||
decommission_capacity_guard = Some(
|
||||
let decommission_capacity_guard = if let Some(store) = opts.decommission_capacity_admission.as_ref() {
|
||||
Some(
|
||||
store
|
||||
.acquire_external_decommission_capacity_fence(&[self.pool_index], DecommissionCapacityAdmission::Mutation)
|
||||
.await?,
|
||||
);
|
||||
}
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let read_opts = ObjectOptions {
|
||||
version_id,
|
||||
versioned: opts.versioned,
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
use super::ECStore;
|
||||
use crate::bucket::utils::is_meta_bucketname;
|
||||
use crate::disk::{DeleteRecoveryCursor, DiskAPI, DiskStore};
|
||||
use crate::disk::{DeleteTransactionId, Disk, DiskAPI, DiskStore, error::DiskError, local::DiscoverySession};
|
||||
use futures::{StreamExt, future::BoxFuture, stream::FuturesUnordered};
|
||||
use rand::RngExt as _;
|
||||
use rustfs_heal_contracts::heal_channel::HealOpts;
|
||||
@@ -29,13 +29,15 @@ use std::sync::{
|
||||
};
|
||||
use std::time::Duration;
|
||||
use tokio::time::{Instant, MissedTickBehavior};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
|
||||
use uuid::Uuid;
|
||||
|
||||
const HINT_CAPACITY: usize = 1_024;
|
||||
const DISCOVERY_PAGE_SIZE: u32 = 128;
|
||||
const PAGES_PER_PASS: usize = 8;
|
||||
const MAX_ACTIVE_DISCOVERY_CURSORS: usize = 32;
|
||||
const DISCOVERY_PAGE_WAIT: Duration = Duration::from_millis(100);
|
||||
const DISCOVERY_PAGE_STALL: Duration = Duration::from_secs(30);
|
||||
const LOG_COMPONENT_ECSTORE: &str = "ecstore";
|
||||
const LOG_SUBSYSTEM_DELETE_RECOVERY: &str = "delete_recovery";
|
||||
const EVENT_DELETE_RECOVERY_STATUS: &str = "delete_recovery_status";
|
||||
@@ -468,18 +470,50 @@ struct LocalSource {
|
||||
available: bool,
|
||||
}
|
||||
|
||||
impl LocalSource {
|
||||
fn same_disk(&self, other: &Self) -> bool {
|
||||
self.pool == other.pool && self.set == other.set && Arc::ptr_eq(&self.disk, &other.disk)
|
||||
}
|
||||
}
|
||||
|
||||
struct DiscoveryPage {
|
||||
incarnation: Uuid,
|
||||
transactions: Vec<DeleteTransactionId>,
|
||||
next: Option<DiscoverySession>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum BucketDiscovery {
|
||||
#[default]
|
||||
Unstarted,
|
||||
Paused(DiscoverySession),
|
||||
InFlight(BoxFuture<'static, crate::disk::error::Result<DiscoveryPage>>),
|
||||
}
|
||||
|
||||
struct BucketScan {
|
||||
bucket: String,
|
||||
incarnation: Option<Uuid>,
|
||||
cursor: Option<DeleteRecoveryCursor>,
|
||||
discovery: BucketDiscovery,
|
||||
pending: VecDeque<String>,
|
||||
}
|
||||
|
||||
impl BucketScan {
|
||||
fn has_progress(&self) -> bool {
|
||||
!matches!(self.discovery, BucketDiscovery::Unstarted) || !self.pending.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
struct DiskScan {
|
||||
source: LocalSource,
|
||||
buckets: Option<VecDeque<BucketScan>>,
|
||||
}
|
||||
|
||||
impl DiskScan {
|
||||
fn front_bucket(&self) -> Option<&BucketScan> {
|
||||
self.buckets.as_ref()?.front()
|
||||
}
|
||||
}
|
||||
|
||||
fn admit_discovered_keys(hints: &DeleteRecoveryHints, source: &LocalSource, bucket: &mut BucketScan) {
|
||||
while let Some(object) = bucket.pending.front() {
|
||||
if !hints.register_discovered(DeleteRecoveryKey {
|
||||
@@ -531,11 +565,8 @@ impl RecoveryPass {
|
||||
}
|
||||
}
|
||||
}
|
||||
let contains_source = |inventory: &[LocalSource], source: &LocalSource| {
|
||||
inventory.iter().any(|current| {
|
||||
current.pool == source.pool && current.set == source.set && Arc::ptr_eq(¤t.disk, &source.disk)
|
||||
})
|
||||
};
|
||||
let contains_source =
|
||||
|inventory: &[LocalSource], source: &LocalSource| inventory.iter().any(|current| current.same_disk(source));
|
||||
if sources.len() != self.sources.len() || self.sources.iter().any(|source| !contains_source(&sources, source)) {
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
@@ -547,12 +578,10 @@ impl RecoveryPass {
|
||||
.iter()
|
||||
.filter(|source| {
|
||||
source.available
|
||||
&& !self.sources.iter().any(|previous| {
|
||||
previous.available
|
||||
&& Arc::ptr_eq(&previous.disk, &source.disk)
|
||||
&& previous.pool == source.pool
|
||||
&& previous.set == source.set
|
||||
})
|
||||
&& !self
|
||||
.sources
|
||||
.iter()
|
||||
.any(|previous| previous.available && previous.same_disk(source))
|
||||
})
|
||||
.map(|source| (source.pool, source.set))
|
||||
.collect();
|
||||
@@ -567,42 +596,39 @@ impl RecoveryPass {
|
||||
fn defer(&mut self, mut scan: DiskScan) {
|
||||
if let Some(buckets) = scan.buckets.as_mut() {
|
||||
for bucket in buckets {
|
||||
bucket.cursor = None;
|
||||
bucket.discovery = BucketDiscovery::Unstarted;
|
||||
bucket.incarnation = None;
|
||||
}
|
||||
}
|
||||
let same_scope = |other: &DiskScan| {
|
||||
scan.source.pool == other.source.pool
|
||||
&& scan.source.set == other.source.set
|
||||
&& scan.source.disk.to_string() == other.source.disk.to_string()
|
||||
&& scan
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.bucket)
|
||||
== other
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.bucket)
|
||||
scan.source.same_disk(&other.source)
|
||||
&& scan.front_bucket().map(|bucket| &bucket.bucket) == other.front_bucket().map(|bucket| &bucket.bucket)
|
||||
};
|
||||
if let Some(failed) = scan.front_bucket() {
|
||||
// A full sweep may have listed this bucket before the retry failed.
|
||||
// Keep the failed scope's backoff for all still-unopened copies.
|
||||
self.scans.retain_mut(|queued| {
|
||||
if queued.source.same_disk(&scan.source)
|
||||
&& let Some(buckets) = queued.buckets.as_mut()
|
||||
{
|
||||
buckets.retain(|bucket| bucket.bucket != failed.bucket || bucket.has_progress());
|
||||
!buckets.is_empty()
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
if !self.deferred.iter().any(|(_, pending)| same_scope(pending)) {
|
||||
self.deferred.push_back((Instant::now() + INVENTORY_INTERVAL, scan));
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant) {
|
||||
async fn discover_page(&mut self, store: &Arc<ECStore>, deadline: Instant, cancel: &CancellationToken) {
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
let active_cursor = |scan: &DiskScan| {
|
||||
scan.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.is_some_and(|bucket| bucket.cursor.is_some() || !bucket.pending.is_empty())
|
||||
};
|
||||
let active_cursor = |scan: &DiskScan| scan.front_bucket().is_some_and(BucketScan::has_progress);
|
||||
if self.scans.iter().filter(|scan| active_cursor(scan)).count() >= MAX_ACTIVE_DISCOVERY_CURSORS {
|
||||
// Keep room for exact-key recovery and other discovery callers in
|
||||
// the disk API's bounded session table. Finish existing cursors
|
||||
// before starting another bucket; queued sources retain their place.
|
||||
// Bound the number of directory stacks we keep open while rotating
|
||||
// across disks. Finish existing walks before opening another bucket.
|
||||
if let Some(index) = self.scans.iter().position(active_cursor) {
|
||||
self.scans.rotate_left(index);
|
||||
}
|
||||
@@ -611,14 +637,28 @@ impl RecoveryPass {
|
||||
if scan.buckets.is_none() {
|
||||
match tokio::time::timeout_at(deadline, scan.source.disk.list_volumes()).await {
|
||||
Ok(Ok(volumes)) => {
|
||||
// A retry that has yet to open its bucket can cover the full
|
||||
// scope for this generation, without bypassing its backoff.
|
||||
let unopened_retries: HashSet<_> = self
|
||||
.scans
|
||||
.iter()
|
||||
.chain(self.deferred.iter().map(|(_, retry)| retry))
|
||||
.filter(|retry| retry.source.same_disk(&scan.source))
|
||||
.filter_map(|retry| retry.buckets.as_ref())
|
||||
.flatten()
|
||||
.filter(|bucket| !bucket.has_progress())
|
||||
.map(|bucket| bucket.bucket.as_str())
|
||||
.collect();
|
||||
scan.buckets = Some(
|
||||
volumes
|
||||
.into_iter()
|
||||
.filter(|volume| !is_meta_bucketname(&volume.name))
|
||||
.filter(|volume| {
|
||||
!is_meta_bucketname(&volume.name) && !unopened_retries.contains(volume.name.as_str())
|
||||
})
|
||||
.map(|volume| BucketScan {
|
||||
bucket: volume.name,
|
||||
incarnation: None,
|
||||
cursor: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
})
|
||||
.collect(),
|
||||
@@ -634,7 +674,7 @@ impl RecoveryPass {
|
||||
{
|
||||
let had_pending = !bucket.pending.is_empty();
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if !bucket.pending.is_empty() || (had_pending && bucket.cursor.is_none()) {
|
||||
if !bucket.pending.is_empty() || (had_pending && matches!(bucket.discovery, BucketDiscovery::Unstarted)) {
|
||||
if !bucket.pending.is_empty() {
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
@@ -643,47 +683,104 @@ impl RecoveryPass {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if bucket.incarnation.is_none() {
|
||||
match tokio::time::timeout_at(deadline, store.bucket_incarnation_id_from_disk(&bucket.bucket)).await {
|
||||
Ok(Ok(incarnation)) => bucket.incarnation = Some(incarnation),
|
||||
_ => {
|
||||
// Finish an older cursor before the new sweep revisits that
|
||||
// bucket. A different bucket may proceed once the disk is idle.
|
||||
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_))
|
||||
&& self
|
||||
.scans
|
||||
.iter()
|
||||
.filter(|other| other.source.same_disk(&scan.source))
|
||||
.filter_map(DiskScan::front_bucket)
|
||||
.any(|other| {
|
||||
matches!(other.discovery, BucketDiscovery::InFlight(_))
|
||||
|| (!bucket.has_progress() && other.bucket == bucket.bucket && other.has_progress())
|
||||
})
|
||||
{
|
||||
buckets.push_front(bucket);
|
||||
self.scans.push_back(scan);
|
||||
return;
|
||||
}
|
||||
if !matches!(bucket.discovery, BucketDiscovery::InFlight(_)) {
|
||||
let store = Arc::clone(store);
|
||||
let incarnation = bucket.incarnation;
|
||||
let disk = Arc::clone(&scan.source.disk);
|
||||
let volume = bucket.bucket.clone();
|
||||
let cancel = cancel.child_token();
|
||||
let session = match std::mem::take(&mut bucket.discovery) {
|
||||
BucketDiscovery::Paused(session) => Some(session),
|
||||
_ => None,
|
||||
};
|
||||
bucket.discovery = BucketDiscovery::InFlight(Box::pin(async move {
|
||||
let _cancel_on_drop = cancel.clone().drop_guard();
|
||||
let (volume, incarnation) = match incarnation {
|
||||
Some(incarnation) => (volume, incarnation),
|
||||
None => {
|
||||
// Finish the quorum read and release its metadata guard even
|
||||
// while the discovery scheduler is polling other disks.
|
||||
let lookup = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let incarnation =
|
||||
tokio::time::timeout(DISCOVERY_BUDGET, store.bucket_incarnation_id_from_disk(&volume))
|
||||
.await
|
||||
.map_err(|_| DiskError::Timeout)?
|
||||
.map_err(DiskError::other)?;
|
||||
Ok::<_, DiskError>((volume, incarnation))
|
||||
}));
|
||||
lookup.await.map_err(DiskError::other)??
|
||||
}
|
||||
};
|
||||
// A stalled disk must not prevent later sweeps on healthy disks.
|
||||
let (transactions, next) = tokio::time::timeout(DISCOVERY_PAGE_STALL, async move {
|
||||
match disk.as_ref() {
|
||||
Disk::Local(local) => {
|
||||
local
|
||||
.advance_background_delete_discovery(volume, session, DISCOVERY_PAGE_SIZE, cancel)
|
||||
.await
|
||||
}
|
||||
#[cfg(feature = "dst")]
|
||||
Disk::Sim(sim) => sim
|
||||
.discover_delete_transactions(&volume, None, None, DISCOVERY_PAGE_SIZE)
|
||||
.await
|
||||
.map(|page| (page.transactions, None)),
|
||||
Disk::Remote(_) => Err(DiskError::DiskNotFound),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| DiskError::Timeout)??;
|
||||
Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions,
|
||||
next,
|
||||
})
|
||||
}));
|
||||
}
|
||||
if let BucketDiscovery::InFlight(page) = &mut bucket.discovery {
|
||||
let wait_until = deadline.min(Instant::now() + DISCOVERY_PAGE_WAIT);
|
||||
match tokio::time::timeout_at(wait_until, page.as_mut()).await {
|
||||
Ok(Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions,
|
||||
next,
|
||||
})) => {
|
||||
bucket.incarnation = Some(incarnation);
|
||||
bucket.pending = transactions.into_iter().map(|transaction| transaction.object).collect();
|
||||
bucket.discovery = next.map_or(BucketDiscovery::Unstarted, BucketDiscovery::Paused);
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if !matches!(bucket.discovery, BucketDiscovery::Unstarted) || !bucket.pending.is_empty() {
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
self.defer(DiskScan {
|
||||
source: scan.source.clone(),
|
||||
buckets: Some(VecDeque::from([bucket])),
|
||||
});
|
||||
if !buckets.is_empty() {
|
||||
self.scans.push_back(scan);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
match tokio::time::timeout_at(
|
||||
deadline,
|
||||
scan.source
|
||||
.disk
|
||||
.discover_delete_transactions(&bucket.bucket, None, bucket.cursor.take(), DISCOVERY_PAGE_SIZE),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(page)) => {
|
||||
bucket.pending = page.transactions.into_iter().map(|transaction| transaction.object).collect();
|
||||
bucket.cursor = page.next;
|
||||
admit_discovered_keys(hints, &scan.source, &mut bucket);
|
||||
if bucket.cursor.is_some() || !bucket.pending.is_empty() {
|
||||
// Keep one bounded page until its keys are admitted;
|
||||
// unopened buckets cannot displace its continuation.
|
||||
Err(_) => {
|
||||
// Native calls can run past a scheduling window. Poll the
|
||||
// same page next time, including any evidence it has found.
|
||||
buckets.push_front(bucket);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Retry only this source, never a full healthy tree
|
||||
// because another disk is offline or a cursor expired.
|
||||
self.defer(DiskScan {
|
||||
source: scan.source.clone(),
|
||||
buckets: Some(VecDeque::from([bucket])),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if scan.buckets.as_ref().is_some_and(|buckets| !buckets.is_empty()) {
|
||||
@@ -699,24 +796,6 @@ impl RecoveryPass {
|
||||
}
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
// Renew only this worker's bounded local cursors before any await.
|
||||
// Backpressure and a slow canonical rollback must not erase progress.
|
||||
for scan in &mut self.scans {
|
||||
if let Some(bucket) = scan.buckets.as_mut().and_then(|buckets| buckets.front_mut())
|
||||
&& let Some(cursor) = bucket.cursor.as_ref()
|
||||
{
|
||||
let renewed = match scan.source.disk.as_ref() {
|
||||
crate::disk::Disk::Local(local) => local.get_disk().renew_delete_recovery_cursor(&bucket.bucket, cursor),
|
||||
crate::disk::Disk::Remote(_) => false,
|
||||
#[cfg(feature = "dst")]
|
||||
crate::disk::Disk::Sim(_) => false,
|
||||
};
|
||||
if !renewed {
|
||||
bucket.cursor = None;
|
||||
hints.request_rescan();
|
||||
}
|
||||
}
|
||||
}
|
||||
let discovery_deadline = Instant::now() + DISCOVERY_BUDGET;
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
@@ -731,12 +810,21 @@ impl RecoveryPass {
|
||||
}
|
||||
if let Some(generation) = hints.rescan() {
|
||||
self.scan_generation = Some(generation);
|
||||
self.scans = self
|
||||
.sources
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|source| DiskScan { source, buckets: None })
|
||||
.collect();
|
||||
// A due retry may already have a live page even though the
|
||||
// previous full sweep completed. Keep it ahead of fresh work.
|
||||
for source in &self.sources {
|
||||
let inventory_queued = self
|
||||
.scans
|
||||
.iter()
|
||||
.chain(self.deferred.iter().map(|(_, retry)| retry))
|
||||
.any(|scan| scan.buckets.is_none() && scan.source.same_disk(source));
|
||||
if !inventory_queued {
|
||||
self.scans.push_back(DiskScan {
|
||||
source: source.clone(),
|
||||
buckets: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _ in 0..self.deferred.len() {
|
||||
@@ -753,7 +841,7 @@ impl RecoveryPass {
|
||||
}
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => return,
|
||||
_ = self.discover_page(store, discovery_deadline) => {}
|
||||
_ = self.discover_page(store, discovery_deadline, cancel) => {}
|
||||
}
|
||||
}
|
||||
if self.scans.is_empty()
|
||||
@@ -1538,6 +1626,180 @@ mod tests {
|
||||
assert!(pass.scans.is_empty());
|
||||
assert!(store.ctx.delete_recovery_hints().rescan().is_none());
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_slow_bucket_identity_does_not_block_other_disks() {
|
||||
let healthy = "runtime-healthy-identity";
|
||||
let blocked = "runtime-blocked-identity";
|
||||
let (_dirs, store, disks) = fixture(healthy).await;
|
||||
store
|
||||
.make_bucket(blocked, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create second bucket");
|
||||
prepare(&store, &disks, healthy).await;
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(healthy)
|
||||
.await
|
||||
.expect("healthy bucket incarnation");
|
||||
let writer = crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked)
|
||||
.await
|
||||
.expect("hold the blocked bucket's metadata write lock");
|
||||
let key = DeleteRecoveryKey {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
bucket: healthy.to_owned(),
|
||||
object: "object".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.scans
|
||||
.extend([blocked, healthy].into_iter().enumerate().map(|(index, bucket)| DiskScan {
|
||||
source: LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[index].clone(),
|
||||
available: true,
|
||||
},
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
}));
|
||||
let cancel = CancellationToken::new();
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
assert!(!hints.is_pending(&key), "the key must be discovered by the healthy scan");
|
||||
tokio::time::timeout(Duration::from_secs(2), pass.discover(&store, &cancel))
|
||||
.await
|
||||
.expect("identity lookup yields to independent disk work");
|
||||
|
||||
assert!(hints.is_pending(&key), "the healthy disk discovers its journal while metadata is locked");
|
||||
assert!(pass.deferred.is_empty(), "the scheduler keeps the waiting page");
|
||||
assert!(matches!(
|
||||
pass.scans.front().and_then(DiskScan::front_bucket),
|
||||
Some(BucketScan { bucket, discovery: BucketDiscovery::InFlight(_), .. }) if bucket == blocked
|
||||
));
|
||||
|
||||
drop(writer);
|
||||
let writer = tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
crate::bucket::metadata_sys::acquire_bucket_metadata_transaction_lock_in(&store.ctx, blocked),
|
||||
)
|
||||
.await
|
||||
.expect("the parked discovery page must not keep the metadata guard held")
|
||||
.expect("reacquire the bucket's metadata write lock");
|
||||
drop(writer);
|
||||
pass.discover(&store, &cancel).await;
|
||||
assert!(pass.scans.is_empty(), "the original identity lookup resumes through the native page");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_rescan_keeps_an_inflight_retry_page() {
|
||||
let bucket = "runtime-rescan-retry";
|
||||
let (_dirs, store, disks) = fixture(bucket).await;
|
||||
let source = LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[0].clone(),
|
||||
available: true,
|
||||
};
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(bucket)
|
||||
.await
|
||||
.expect("bucket incarnation");
|
||||
let discovered = DeleteRecoveryKey {
|
||||
pool: source.pool,
|
||||
set: source.set,
|
||||
bucket: bucket.to_owned(),
|
||||
object: "found-in-retry".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.sources.push(source.clone());
|
||||
pass.scans.push_back(DiskScan {
|
||||
source,
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
discovery: BucketDiscovery::InFlight(Box::pin(std::future::ready(Ok(DiscoveryPage {
|
||||
incarnation,
|
||||
transactions: vec![DeleteTransactionId {
|
||||
object: discovered.object.clone(),
|
||||
transaction: Uuid::new_v4(),
|
||||
}],
|
||||
next: None,
|
||||
})))),
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
pass.discover(&store, &CancellationToken::new()).await;
|
||||
|
||||
assert!(hints.is_pending(&discovered), "a fresh sweep must admit the in-flight retry result");
|
||||
assert!(pass.scans.is_empty(), "the fresh sweep also completes");
|
||||
assert!(hints.rescan().is_none(), "the new generation is acknowledged");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_rescan_respects_the_retry_backoff() {
|
||||
let bucket = "runtime-rescan-backoff";
|
||||
let (_dirs, store, disks) = fixture(bucket).await;
|
||||
prepare(&store, &disks, bucket).await;
|
||||
let source = LocalSource {
|
||||
pool: 0,
|
||||
set: 0,
|
||||
disk: disks[0].clone(),
|
||||
available: true,
|
||||
};
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(bucket)
|
||||
.await
|
||||
.expect("bucket incarnation");
|
||||
let discovered = DeleteRecoveryKey {
|
||||
pool: source.pool,
|
||||
set: source.set,
|
||||
bucket: bucket.to_owned(),
|
||||
object: "object".to_owned(),
|
||||
incarnation: Some(incarnation),
|
||||
};
|
||||
let mut pass = hint_only_pass(&store);
|
||||
pass.sources.push(source.clone());
|
||||
pass.scans.push_back(DiskScan {
|
||||
source: source.clone(),
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
pass.defer(DiskScan {
|
||||
source,
|
||||
buckets: Some(VecDeque::from([BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}])),
|
||||
});
|
||||
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
let cancel = CancellationToken::new();
|
||||
pass.discover(&store, &cancel).await;
|
||||
|
||||
assert!(!hints.is_pending(&discovered), "the full sweep must not bypass the bucket retry");
|
||||
assert!(hints.rescan().is_none(), "the deferred bucket does not block the full sweep");
|
||||
let (ready, _) = pass.deferred.front_mut().expect("pending bucket retry");
|
||||
*ready = Instant::now();
|
||||
pass.discover(&store, &cancel).await;
|
||||
|
||||
assert!(hints.is_pending(&discovered), "the due retry still reads the hidden preparation");
|
||||
assert!(pass.deferred.is_empty(), "the retry settled its discovery obligation");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_blocked_capacity_yields_until_periodic_sweep() {
|
||||
let (_dirs, store, _disks) = fixture("runtime-blocked-sweep").await;
|
||||
@@ -1962,6 +2224,24 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_continues_current_bucket_before_opening_later_buckets() {
|
||||
async fn finish_page(pass: &mut RecoveryPass, store: &Arc<ECStore>, cancel: &CancellationToken) {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
assert!(Instant::now() < deadline, "discovery page did not return");
|
||||
pass.discover_page(store, deadline, cancel).await;
|
||||
if !matches!(
|
||||
pass.scans
|
||||
.front()
|
||||
.and_then(|scan| scan.buckets.as_ref())
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.discovery),
|
||||
Some(BucketDiscovery::InFlight(_))
|
||||
) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let bucket = "runtime-cursor-progress";
|
||||
let (dirs, store, disks) = fixture(bucket).await;
|
||||
let other = "runtime-after-large";
|
||||
@@ -1983,11 +2263,12 @@ mod tests {
|
||||
buckets: Some(VecDeque::from([bucket, other].map(|bucket| BucketScan {
|
||||
bucket: bucket.to_owned(),
|
||||
incarnation: None,
|
||||
cursor: None,
|
||||
discovery: BucketDiscovery::Unstarted,
|
||||
pending: VecDeque::new(),
|
||||
}))),
|
||||
});
|
||||
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
|
||||
let cancel = CancellationToken::new();
|
||||
finish_page(&mut pass, &store, &cancel).await;
|
||||
let first = pass.scans[0]
|
||||
.buckets
|
||||
.as_ref()
|
||||
@@ -1995,8 +2276,44 @@ mod tests {
|
||||
.front()
|
||||
.expect("current bucket");
|
||||
assert_eq!(first.bucket, bucket);
|
||||
assert!(first.cursor.is_some(), "raw entry budget must leave a continuation");
|
||||
pass.discover_page(&store, Instant::now() + Duration::from_secs(30)).await;
|
||||
assert!(
|
||||
matches!(first.discovery, BucketDiscovery::Paused(_)),
|
||||
"raw entry budget must leave a continuation"
|
||||
);
|
||||
let Disk::Local(local) = disks[0].as_ref() else {
|
||||
panic!("expected a local drive");
|
||||
};
|
||||
let lease = local
|
||||
.get_disk()
|
||||
.lock_delete_discovery_bucket(bucket)
|
||||
.await
|
||||
.expect("hold bucket lease");
|
||||
pass.discover_page(&store, Instant::now(), &cancel).await;
|
||||
assert!(
|
||||
pass.deferred.is_empty(),
|
||||
"the scheduling deadline must not discard a page waiting on the disk"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
pass.scans[0]
|
||||
.buckets
|
||||
.as_ref()
|
||||
.and_then(|buckets| buckets.front())
|
||||
.map(|bucket| &bucket.discovery),
|
||||
Some(BucketDiscovery::InFlight(_))
|
||||
),
|
||||
"the original page and its continuation stay owned across the deadline"
|
||||
);
|
||||
let volumes = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
crate::disk::with_background_disk_io(cancel.clone(), local.list_volumes()),
|
||||
)
|
||||
.await
|
||||
.expect("another background operation can use the disk while discovery waits for its bucket lease")
|
||||
.expect("list volumes under background admission");
|
||||
assert!(volumes.iter().any(|volume| volume.name == other));
|
||||
drop(lease);
|
||||
finish_page(&mut pass, &store, &cancel).await;
|
||||
assert_eq!(
|
||||
pass.scans[0]
|
||||
.buckets
|
||||
@@ -2008,5 +2325,25 @@ mod tests {
|
||||
other,
|
||||
"the second page completes instead of cycling through unopened buckets"
|
||||
);
|
||||
let hints = store.ctx.delete_recovery_hints();
|
||||
hints.request_rescan();
|
||||
pass.scan_generation = Some(hints.rescan().expect("scan obligation before the stall"));
|
||||
let incarnation = store
|
||||
.bucket_incarnation_id_from_disk(other)
|
||||
.await
|
||||
.expect("source incarnation");
|
||||
pass.scans[0].buckets.as_mut().expect("open inventory")[0].incarnation = Some(incarnation);
|
||||
let _lease = local
|
||||
.get_disk()
|
||||
.lock_delete_discovery_bucket(other)
|
||||
.await
|
||||
.expect("hold bucket lease");
|
||||
tokio::time::pause();
|
||||
pass.discover_page(&store, Instant::now(), &cancel).await;
|
||||
tokio::time::advance(DISCOVERY_PAGE_STALL).await;
|
||||
pass.next_inventory = Some(Instant::now() + INVENTORY_INTERVAL);
|
||||
pass.discover(&store, &cancel).await;
|
||||
assert_eq!(pass.deferred.len(), 1, "a genuinely stalled source is deferred");
|
||||
assert!(pass.scan_generation.is_none(), "the stall cannot pin subsequent sweeps");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -592,6 +592,53 @@ impl ECStore {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Check whether an unversioned MRF target is absent from its original set.
|
||||
/// A true result requires every configured drive and no pending delete recovery.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if storage cannot establish identity, locks, or complete reads.
|
||||
pub async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
|
||||
) -> Result<bool> {
|
||||
use rustfs_common::mrf_channel::MrfKind;
|
||||
|
||||
let (Some(scope), None, MrfKind::PartialWrite) = (anchor.scope, anchor.version_id, anchor.kind) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let bucket = anchor.bucket.as_ref();
|
||||
let object = anchor.object.as_ref();
|
||||
if anchor.bucket_incarnation_id.is_nil()
|
||||
|| self.ctx.lock_manager().is_disabled()
|
||||
|| super::utils::is_reserved_or_invalid_bucket(bucket, false)
|
||||
|| object.ends_with('/')
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let pool_index = scope.pool_index as usize;
|
||||
let set_index = scope.set_index as usize;
|
||||
let opts = HealOpts {
|
||||
pool: Some(pool_index),
|
||||
set: Some(set_index),
|
||||
..Default::default()
|
||||
};
|
||||
let bucket_guard = self
|
||||
.acquire_bucket_incarnation_fence(bucket, anchor.bucket_incarnation_id)
|
||||
.await?;
|
||||
let pool = self
|
||||
.pools
|
||||
.get(pool_index)
|
||||
.ok_or_else(|| invalid_heal_pool_index(pool_index, self.pools.len()))?;
|
||||
if self.pool_meta.read().await.is_suspended(pool_index) {
|
||||
return Ok(false);
|
||||
}
|
||||
let set = pool.get_disks_for_heal_object(object, &opts)?;
|
||||
let capacity_store = (!self.single_pool()).then_some(self);
|
||||
let absent = set.probe_mrf_unversioned_absence(bucket, object, capacity_store).await?;
|
||||
self.validate_bucket_incarnation_fence(&bucket_guard, bucket)?;
|
||||
Ok(absent)
|
||||
}
|
||||
|
||||
async fn acquire_heal_format_fence(
|
||||
&self,
|
||||
) -> Result<(
|
||||
@@ -1453,24 +1500,10 @@ impl ECStore {
|
||||
Err(err) => vec![Err(err)],
|
||||
}
|
||||
} else {
|
||||
let mut futures = Vec::with_capacity(heal_pools.len());
|
||||
for pool in heal_pools {
|
||||
let pool_idx = pool.pool_idx;
|
||||
let pool_object = object.clone();
|
||||
let opts = *opts;
|
||||
futures.push(self.run_external_decommission_capacity_heal(
|
||||
pool_idx,
|
||||
bucket,
|
||||
&object,
|
||||
opts,
|
||||
move |opts| async move {
|
||||
#[cfg(test)]
|
||||
crate::core::pools::notify_decommission_external_heal_operation_started(store_id);
|
||||
pool.heal_object_with_absence(bucket, &pool_object, version_id, &opts, proof)
|
||||
.await
|
||||
},
|
||||
));
|
||||
}
|
||||
let capacity_store = (!self.single_pool()).then_some(self);
|
||||
let futures = heal_pools
|
||||
.iter()
|
||||
.map(|pool| pool.heal_object_with_absence(bucket, &object, version_id, opts, proof, capacity_store));
|
||||
join_all(futures).await
|
||||
};
|
||||
|
||||
@@ -1524,7 +1557,7 @@ impl ECStore {
|
||||
version_id
|
||||
};
|
||||
let (before, error, absence) = pool
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
|
||||
.await?;
|
||||
let target = pool.get_disks_for_heal_object(POOL_META_NAME, opts)?;
|
||||
let owns_replica = Arc::ptr_eq(&target, &pool.get_disks_by_key(POOL_META_NAME));
|
||||
@@ -1543,7 +1576,7 @@ impl ECStore {
|
||||
return Ok((before, Some(error), None));
|
||||
}
|
||||
let (mut after, error, _) = pool
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof)
|
||||
.heal_object_with_absence(RUSTFS_META_BUCKET, POOL_META_NAME, version, &inspect_opts, proof, None)
|
||||
.await?;
|
||||
after.before = before.before;
|
||||
if guard.is_lock_lost() {
|
||||
|
||||
@@ -6119,6 +6119,351 @@ mod tests {
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
async fn stage_multipart_on_first_pool(
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
bytes: &[u8],
|
||||
opts: &ObjectOptions,
|
||||
) -> (String, Vec<crate::storage_api_contracts::multipart::CompletePart>) {
|
||||
use crate::storage_api_contracts::multipart::CompletePart;
|
||||
|
||||
let pool = &store.pools[0];
|
||||
let upload = pool
|
||||
.new_multipart_upload(bucket, key, opts)
|
||||
.await
|
||||
.expect("stage upload in pool 0");
|
||||
let part = pool
|
||||
.put_object_part(bucket, key, &upload.upload_id, 1, &mut PutObjReader::from_vec(bytes.to_vec()), opts)
|
||||
.await
|
||||
.expect("stage the part");
|
||||
(
|
||||
upload.upload_id,
|
||||
vec![CompletePart {
|
||||
part_num: part.part_num,
|
||||
etag: part.etag,
|
||||
..Default::default()
|
||||
}],
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
async fn seed_multipart_predecessors(
|
||||
store: &crate::store::ECStore,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
named_predecessor: bool,
|
||||
) -> (ObjectInfo, ObjectInfo) {
|
||||
store
|
||||
.make_bucket(bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create bucket");
|
||||
store
|
||||
.update_bucket_metadata_config(
|
||||
bucket,
|
||||
crate::bucket::metadata::OBJECT_LOCK_CONFIG,
|
||||
b"<ObjectLockConfiguration><ObjectLockEnabled>Enabled</ObjectLockEnabled></ObjectLockConfiguration>".to_vec(),
|
||||
)
|
||||
.await
|
||||
.expect("enable Object Lock");
|
||||
let peer = &store.pools[1];
|
||||
let old = peer
|
||||
.put_object(
|
||||
bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(vec![1; 20]),
|
||||
&ObjectOptions {
|
||||
versioned: named_predecessor,
|
||||
user_defined: HashMap::from([(
|
||||
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
|
||||
"ON".to_owned(),
|
||||
)]),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write protected predecessor in pool 1");
|
||||
let head = peer
|
||||
.put_object(
|
||||
bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(vec![2; 10]),
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write a newer unprotected version in pool 1");
|
||||
(old, head)
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn unconditional_multipart_checks_the_historical_null_for_object_lock_and_quota() {
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-null-predecessor", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("mpu-null-{}", Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, false).await;
|
||||
let mut opts = ObjectOptions {
|
||||
version_suspended: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(opts.set_quota_admission(30, 30));
|
||||
let (upload, parts) = stage_multipart_on_first_pool(&store, &bucket, key, &[3; 20], &opts).await;
|
||||
let denied = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &opts)
|
||||
.await
|
||||
.expect_err("the historical null is under legal hold in pool 1");
|
||||
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
|
||||
let null = ObjectOptions {
|
||||
version_id: Some(Uuid::nil().to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
store.pools[1]
|
||||
.get_object_info(&bucket, key, &null)
|
||||
.await
|
||||
.expect("preserved null")
|
||||
.etag,
|
||||
old.etag
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("unchanged head")
|
||||
.version_id,
|
||||
head.version_id
|
||||
);
|
||||
store.pools[1]
|
||||
.get_disks_by_key(key)
|
||||
.put_object_metadata(
|
||||
&bucket,
|
||||
key,
|
||||
&ObjectOptions {
|
||||
eval_metadata: Some(HashMap::from([(
|
||||
rustfs_filemeta::metadata_keys::OBJECT_LOCK_LEGAL_HOLD.to_string(),
|
||||
"OFF".to_owned(),
|
||||
)])),
|
||||
..null
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("release the legal hold on the historical null");
|
||||
let completed = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &opts)
|
||||
.await
|
||||
.expect("retry the same upload and replace 20 bytes in a full bucket");
|
||||
assert!(completed.version_id.is_none_or(|id| id.is_nil()));
|
||||
assert_ne!(completed.etag, old.etag);
|
||||
assert!(completed.mod_time > head.mod_time);
|
||||
assert_eq!(completed.put_usage.expect("replacement usage").replaced_size(), 20);
|
||||
assert_eq!(
|
||||
store.pools[1]
|
||||
.get_object_info(
|
||||
&bucket,
|
||||
key,
|
||||
&ObjectOptions {
|
||||
version_id: Some(head.version_id.expect("named head").to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.expect("preserved named version")
|
||||
.etag,
|
||||
head.etag
|
||||
);
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn multipart_reads_remote_history_only_for_an_explicit_named_replacement() {
|
||||
use crate::disk::lifecycle_test_io::Observer;
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "mpu-named-predecessor", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("mpu-named-{}", Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
let (old, head) = seed_multipart_predecessors(&store, &bucket, key, true).await;
|
||||
let old_id = old.version_id.expect("named predecessor");
|
||||
let opts = ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (explicit, explicit_parts) = stage_multipart_on_first_pool(
|
||||
&store,
|
||||
&bucket,
|
||||
key,
|
||||
b"replace the retained version",
|
||||
&ObjectOptions {
|
||||
version_id: Some(old_id.to_string()),
|
||||
..opts.clone()
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let (fresh, fresh_parts) = stage_multipart_on_first_pool(&store, &bucket, key, b"new version", &opts).await;
|
||||
let reads = Observer::new(&bucket);
|
||||
let condition = ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: Some(head.etag.expect("current ETag")),
|
||||
..Default::default()
|
||||
}),
|
||||
..opts.clone()
|
||||
};
|
||||
let completed = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &fresh, fresh_parts, &condition)
|
||||
.await
|
||||
.expect("publish a fresh named version beside a retained historical version");
|
||||
let id = completed.version_id.expect("fresh UUID");
|
||||
assert_ne!(id, old_id);
|
||||
assert_ne!(Some(id), head.version_id);
|
||||
assert_eq!(completed.put_usage.expect("usage for fresh version").replaced_size(), 0);
|
||||
assert!(
|
||||
reads.snapshot().reads.iter().all(|name| name != key),
|
||||
"a live head proves a fresh version appends without reading the complete history"
|
||||
);
|
||||
let denied = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &explicit, explicit_parts, &opts)
|
||||
.await
|
||||
.expect_err("the version requested at initiation remains protected");
|
||||
assert!(matches!(denied, StorageError::PrefixAccessDenied(_, _)));
|
||||
assert!(
|
||||
reads.snapshot().reads.iter().any(|name| name == key),
|
||||
"an explicit historical replacement must be located before publication"
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("preserved fresh head")
|
||||
.version_id,
|
||||
Some(id)
|
||||
);
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
async fn conditional_multipart_matches_the_current_pool_and_rechecks_concurrent_writes() {
|
||||
use crate::set_disk::{MultipartCommitBarrier, MultipartCommitPause};
|
||||
use crate::storage_api_contracts::object::HTTPPreconditions;
|
||||
|
||||
let if_match = |info: &ObjectInfo| ObjectOptions {
|
||||
http_preconditions: Some(HTTPPreconditions {
|
||||
if_match: Some(info.etag.clone().expect("object ETag")),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let dirs = tempfile::tempdir().expect("store directory");
|
||||
let (_ctx, store, shutdown) =
|
||||
without_storage_class_env(build_isolated_test_store(dirs.path(), "conditional-mpu-writes", &[4, 4])).await;
|
||||
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
|
||||
let bucket = format!("conditional-mpu-{}", uuid::Uuid::new_v4().simple());
|
||||
let key = "object";
|
||||
store
|
||||
.make_bucket(&bucket, &MakeBucketOptions::default())
|
||||
.await
|
||||
.expect("create bucket");
|
||||
let write_peer = async |body: &[u8], mod_time| {
|
||||
store.pools[1]
|
||||
.put_object(
|
||||
&bucket,
|
||||
key,
|
||||
&mut PutObjReader::from_vec(body.to_vec()),
|
||||
&ObjectOptions {
|
||||
mod_time: Some(mod_time),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("write on the other pool")
|
||||
};
|
||||
let future_time = OffsetDateTime::now_utc() + time::Duration::hours(1);
|
||||
let existing = write_peer(b"old", future_time).await;
|
||||
let (upload, parts) =
|
||||
stage_multipart_on_first_pool(&store, &bucket, key, b"first completion", &ObjectOptions::default()).await;
|
||||
let first = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&existing))
|
||||
.await
|
||||
.expect("match the object in pool 1 and publish the upload in pool 0");
|
||||
assert!(first.mod_time > existing.mod_time);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("current completion")
|
||||
.etag,
|
||||
first.etag
|
||||
);
|
||||
|
||||
let (upload, parts) =
|
||||
stage_multipart_on_first_pool(&store, &bucket, key, b"retryable completion", &ObjectOptions::default()).await;
|
||||
let paused = MultipartCommitBarrier::install(&bucket, key, MultipartCommitPause::BeforeConditionalNamespace);
|
||||
let complete = tokio::spawn({
|
||||
let (store, bucket, upload, parts, condition) =
|
||||
(store.clone(), bucket.clone(), upload.clone(), parts.clone(), if_match(&first));
|
||||
async move {
|
||||
store
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &condition)
|
||||
.await
|
||||
}
|
||||
});
|
||||
paused.wait_until_paused().await;
|
||||
let winner = write_peer(b"concurrent write", future_time + time::Duration::seconds(1)).await;
|
||||
drop(paused);
|
||||
assert_eq!(
|
||||
complete
|
||||
.await
|
||||
.expect("completion task")
|
||||
.expect_err("the concurrent write changed the current ETag"),
|
||||
StorageError::PreconditionFailed
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_object_info(&bucket, key, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("concurrent winner")
|
||||
.etag,
|
||||
winner.etag
|
||||
);
|
||||
let retry = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts.clone(), &if_match(&winner))
|
||||
.await
|
||||
.expect("retry the same staged upload with the current ETag");
|
||||
assert!(retry.mod_time > winner.mod_time);
|
||||
let replay = store
|
||||
.clone()
|
||||
.complete_multipart_upload(&bucket, key, &upload, parts, &if_match(&retry))
|
||||
.await
|
||||
.expect("a matching condition may replay the published upload");
|
||||
assert!(replay.multipart_completion_replayed);
|
||||
assert_eq!(replay.data_dir, retry.data_dir);
|
||||
assert!(replay.put_usage.is_none());
|
||||
shutdown.cancel();
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(storage_class_env)]
|
||||
|
||||
@@ -1438,19 +1438,7 @@ impl ECStore {
|
||||
.acquire_object_read_lock_if_needed("lifecycle_versions", bucket, &disk_object, &mut opts)
|
||||
.await?;
|
||||
|
||||
// As with version listings, include every physical set: migration can
|
||||
// leave a key's history in more than its current hash destination.
|
||||
let reads = self
|
||||
.pools
|
||||
.iter()
|
||||
.flat_map(|pool| &pool.disk_set)
|
||||
.map(|set| set.read_object_versions_for_lifecycle(bucket, object));
|
||||
let mut entries = Vec::new();
|
||||
for result in join_all(reads).await {
|
||||
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
let versions = self.read_object_version_history(bucket, object, &[]).await?;
|
||||
if self.pools.is_empty()
|
||||
|| bucket_guard.as_ref().is_some_and(|guard| guard.is_lock_lost())
|
||||
|| opts
|
||||
@@ -1462,6 +1450,34 @@ impl ECStore {
|
||||
{
|
||||
return Err(Error::PreconditionFailed);
|
||||
}
|
||||
let versioned = versioning.versioned(object);
|
||||
Ok(versions
|
||||
.iter()
|
||||
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(super) async fn read_object_version_history(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
retired: &[usize],
|
||||
) -> Result<Vec<rustfs_filemeta::FileInfo>> {
|
||||
// As with version listings, include every physical set: migration can
|
||||
// leave a key's history in more than its current hash destination.
|
||||
let reads = self
|
||||
.pools
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| !retired.contains(index))
|
||||
.flat_map(|(_, pool)| &pool.disk_set)
|
||||
.map(|set| set.read_object_version_history(bucket, object));
|
||||
let mut entries = Vec::new();
|
||||
for result in join_all(reads).await {
|
||||
if let Some(entry) = result.map_err(|error| to_object_err(error.into(), vec![bucket, object]))? {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
let mut entries = entries.into_iter();
|
||||
let Some(mut entry) = entries.next() else {
|
||||
return Ok(Vec::new());
|
||||
@@ -1469,15 +1485,7 @@ impl ECStore {
|
||||
if entries.len() > 0 {
|
||||
merge_object_entry_versions(&mut entry, entries, log_listing_merge_corruption)?;
|
||||
}
|
||||
// This projection excludes tier free-version bookkeeping but retains
|
||||
// pending version purges for the evaluator's replication safeguards.
|
||||
let versions = entry.file_info_versions(bucket)?;
|
||||
let versioned = versioning.versioned(object);
|
||||
Ok(versions
|
||||
.versions
|
||||
.iter()
|
||||
.map(|version| ObjectInfo::from_file_info(version, bucket, object, versioned))
|
||||
.collect())
|
||||
Ok(entry.file_info_versions(bucket)?.versions)
|
||||
}
|
||||
|
||||
async fn inner_list_object_versions_with_projection(
|
||||
@@ -1572,6 +1580,18 @@ impl ECStore {
|
||||
})
|
||||
}
|
||||
|
||||
fn list_read_fanout(&self) -> usize {
|
||||
self.pools.iter().fold(0usize, |total, pool| {
|
||||
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the local budget can fit one full listing walk at the time of sampling.
|
||||
/// Returns `None` until a listing walk initializes the budget.
|
||||
pub fn list_read_budget_has_capacity(&self) -> Option<bool> {
|
||||
self.ctx.list_read_budget_has_capacity(self.list_read_fanout())
|
||||
}
|
||||
|
||||
pub async fn list_path(self: Arc<Self>, o: &ListPathOptions) -> Result<ListPage> {
|
||||
// tracing::warn!("list_path opt {:?}", &o);
|
||||
|
||||
@@ -1625,10 +1645,11 @@ impl ECStore {
|
||||
if o.transient {
|
||||
o.create = false;
|
||||
}
|
||||
let fanout = self.pools.iter().fold(0usize, |total, pool| {
|
||||
total.saturating_add(pool.disk_set.len().saturating_mul(pool.set_drive_count))
|
||||
});
|
||||
o.read_budget = self.ctx.acquire_list_read_budget(fanout).await.map_err(Error::other)?;
|
||||
o.read_budget = self
|
||||
.ctx
|
||||
.acquire_list_read_budget(self.list_read_fanout())
|
||||
.await
|
||||
.map_err(Error::other)?;
|
||||
|
||||
let log_context = ListPathLogContext::from_options(&o);
|
||||
|
||||
@@ -2716,7 +2737,7 @@ fn merge_object_entry_versions(
|
||||
let equivalent = if info.delete_marker && previous_info.delete_marker {
|
||||
super::object::is_equivalent_data_movement_delete_marker(&info, previous_info)
|
||||
} else {
|
||||
crate::data_movement::is_equivalent_data_movement_object_identity(&info, previous_info, true, true)
|
||||
crate::data_movement::equivalent_listed_object_versions(&info, previous_info)
|
||||
};
|
||||
if !equivalent {
|
||||
return Err(corrupt("version_identity_conflict"));
|
||||
@@ -9085,7 +9106,15 @@ mod test {
|
||||
let first = test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 4, 2)]);
|
||||
let second = rewrite_test_version(
|
||||
test_object_meta_entry_with_erasure_versions("key", &[(time, "same-etag", 6, 2)]),
|
||||
|version| version.object.as_mut().expect("object version").data_dir = Some(Uuid::from_u128(42)),
|
||||
|version| {
|
||||
let object = version.object.as_mut().expect("object version");
|
||||
let original = object.data_dir.replace(Uuid::from_u128(42)).expect("source data directory");
|
||||
rustfs_utils::http::insert_bytes(
|
||||
&mut object.meta_sys,
|
||||
crate::object_api::LOGICAL_BODY_REVISION_SUFFIX,
|
||||
original.to_string().into_bytes(),
|
||||
);
|
||||
},
|
||||
);
|
||||
let forward = merge_test_object_entries(vec![first.clone(), second.clone()])
|
||||
.await
|
||||
|
||||
@@ -217,6 +217,33 @@ async fn lifecycle_exact_matches_listing_for_complete_version_groups() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_usage_counts_live_versions_hidden_by_a_current_marker() {
|
||||
let (dirs, store, bucket, _) = fixture(2).await;
|
||||
let key = "masked";
|
||||
let marker = FileInfo {
|
||||
name: key.into(),
|
||||
deleted: true,
|
||||
mod_time: Some(OffsetDateTime::from_unix_timestamp(1_700_000_001).expect("marker timestamp")),
|
||||
..Default::default()
|
||||
};
|
||||
seed(&dirs[..4], &bucket, key, std::slice::from_ref(&marker)).await;
|
||||
let current = ObjectInfo::from_file_info(&marker, &bucket, key, true);
|
||||
for had_live_version in [false, true] {
|
||||
if had_live_version {
|
||||
seed(&dirs[4..], &bucket, key, &[version(key, Some(Uuid::new_v4()), 1_700_000_000)]).await;
|
||||
}
|
||||
let previous = store
|
||||
.resolve_put_predecessors(&bucket, key, &ObjectOptions::default(), Some(current.clone()), Some(Uuid::nil()))
|
||||
.await
|
||||
.expect("resolve all live versions under the marker");
|
||||
assert_eq!(
|
||||
previous.usage_receipt().expect("version usage"),
|
||||
crate::data_usage::PutUsageReceipt::from_predecessors(had_live_version, Some(¤t)).expect("fixture usage")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lifecycle_exact_merges_pools_and_more_than_one_page_of_versions() {
|
||||
let (dirs, store, bucket, incarnation) = fixture(2).await;
|
||||
|
||||
@@ -712,7 +712,7 @@ impl ECStore {
|
||||
}
|
||||
if opts.http_preconditions.is_some()
|
||||
&& !opts.data_movement
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, &opts, false).await
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, &opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
@@ -1340,32 +1340,12 @@ impl ECStore {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn check_write_precondition(
|
||||
&self,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
opts: &ObjectOptions,
|
||||
require_all_pools: bool,
|
||||
) -> Option<StorageError> {
|
||||
async fn check_write_precondition(&self, bucket: &str, object: &str, opts: &ObjectOptions) -> Option<StorageError> {
|
||||
let mut lookup_opts = opts.clone();
|
||||
let http_preconditions = lookup_opts.http_preconditions?;
|
||||
lookup_opts.http_preconditions = None;
|
||||
lookup_opts.no_lock = true;
|
||||
let oi = if require_all_pools {
|
||||
lookup_opts.metadata_cache_safe = false;
|
||||
lookup_opts.metadata_cache_fence_proof = None;
|
||||
lookup_opts.suppress_read_repair = true;
|
||||
// Only completion uses this branch, after validating bucket and object.
|
||||
let encoded_object = encode_dir_object_ref(object);
|
||||
self.get_latest_object_info_for_conditional_write(bucket, encoded_object.as_ref(), &lookup_opts)
|
||||
.await
|
||||
.and_then(|(info, _)| {
|
||||
lookup_opts.precondition_check(&info)?;
|
||||
Ok(info)
|
||||
})
|
||||
} else {
|
||||
self.get_object_info_for_delete(bucket, object, &lookup_opts).await
|
||||
};
|
||||
let oi = self.get_object_info_for_delete(bucket, object, &lookup_opts).await;
|
||||
crate::set_disk::SetDisks::evaluate_write_precondition(oi, &http_preconditions, bucket, object, opts)
|
||||
}
|
||||
|
||||
@@ -1421,33 +1401,36 @@ impl ECStore {
|
||||
.await;
|
||||
return enqueue_transition_after_write(self.as_ref(), result, LcEventSrc::S3CompleteMultipartUpload, opts).await;
|
||||
}
|
||||
if opts.http_preconditions.is_some() && !opts.data_movement {
|
||||
// Preserve explicitly scoped internal reads and borrowed-lock callers.
|
||||
let require_all_pools =
|
||||
!opts.replication_request && !opts.no_lock && !opts.skip_decommissioned && !opts.skip_rebalancing;
|
||||
if let Some(err) = self.check_write_precondition(bucket, object, opts, require_all_pools).await {
|
||||
return Err(err);
|
||||
}
|
||||
let multipool_store = (!opts.skip_decommissioned
|
||||
&& !opts.skip_rebalancing
|
||||
&& !opts.restore_copyback
|
||||
&& !opts.is_inbound_multipart_replica()
|
||||
&& self.uses_multipool_put_commit(bucket, object, opts).await?)
|
||||
.then_some(self.as_ref());
|
||||
if multipool_store.is_none()
|
||||
&& opts.http_preconditions.is_some()
|
||||
&& !opts.data_movement
|
||||
&& let Some(err) = self.check_write_precondition(bucket, object, opts).await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let result = match self.multipart_upload_pool_idx(bucket, object, upload_id, opts).await {
|
||||
Ok(pool_idx) => {
|
||||
let complete = |pool_idx: usize, parts| {
|
||||
Box::pin(
|
||||
self.pools[pool_idx]
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts, opts)
|
||||
.await
|
||||
}
|
||||
.get_disks_by_key(object)
|
||||
.complete_multipart_upload_with_store(bucket, object, upload_id, parts, opts, multipool_store),
|
||||
)
|
||||
};
|
||||
let result = match self.multipart_upload_pool_idx(bucket, object, upload_id, opts).await {
|
||||
Ok(pool_idx) => complete(pool_idx, uploaded_parts).await,
|
||||
// The staging upload is already gone. The completed object lives on
|
||||
// the pool that published it; other pools answer InvalidUploadID.
|
||||
Err(err) if is_err_invalid_upload_id(&err) => {
|
||||
let mut missing = err;
|
||||
let mut found = None;
|
||||
for pool_idx in self.existing_multipart_pool_order().await {
|
||||
match self.pools[pool_idx]
|
||||
.clone()
|
||||
.complete_multipart_upload(bucket, object, upload_id, uploaded_parts.clone(), opts)
|
||||
.await
|
||||
{
|
||||
match complete(pool_idx, uploaded_parts.clone()).await {
|
||||
Ok(info) => {
|
||||
found = Some(Ok(info));
|
||||
break;
|
||||
|
||||
+1248
-200
File diff suppressed because it is too large
Load Diff
@@ -876,6 +876,25 @@ impl ECStore {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Completed sources have passed the terminal empty-pool verification and can
|
||||
/// be removed from the deployment. Active, failed and canceled sources remain readable.
|
||||
pub(super) async fn completed_decommission_pools(&self) -> Vec<usize> {
|
||||
self.pool_meta
|
||||
.read()
|
||||
.await
|
||||
.pools
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, status)| {
|
||||
status
|
||||
.decommission
|
||||
.as_ref()
|
||||
.filter(|info| info.complete && !info.failed && !info.canceled && info.unresolved_entries.is_empty())
|
||||
.map(|_| idx)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Observe every pool for a conditional-write preflight. This does not
|
||||
/// hold the namespace locks needed to prove a condition at publication.
|
||||
pub(super) async fn get_latest_object_info_for_conditional_write(
|
||||
@@ -904,9 +923,14 @@ impl ECStore {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let completed = if require_all_pools && !is_meta_bucketname(bucket) {
|
||||
self.completed_decommission_pools().await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut futures = Vec::with_capacity(self.pools.len());
|
||||
for (idx, pool) in self.pools.iter().enumerate() {
|
||||
if suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
|
||||
if completed.contains(&idx) || suspended_pools.as_ref().is_some_and(|pools| pools[idx]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ use thiserror::Error;
|
||||
use super::heal::{DiskError, EcstoreError, storage_api::owner::EcstorePoolMetadataFailure};
|
||||
|
||||
const HEAL_DANGLING_DELETE_GRACE_MESSAGE: &str = "dangling object deletion deferred by heal grace window";
|
||||
pub(crate) const MRF_MISSING_PROOF_PREFIX: &str = "Missing exact storage proof for durable MRF repair ";
|
||||
|
||||
/// Custom error type for heal operations
|
||||
/// This enum defines various error variants that can occur during
|
||||
@@ -57,6 +56,10 @@ pub enum Error {
|
||||
#[error("Heal task execution failed: {message}")]
|
||||
TaskExecutionFailed { message: String },
|
||||
|
||||
/// The storage result could not authorize discharge of a durable partial write.
|
||||
#[error("Missing exact storage proof for durable MRF repair {target}: {reason}")]
|
||||
MrfStorageProofUnavailable { target: String, reason: &'static str },
|
||||
|
||||
/// Only the qualified MRF Deep check may produce this terminal result.
|
||||
#[error("Independent verification unavailable for legacy object {target}; durable MRF responsibility retained")]
|
||||
LegacyMrfUnverified { target: String },
|
||||
@@ -239,11 +242,10 @@ pub(crate) fn classify_heal_error(error: &Error) -> HealErrorClass {
|
||||
| Error::ReplacementNamespaceChanged
|
||||
| Error::TransientSkip { .. }
|
||||
| Error::BucketDiscoveryIncomplete => HealErrorClass::Transient,
|
||||
Error::LegacyMrfUnverified { .. } => HealErrorClass::Permanent,
|
||||
Error::LegacyMrfUnverified { .. } | Error::MrfStorageProofUnavailable { .. } => HealErrorClass::Permanent,
|
||||
Error::Storage(error) => classify_storage_error(error),
|
||||
Error::Disk(error) => classify_disk_error(error),
|
||||
Error::Io(error) => classify_io_error(error),
|
||||
Error::TaskExecutionFailed { message } if message.starts_with(MRF_MISSING_PROOF_PREFIX) => HealErrorClass::Permanent,
|
||||
Error::TaskExecutionFailed { message } | Error::Other(message) => {
|
||||
classify_error_display(message).unwrap_or(HealErrorClass::Permanent)
|
||||
}
|
||||
|
||||
@@ -2317,6 +2317,13 @@ impl HealManager {
|
||||
self.storage.mrf_bucket_incarnation_retired(bucket, expected).await
|
||||
}
|
||||
|
||||
pub(super) async fn probe_mrf_unversioned_absence(
|
||||
&self,
|
||||
anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor,
|
||||
) -> Result<bool> {
|
||||
self.storage.probe_mrf_unversioned_absence(anchor).await
|
||||
}
|
||||
|
||||
async fn submit_heal_request_with_receipt_alias_and_mrf_notice(
|
||||
&self,
|
||||
mut request: HealRequest,
|
||||
|
||||
@@ -2176,6 +2176,10 @@ fn only_typed_mrf_result_can_pause_unverified_legacy() {
|
||||
Err(Error::TaskExecutionFailed {
|
||||
message: "Missing exact storage proof for durable MRF repair display only".to_owned(),
|
||||
}),
|
||||
Err(Error::MrfStorageProofUnavailable {
|
||||
target: "file not found".to_owned(),
|
||||
reason: "storage receipt did not verify the requested identity and disposition",
|
||||
}),
|
||||
Err(Error::TaskCancelled),
|
||||
Err(Error::TaskTimeout),
|
||||
] {
|
||||
|
||||
@@ -57,6 +57,9 @@ use partial_write::{PartialWrites, ResponsibilityCheckpoint};
|
||||
|
||||
const MRF_LIFECYCLE_CONTROL_CAPACITY: usize = 128;
|
||||
const MRF_JOURNAL_DISK_CONCURRENCY: usize = 4;
|
||||
const MRF_HELD_ABSENCE_PROBE_INTERVAL: Duration = Duration::from_secs(1);
|
||||
const MRF_HELD_ABSENCE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const MRF_LIFECYCLE_LIST_MAX_LIMIT: usize = 256;
|
||||
|
||||
static GLOBAL_MRF_LIFECYCLE_SENDER: std::sync::OnceLock<mpsc::Sender<MrfLifecycleCommand>> = std::sync::OnceLock::new();
|
||||
@@ -1035,6 +1038,29 @@ async fn submit_mrf_heal_request(
|
||||
Ok(receipt.result)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
struct MrfCheckpointRecords {
|
||||
authoritative: Vec<u8>,
|
||||
legacy: Vec<u8>,
|
||||
lifecycle: Vec<ResponsibilityCheckpoint>,
|
||||
}
|
||||
|
||||
impl MrfCheckpointRecords {
|
||||
fn append(&mut self, intent: &MrfIntent) -> Option<&[u8]> {
|
||||
let start = self.authoritative.len();
|
||||
if !encode_intent(intent, &mut self.authoritative) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
return None;
|
||||
}
|
||||
let encoded = &self.authoritative[start..];
|
||||
if intent.kind == MrfKind::MetadataCorruption || intent.scope.is_none() {
|
||||
self.legacy.extend_from_slice(encoded);
|
||||
}
|
||||
Some(encoded)
|
||||
}
|
||||
}
|
||||
|
||||
struct MrfRuntime {
|
||||
queue: MrfQueue,
|
||||
partial_writes: PartialWrites,
|
||||
@@ -1410,20 +1436,17 @@ impl MrfRuntime {
|
||||
self.publish_metrics();
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> (Vec<u8>, Vec<u8>) {
|
||||
let mut authoritative = Vec::new();
|
||||
let mut legacy = Vec::new();
|
||||
for intent in self.queue.intents().chain(self.partial_writes.intents()) {
|
||||
let scoped_identity =
|
||||
!matches!(intent.kind, rustfs_common::mrf_channel::MrfKind::MetadataCorruption) && intent.scope.is_some();
|
||||
if !encode_intent(intent, &mut authoritative) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
}
|
||||
if !scoped_identity && !encode_intent(intent, &mut legacy) {
|
||||
counter!("rustfs_heal_mrf_dropped_total", "reason" => "journal_identity_oversized").increment(1);
|
||||
}
|
||||
fn snapshot(&self) -> MrfCheckpointRecords {
|
||||
let mut snapshot = MrfCheckpointRecords::default();
|
||||
for intent in self.queue.intents() {
|
||||
let _ = snapshot.append(intent);
|
||||
}
|
||||
(authoritative, legacy)
|
||||
// Bind the lifecycle record to the exact published bytes, including
|
||||
// the record CRC, without running the codec a second time.
|
||||
snapshot.lifecycle = self
|
||||
.partial_writes
|
||||
.checkpoint_records(|intent| snapshot.append(intent).map(|bytes| sha2::Sha256::digest(bytes).into()));
|
||||
snapshot
|
||||
}
|
||||
|
||||
async fn flush(&mut self) -> bool {
|
||||
@@ -1435,29 +1458,31 @@ impl MrfRuntime {
|
||||
if self.partial_writes.pending_lifecycle_transition.is_some() {
|
||||
return self.flush_pending_lifecycle(None).await;
|
||||
}
|
||||
let (authoritative, legacy) = self.snapshot();
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle,
|
||||
} = self.snapshot();
|
||||
if lifecycle.len() != self.partial_writes.depth() {
|
||||
return false;
|
||||
}
|
||||
let lifecycle_byte_limit = self.config.journal_max_bytes.saturating_mul(4);
|
||||
let lifecycle_checkpoint = if self.partial_writes.depth() == 0 {
|
||||
let lifecycle_checkpoint = if lifecycle.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let records = self.partial_writes.checkpoint_records(intent_digest);
|
||||
(records.len() == self.partial_writes.depth())
|
||||
.then(|| {
|
||||
encode_mrf_lifecycle_checkpoint(
|
||||
self.lifecycle_format_version,
|
||||
self.checkpoint_owner,
|
||||
self.next_checkpoint_sequence,
|
||||
records,
|
||||
lifecycle_byte_limit,
|
||||
)
|
||||
})
|
||||
.flatten()
|
||||
let Some(checkpoint) = encode_mrf_lifecycle_checkpoint(
|
||||
self.lifecycle_format_version,
|
||||
self.checkpoint_owner,
|
||||
self.next_checkpoint_sequence,
|
||||
lifecycle,
|
||||
lifecycle_byte_limit,
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
Some(checkpoint)
|
||||
};
|
||||
let lifecycle_ready = self.partial_writes.depth() == 0 || lifecycle_checkpoint.is_some();
|
||||
let (committed_persisted, committed_on_disk) = if authoritative.is_empty() {
|
||||
(true, false)
|
||||
} else if !lifecycle_ready {
|
||||
(false, false)
|
||||
} else {
|
||||
match snapshot::publish_committed_snapshot_with_companion(
|
||||
&journal_disks().await,
|
||||
@@ -1487,14 +1512,8 @@ impl MrfRuntime {
|
||||
}
|
||||
}
|
||||
};
|
||||
self.finish_flush(
|
||||
&authoritative,
|
||||
&legacy,
|
||||
committed_persisted,
|
||||
committed_on_disk,
|
||||
lifecycle_checkpoint.is_some(),
|
||||
)
|
||||
.await
|
||||
self.finish_flush(&authoritative, &legacy, committed_persisted, committed_on_disk)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn pending_lifecycle_commit_matches(
|
||||
@@ -1541,7 +1560,14 @@ impl MrfRuntime {
|
||||
.clamp(Duration::from_secs(5), Duration::from_secs(60));
|
||||
let intent = pending.intent.clone();
|
||||
let record = pending.record.clone();
|
||||
let mut records = self.partial_writes.checkpoint_records(intent_digest);
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle: mut records,
|
||||
} = self.snapshot();
|
||||
if records.len() != self.partial_writes.depth() {
|
||||
return false;
|
||||
}
|
||||
let Some(current) = records.iter_mut().find(|current| {
|
||||
current.responsibility_id == record.responsibility_id && current.intent_digest == record.intent_digest
|
||||
}) else {
|
||||
@@ -1563,15 +1589,14 @@ impl MrfRuntime {
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let (authoritative, legacy) = self.snapshot();
|
||||
// A lost publication result must not regenerate the body or downgrade
|
||||
// the owner. An exact committed readback resolves it without new writes.
|
||||
let already_committed = match self.pending_lifecycle_commit_matches(&authoritative, &lifecycle).await {
|
||||
Ok(committed) => committed,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let (authoritative, lifecycle) = if already_committed {
|
||||
(authoritative, lifecycle)
|
||||
let authoritative = if already_committed {
|
||||
authoritative
|
||||
} else {
|
||||
let proof = match proof {
|
||||
Some(proof) => proof,
|
||||
@@ -1636,7 +1661,7 @@ impl MrfRuntime {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
(authoritative, lifecycle)
|
||||
authoritative
|
||||
};
|
||||
if !self.partial_writes.restore_state(&intent, &record) {
|
||||
return false;
|
||||
@@ -1647,8 +1672,7 @@ impl MrfRuntime {
|
||||
self.next_checkpoint_sequence = self.next_checkpoint_sequence.saturating_add(1);
|
||||
self.journal_on_disk = true;
|
||||
self.dirty = true;
|
||||
self.finish_flush(&authoritative, &legacy, true, true, !lifecycle.is_empty())
|
||||
.await
|
||||
self.finish_flush(&authoritative, &legacy, true, true).await
|
||||
}
|
||||
|
||||
async fn finish_flush(
|
||||
@@ -1657,7 +1681,6 @@ impl MrfRuntime {
|
||||
legacy: &[u8],
|
||||
committed_persisted: bool,
|
||||
committed_on_disk: bool,
|
||||
lifecycle_ready: bool,
|
||||
) -> bool {
|
||||
let authoritative_persisted = write_journal(MRF_SCOPED_JOURNAL_PATH, authoritative).await;
|
||||
if !authoritative.is_empty() {
|
||||
@@ -1676,7 +1699,7 @@ impl MrfRuntime {
|
||||
}
|
||||
all_deleted
|
||||
} else {
|
||||
lifecycle_ready && committed_persisted
|
||||
committed_persisted
|
||||
};
|
||||
// Keep dirty until the committed checkpoint, authoritative snapshot,
|
||||
// and compatibility mirror have all been accepted; otherwise a
|
||||
@@ -1851,22 +1874,20 @@ impl MrfRuntime {
|
||||
.chain(self.partial_writes.anchors())
|
||||
.cloned()
|
||||
.collect();
|
||||
let mut buckets: Vec<Arc<str>> = anchors.iter().map(|anchor| anchor.bucket.clone()).collect();
|
||||
buckets.sort_unstable();
|
||||
buckets.dedup();
|
||||
for bucket in &buckets {
|
||||
rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events_for(bucket.as_ref(), &mut anchors);
|
||||
let buckets = anchors.iter().map(|anchor| anchor.bucket.as_ref()).collect();
|
||||
let legacy = rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for_buckets(&buckets);
|
||||
if rustfs_common::mrf_channel::consume_recorded_verified_mrf_repair_events(&mut anchors) != 0 {
|
||||
let remaining: HashSet<_> = anchors.into_iter().collect();
|
||||
let previous_replay_anchor_count = self.durable_replay_anchors.len();
|
||||
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
|
||||
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
|
||||
let partial_writes_changed = self.partial_writes.retain_unproven(&remaining);
|
||||
self.dirty |= replay_anchors_changed || partial_writes_changed;
|
||||
}
|
||||
let remaining: HashSet<_> = anchors.into_iter().collect();
|
||||
let previous_replay_anchor_count = self.durable_replay_anchors.len();
|
||||
self.durable_replay_anchors.retain(|anchor| remaining.contains(anchor));
|
||||
let replay_anchors_changed = self.durable_replay_anchors.len() != previous_replay_anchor_count;
|
||||
self.dirty |= replay_anchors_changed || self.partial_writes.retain_unproven(&remaining);
|
||||
for bucket in buckets {
|
||||
for event in rustfs_common::mrf_channel::take_mrf_unverified_legacy_events_for(bucket.as_ref()) {
|
||||
if self.partial_writes.park_unverified_legacy(&event.anchor) {
|
||||
self.dirty = true;
|
||||
}
|
||||
// Exact discharge takes precedence over held notices from this batch.
|
||||
for event in legacy {
|
||||
if self.partial_writes.park_unverified_legacy(&event.anchor) {
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
self.publish_metrics();
|
||||
@@ -2389,6 +2410,9 @@ async fn run_mrf_consumer_with_stop(
|
||||
flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let mut batch: Vec<MrfIntent> = Vec::with_capacity(runtime.config.replay_batch);
|
||||
let mut durable_batch = Vec::with_capacity(runtime.config.replay_batch);
|
||||
let mut held_probe = tokio::task::JoinSet::new();
|
||||
let mut retirement_probe = tokio::task::JoinSet::new();
|
||||
let mut next_held_probe = tokio::time::Instant::now();
|
||||
|
||||
loop {
|
||||
if stop.as_ref().is_some_and(tokio_util::sync::CancellationToken::is_cancelled) {
|
||||
@@ -2504,8 +2528,61 @@ async fn run_mrf_consumer_with_stop(
|
||||
runtime.flush().await;
|
||||
}
|
||||
}
|
||||
Some(result) = retirement_probe.join_next(), if !retirement_probe.is_empty() => {
|
||||
let result = match result {
|
||||
Ok((generation, Ok(Ok(true)))) => {
|
||||
runtime.partial_writes.note_bucket_retired(&generation);
|
||||
"proved"
|
||||
}
|
||||
Ok((_, Ok(Ok(false)))) => "retained",
|
||||
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
|
||||
Ok((_, Err(_))) => "timed_out",
|
||||
};
|
||||
counter!("rustfs_heal_mrf_bucket_retirement_probe_total", "result" => result).increment(1);
|
||||
}
|
||||
Some(result) = held_probe.join_next(), if !held_probe.is_empty() => {
|
||||
let result = match result {
|
||||
Ok((anchor, Ok(Ok(true)))) => {
|
||||
if runtime.partial_writes.note_held_absence_proof(anchor) {
|
||||
"proved"
|
||||
} else {
|
||||
"superseded"
|
||||
}
|
||||
}
|
||||
Ok((_, Ok(Ok(false)))) => "retained",
|
||||
Ok((_, Ok(Err(_)))) | Err(_) => "unavailable",
|
||||
Ok((_, Err(_))) => "timed_out",
|
||||
};
|
||||
counter!("rustfs_heal_mrf_held_absence_probe_total", "result" => result).increment(1);
|
||||
}
|
||||
_ = flush_tick.tick() => {
|
||||
runtime.partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
|
||||
let now = tokio::time::Instant::now();
|
||||
let can_probe = runtime.replay_readable && held_probe.is_empty() && now >= next_held_probe;
|
||||
let (retirement, held) = runtime.partial_writes.plan_maintenance(
|
||||
runtime.replay_readable && retirement_probe.is_empty(),
|
||||
can_probe,
|
||||
);
|
||||
if let Some(generation) = retirement {
|
||||
let manager = manager.clone();
|
||||
retirement_probe.spawn(async move {
|
||||
let outcome = tokio::time::timeout(
|
||||
MRF_BUCKET_RETIREMENT_PROBE_TIMEOUT,
|
||||
manager.mrf_bucket_incarnation_retired(&generation.0, generation.1),
|
||||
).await;
|
||||
(generation, outcome)
|
||||
});
|
||||
}
|
||||
if let Some(anchor) = held {
|
||||
next_held_probe = tokio::time::Instant::now() + MRF_HELD_ABSENCE_PROBE_INTERVAL;
|
||||
let manager = manager.clone();
|
||||
held_probe.spawn(async move {
|
||||
let outcome = tokio::time::timeout(
|
||||
MRF_HELD_ABSENCE_PROBE_TIMEOUT,
|
||||
manager.probe_mrf_unversioned_absence(&anchor),
|
||||
).await;
|
||||
(anchor, outcome)
|
||||
});
|
||||
}
|
||||
runtime.discharge_durable_replay_anchors();
|
||||
match tick_action(
|
||||
runtime.dirty,
|
||||
@@ -3163,7 +3240,11 @@ mod tests {
|
||||
backoff_until: None,
|
||||
};
|
||||
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
|
||||
let (authoritative, legacy_mirror) = runtime.snapshot();
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy: legacy_mirror,
|
||||
..
|
||||
} = runtime.snapshot();
|
||||
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
|
||||
let (legacy_mirror_decoded, legacy_mirror_truncated) = decode_journal(&legacy_mirror);
|
||||
assert_eq!(authoritative_truncated, 0, "W13 authoritative scoped mirror must decode cleanly");
|
||||
@@ -4285,10 +4366,24 @@ mod tests {
|
||||
runtime_checkpoint: None,
|
||||
backoff_until: None,
|
||||
};
|
||||
assert_eq!(runtime.queue.try_push_typed(scoped.clone()), MrfQueuePushResult::Enqueued);
|
||||
runtime
|
||||
.admit_partial_write(scoped.clone(), Some(Uuid::new_v4()))
|
||||
.expect("admit scoped responsibility");
|
||||
assert_eq!(runtime.queue.try_push_typed(compat.clone()), MrfQueuePushResult::Enqueued);
|
||||
|
||||
let (authoritative, legacy) = runtime.snapshot();
|
||||
let MrfCheckpointRecords {
|
||||
authoritative,
|
||||
legacy,
|
||||
lifecycle,
|
||||
} = runtime.snapshot();
|
||||
let plain_bytes = encoded_payload(&compat);
|
||||
let scoped_bytes = encoded_payload(&scoped);
|
||||
assert_eq!(legacy, plain_bytes, "mirror reuses the exact unscoped bytes");
|
||||
assert_eq!(authoritative, [plain_bytes, scoped_bytes].concat());
|
||||
let (_, consumed) = decode_one(&authoritative).expect("decode first record");
|
||||
let durable_digest: [u8; 32] = sha2::Sha256::digest(&authoritative[consumed..]).into();
|
||||
assert_eq!(lifecycle.len(), 1);
|
||||
assert_eq!(lifecycle[0].intent_digest, durable_digest);
|
||||
let (authoritative_decoded, authoritative_truncated) = decode_journal(&authoritative);
|
||||
assert_eq!(authoritative_truncated, 0);
|
||||
assert_eq!(authoritative_decoded.len(), 2);
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
use super::{
|
||||
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfLegacyRiskAcceptanceRequest, MrfQueueKey, queue_key,
|
||||
submit_mrf_heal_request,
|
||||
HealManager, MrfConsumerConfig, MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfLegacyRiskAcceptanceRequest, MrfQueueKey,
|
||||
queue_key, submit_mrf_heal_request,
|
||||
};
|
||||
use rustfs_common::mrf_channel::{
|
||||
MrfDurableAdmissionError, MrfIngressResult, MrfVerifiedRepairDisposition, MrfVerifiedRepairEvent, release_mrf_intent,
|
||||
@@ -22,7 +22,7 @@ use rustfs_common::mrf_channel::{
|
||||
};
|
||||
use rustfs_heal_contracts::heal_channel::HealAdmissionResult;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque, hash_map::Entry};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::time::Instant;
|
||||
@@ -34,7 +34,11 @@ const MAX_OPERATOR_REFERENCE_BYTES: usize = 256;
|
||||
const LIFECYCLE_CHECKPOINT_RECORD_OVERHEAD_BYTES: usize = 256;
|
||||
const MAX_UNVERIFIED_RETRY_BACKOFF: Duration = Duration::from_secs(60);
|
||||
const MRF_RETIREMENT_PROOF_RECHECK_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const MRF_HELD_ABSENCE_RECHECK_INTERVAL: Duration = Duration::from_secs(60);
|
||||
const MRF_IDENTITY_PROBE_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
const MRF_DISPATCH_IDENTITY_START_BUDGET: Duration = Duration::from_secs(1);
|
||||
|
||||
pub(super) type BucketGeneration = (Arc<str>, Uuid);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
struct PartialWriteKey {
|
||||
@@ -291,7 +295,7 @@ pub(super) struct PartialWrites {
|
||||
retry_index: HashSet<PartialWriteKey>,
|
||||
identity_probe_order: VecDeque<PartialWriteKey>,
|
||||
identity_probe_index: HashSet<PartialWriteKey>,
|
||||
retirement_checks: HashMap<(Arc<str>, Uuid), (Instant, bool)>,
|
||||
retirement_checks: HashMap<BucketGeneration, (Instant, bool)>,
|
||||
unresolved_generation_candidate: Option<PartialWriteKey>,
|
||||
pub(super) pending_lifecycle_transition: Option<PendingLifecycleTransition>,
|
||||
bytes: usize,
|
||||
@@ -412,67 +416,104 @@ impl PartialWrites {
|
||||
self.entries.values().filter_map(|entry| entry.anchor.as_ref())
|
||||
}
|
||||
|
||||
pub(super) async fn note_retired_generation_proofs(&mut self, manager: &HealManager) {
|
||||
let mut intents_by_generation: HashMap<(Arc<str>, Uuid), Vec<&MrfIntent>> = HashMap::new();
|
||||
for entry in self.entries.values() {
|
||||
pub(super) fn plan_maintenance(
|
||||
&mut self,
|
||||
probe_retirement: bool,
|
||||
probe_held: bool,
|
||||
) -> (Option<BucketGeneration>, Option<MrfDurableRepairAnchor>) {
|
||||
let now = Instant::now();
|
||||
let mut due_generation = None;
|
||||
let mut held = None;
|
||||
let mut generations = HashMap::new();
|
||||
for (key, entry) in &mut self.entries {
|
||||
if !entry.persisted {
|
||||
continue;
|
||||
}
|
||||
let Some(source_incarnation) = entry.source_bucket_incarnation_id else {
|
||||
let Some(source) = entry.source_bucket_incarnation_id else {
|
||||
continue;
|
||||
};
|
||||
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source_incarnation) {
|
||||
if !MrfDurableRepairAnchor::is_eligible_for_source(&entry.intent, source) {
|
||||
continue;
|
||||
}
|
||||
intents_by_generation
|
||||
.entry((entry.intent.bucket.clone(), source_incarnation))
|
||||
.or_default()
|
||||
.push(&entry.intent);
|
||||
let bucket = &entry.intent.bucket;
|
||||
let retirement = match generations.entry((bucket.as_ref(), source)) {
|
||||
Entry::Occupied(previous) => previous.into_mut(),
|
||||
Entry::Vacant(generation) => {
|
||||
let (next, retired) = *self.retirement_checks.entry((bucket.clone(), source)).or_insert((now, false));
|
||||
if probe_retirement
|
||||
&& !retired
|
||||
&& next <= now
|
||||
&& due_generation.as_ref().is_none_or(|(_, _, due)| next < *due)
|
||||
{
|
||||
due_generation = Some((bucket.clone(), source, next));
|
||||
}
|
||||
generation.insert(retired.then(Vec::new))
|
||||
}
|
||||
};
|
||||
if let Some(anchors) = retirement {
|
||||
if let Some(anchor) = MrfDurableRepairAnchor::from_intent(&entry.intent, source) {
|
||||
// The retirement record also covers responsibilities that
|
||||
// never reached object-heal admission.
|
||||
if entry.anchor.as_ref() != Some(&anchor) {
|
||||
entry.anchor = Some(anchor.clone());
|
||||
}
|
||||
anchors.push(anchor);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if probe_held
|
||||
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
|
||||
&& entry.intent.kind == MrfKind::PartialWrite
|
||||
&& entry.intent.scope.is_some()
|
||||
&& entry.intent.version_id.is_none_or(|version| version == [0; 16])
|
||||
&& !entry.intent.object.ends_with('/')
|
||||
&& entry.next_attempt <= now
|
||||
&& held.is_none_or(|(_, due)| entry.next_attempt < due)
|
||||
{
|
||||
held = Some((key, entry.next_attempt));
|
||||
}
|
||||
}
|
||||
|
||||
self.retirement_checks
|
||||
.retain(|generation, _| intents_by_generation.contains_key(generation));
|
||||
let now = Instant::now();
|
||||
for ((bucket, incarnation), intents) in intents_by_generation {
|
||||
let retired = match self.retirement_checks.get(&(bucket.clone(), incarnation)) {
|
||||
Some((_, true)) => true,
|
||||
Some((checked_at, false))
|
||||
if now.saturating_duration_since(*checked_at) < MRF_RETIREMENT_PROOF_RECHECK_INTERVAL =>
|
||||
{
|
||||
false
|
||||
}
|
||||
_ => {
|
||||
let retired = manager
|
||||
.mrf_bucket_incarnation_retired(bucket.as_ref(), incarnation)
|
||||
.await
|
||||
.unwrap_or(false);
|
||||
self.retirement_checks.insert((bucket.clone(), incarnation), (now, retired));
|
||||
retired
|
||||
}
|
||||
};
|
||||
if !retired {
|
||||
continue;
|
||||
}
|
||||
|
||||
for intent in intents {
|
||||
let Some(anchor) = MrfDurableRepairAnchor::from_intent(intent, incarnation)
|
||||
.filter(|anchor| anchor.bucket_incarnation_id == incarnation)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
|
||||
kind: anchor.kind,
|
||||
bucket: anchor.bucket,
|
||||
object: anchor.object,
|
||||
version_id: anchor.version_id,
|
||||
scope: anchor.scope,
|
||||
delete_marker_purge: anchor.delete_marker_purge,
|
||||
lease: Some(anchor.lease),
|
||||
bucket_incarnation_id: anchor.bucket_incarnation_id,
|
||||
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
|
||||
});
|
||||
}
|
||||
.retain(|(bucket, incarnation), _| generations.contains_key(&(bucket.as_ref(), *incarnation)));
|
||||
for anchor in generations.into_values().flatten().flatten() {
|
||||
publish_mrf_absence(anchor);
|
||||
}
|
||||
|
||||
let retirement = due_generation.and_then(|(bucket, source, _)| {
|
||||
let generation = (bucket, source);
|
||||
self.retirement_checks.get_mut(&generation)?.0 = now + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL;
|
||||
Some(generation)
|
||||
});
|
||||
let held_key = held.map(|(key, _)| key.clone());
|
||||
let held = held_key.and_then(|key| {
|
||||
let entry = self.entries.get_mut(&key)?;
|
||||
let anchor = MrfDurableRepairAnchor::from_intent(&entry.intent, key.source_bucket_incarnation_id?)?;
|
||||
entry.next_attempt = now + MRF_HELD_ABSENCE_RECHECK_INTERVAL;
|
||||
entry.anchor = Some(anchor.clone());
|
||||
Some(anchor)
|
||||
});
|
||||
(retirement, held)
|
||||
}
|
||||
|
||||
pub(super) fn note_bucket_retired(&mut self, generation: &BucketGeneration) {
|
||||
if let Some((_, retired)) = self.retirement_checks.get_mut(generation) {
|
||||
*retired = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn note_held_absence_proof(&self, anchor: MrfDurableRepairAnchor) -> bool {
|
||||
let key = PartialWriteKey::from_anchor(&anchor);
|
||||
if self.entries.get(&key).is_some_and(|entry| {
|
||||
entry.persisted
|
||||
&& matches!(entry.state, ResponsibilityState::HeldUnverifiedLegacy { .. })
|
||||
&& entry.anchor.as_ref() == Some(&anchor)
|
||||
}) {
|
||||
publish_mrf_absence(anchor);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn park_unverified_legacy(&mut self, anchor: &MrfDurableRepairAnchor) -> bool {
|
||||
@@ -550,7 +591,7 @@ impl PartialWrites {
|
||||
|
||||
pub(super) fn checkpoint_records(
|
||||
&self,
|
||||
digest_for: impl Fn(&MrfIntent) -> Option<[u8; 32]>,
|
||||
mut digest_for: impl FnMut(&MrfIntent) -> Option<[u8; 32]>,
|
||||
) -> Vec<ResponsibilityCheckpoint> {
|
||||
self.entries
|
||||
.values()
|
||||
@@ -1016,15 +1057,17 @@ impl PartialWrites {
|
||||
return lifecycle_changed;
|
||||
}
|
||||
let in_flight = manager.try_in_flight_durable_mrf_anchors();
|
||||
for key in ready {
|
||||
let Some(entry) = self.entries.get_mut(&key) else {
|
||||
let identity_cutoff = Instant::now() + MRF_DISPATCH_IDENTITY_START_BUDGET;
|
||||
let mut observed_buckets = HashMap::new();
|
||||
for key in &ready {
|
||||
let Some(entry) = self.entries.get_mut(key) else {
|
||||
continue;
|
||||
};
|
||||
entry.next_attempt = Instant::now() + config.admission_backoff;
|
||||
if entry.attempt_in_flight
|
||||
&& let Some(in_flight) = in_flight.as_ref()
|
||||
{
|
||||
if entry.anchor.as_ref().is_some_and(|anchor| in_flight.contains(anchor)) {
|
||||
entry.next_attempt = Instant::now() + config.admission_backoff;
|
||||
continue;
|
||||
}
|
||||
// A terminal attempt without proof remains owned by the journal.
|
||||
@@ -1032,10 +1075,26 @@ impl PartialWrites {
|
||||
entry.defer_unverified_attempt(Instant::now(), config.admission_backoff);
|
||||
continue;
|
||||
}
|
||||
// The bucket can be deleted and recreated while an obligation is
|
||||
// parked, so every dispatch must compare against a fresh identity.
|
||||
if let Ok(Some(anchor)) = manager.durable_mrf_repair_anchor(&entry.intent).await {
|
||||
entry.anchor = Some(anchor.clone());
|
||||
// The observation belongs to this batch. The storage repair
|
||||
// still acquires its own fence for the expected incarnation.
|
||||
let observed = if let Some(purge) = entry.intent.delete_marker_purge.as_ref() {
|
||||
Some(purge.bucket_incarnation_id)
|
||||
} else {
|
||||
let bucket = key.identity.bucket.as_ref();
|
||||
match observed_buckets.entry(bucket) {
|
||||
Entry::Occupied(observation) => *observation.get(),
|
||||
Entry::Vacant(observation) => {
|
||||
if Instant::now() >= identity_cutoff {
|
||||
// Leave unexamined work due in the rotated retry queue.
|
||||
continue;
|
||||
}
|
||||
let incarnation = manager.mrf_bucket_incarnation_id(bucket).await.ok().flatten();
|
||||
*observation.insert(incarnation)
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Some(anchor) = observed.and_then(|incarnation| MrfDurableRepairAnchor::from_intent(&entry.intent, incarnation))
|
||||
{
|
||||
if let Some(source_bucket_incarnation_id) = entry.source_bucket_incarnation_id
|
||||
&& source_bucket_incarnation_id != anchor.bucket_incarnation_id
|
||||
{
|
||||
@@ -1053,6 +1112,7 @@ impl PartialWrites {
|
||||
lifecycle_changed = true;
|
||||
continue;
|
||||
}
|
||||
entry.anchor = Some(anchor.clone());
|
||||
// Proofless legacy results stay owned by the durable journal;
|
||||
// the lifecycle checkpoint determines whether this process
|
||||
// retries or waits for an explicit operator action.
|
||||
@@ -1201,6 +1261,20 @@ impl PartialWrites {
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_mrf_absence(anchor: MrfDurableRepairAnchor) {
|
||||
rustfs_common::mrf_channel::note_mrf_verified_repair(MrfVerifiedRepairEvent {
|
||||
kind: anchor.kind,
|
||||
bucket: anchor.bucket,
|
||||
object: anchor.object,
|
||||
version_id: anchor.version_id,
|
||||
scope: anchor.scope,
|
||||
delete_marker_purge: anchor.delete_marker_purge,
|
||||
lease: Some(anchor.lease),
|
||||
bucket_incarnation_id: anchor.bucket_incarnation_id,
|
||||
disposition: MrfVerifiedRepairDisposition::AuthoritativelyAbsent,
|
||||
});
|
||||
}
|
||||
|
||||
fn validate_operator_audit_fields(actor: &str, reason: &str, reference: &str, request_id: Uuid) -> Result<(), &'static str> {
|
||||
if request_id.is_nil() || actor.trim().is_empty() || actor.len() > MAX_OPERATOR_ACTOR_BYTES {
|
||||
return Err("operator identity or request id is invalid");
|
||||
@@ -2680,9 +2754,10 @@ mod tests {
|
||||
.admit_with_source_incarnation(item.clone(), Some(incarnation), 1, 8192)
|
||||
.expect("retain exact old-generation responsibility");
|
||||
partial_writes.mark_persisted();
|
||||
let key = PartialWriteKey::new(&item, Some(incarnation));
|
||||
let anchor = MrfDurableRepairAnchor::from_intent(&item, incarnation).expect("exact retirement anchor");
|
||||
partial_writes.entries.get_mut(&key).expect("durable responsibility").anchor = Some(anchor);
|
||||
assert!(
|
||||
partial_writes.anchors().next().is_none(),
|
||||
"this responsibility has not reached object-heal admission"
|
||||
);
|
||||
|
||||
assert!(
|
||||
!manager
|
||||
@@ -2696,7 +2771,7 @@ mod tests {
|
||||
.await
|
||||
.expect("normal bucket deletion publishes durable retirement evidence");
|
||||
|
||||
partial_writes.note_retired_generation_proofs(manager.as_ref()).await;
|
||||
retirement_tests::check_retirement_once(&mut partial_writes, manager.as_ref()).await;
|
||||
let config = MrfConsumerConfig::default();
|
||||
let mut runtime = MrfRuntime {
|
||||
partial_writes,
|
||||
|
||||
@@ -27,7 +27,6 @@ use std::sync::atomic::{AtomicU8, Ordering};
|
||||
struct RetirementCall {
|
||||
bucket: String,
|
||||
incarnation: Uuid,
|
||||
at: Instant,
|
||||
object_refs: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -38,6 +37,7 @@ struct RetirementStorage {
|
||||
calls: Mutex<Vec<RetirementCall>>,
|
||||
result: AtomicU8,
|
||||
delay: Duration,
|
||||
started: tokio::sync::Notify,
|
||||
}
|
||||
|
||||
impl RetirementStorage {
|
||||
@@ -47,6 +47,7 @@ impl RetirementStorage {
|
||||
calls: Mutex::new(Vec::new()),
|
||||
result: AtomicU8::new(0),
|
||||
delay,
|
||||
started: tokio::sync::Notify::new(),
|
||||
}
|
||||
}
|
||||
fn calls(&self) -> Vec<RetirementCall> {
|
||||
@@ -60,9 +61,9 @@ impl HealStorageAPI for RetirementStorage {
|
||||
self.calls.lock().expect("retirement calls").push(RetirementCall {
|
||||
bucket: bucket.to_string(),
|
||||
incarnation: expected,
|
||||
at: Instant::now(),
|
||||
object_refs: self.watched.iter().map(Arc::strong_count).collect(),
|
||||
});
|
||||
self.started.notify_one();
|
||||
if !self.delay.is_zero() {
|
||||
tokio::time::sleep(self.delay).await;
|
||||
}
|
||||
@@ -151,6 +152,19 @@ fn expected_event(entry: &Responsibility, source: Uuid) -> MrfVerifiedRepairEven
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn check_retirement_once(writes: &mut PartialWrites, manager: &HealManager) {
|
||||
if let Some(generation) = writes.plan_maintenance(true, false).0 {
|
||||
if manager
|
||||
.mrf_bucket_incarnation_retired(&generation.0, generation.1)
|
||||
.await
|
||||
.unwrap_or(false)
|
||||
{
|
||||
writes.note_bucket_retired(&generation);
|
||||
}
|
||||
writes.plan_maintenance(false, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_true_cache() {
|
||||
let bucket = format!("retirement-cost-{}", Uuid::new_v4());
|
||||
@@ -184,7 +198,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
let original = writes.checkpoint_records(super::super::super::intent_digest);
|
||||
let started = Instant::now();
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert_eq!(storage.calls().len(), 1);
|
||||
assert_eq!(
|
||||
storage.calls()[0].object_refs,
|
||||
@@ -192,26 +206,29 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
|
||||
"the actual retirement storage callback must not see N eagerly owned anchor object handles"
|
||||
);
|
||||
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
|
||||
assert_eq!(writes.retirement_checks[&(Arc::from(bucket.as_str()), source)], (started, false));
|
||||
assert_eq!(
|
||||
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
|
||||
(started + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false)
|
||||
);
|
||||
tokio::time::advance(Duration::from_millis(4999)).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert_eq!(storage.calls().len(), 1, "cached false does not query or refresh its timestamp");
|
||||
storage.result.store(2, Ordering::Relaxed);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
let failed_at = Instant::now();
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert_eq!(storage.calls().len(), 2, "the exact TTL boundary must recheck");
|
||||
assert_eq!(
|
||||
writes.retirement_checks[&(Arc::from(bucket.as_str()), source)],
|
||||
(failed_at, false),
|
||||
(failed_at + MRF_RETIREMENT_PROOF_RECHECK_INTERVAL, false),
|
||||
"I/O error is cached false"
|
||||
);
|
||||
tokio::time::advance(Duration::from_millis(4999)).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert_eq!(storage.calls().len(), 2);
|
||||
storage.result.store(1, Ordering::Relaxed);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert_eq!(storage.calls().len(), 3);
|
||||
assert!(storage.calls().iter().all(|call| call.object_refs == baseline));
|
||||
let expected = writes
|
||||
@@ -225,7 +242,7 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
|
||||
"proofs preserve exact fields and entry order"
|
||||
);
|
||||
tokio::time::advance(Duration::from_secs(100)).await;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert_eq!(storage.calls().len(), 3, "true is sticky while the eligible generation remains");
|
||||
assert_eq!(
|
||||
take_mrf_verified_repair_events_for(&bucket),
|
||||
@@ -240,52 +257,39 @@ async fn retirement_avoids_prepared_object_handles_and_preserves_false_error_tru
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn retirement_keeps_one_preawait_now_and_one_query_per_generation() {
|
||||
async fn retirement_selects_the_oldest_due_generation_and_groups_exact_proofs() {
|
||||
let bucket = format!("retirement-clock-{}", Uuid::new_v4());
|
||||
let sources = [Uuid::new_v4(), Uuid::new_v4()];
|
||||
let sources = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()];
|
||||
let mut writes = PartialWrites::default();
|
||||
for (index, source) in sources.iter().enumerate() {
|
||||
for (index, source) in sources[..2].iter().enumerate() {
|
||||
admit(&mut writes, &bucket, &format!("object-{index}-a"), Some(*source), true);
|
||||
admit(&mut writes, &bucket, &format!("object-{index}-b"), Some(*source), true);
|
||||
}
|
||||
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(3)));
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
let started = Instant::now();
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 2);
|
||||
let first = writes.plan_maintenance(true, false).0.expect("first due generation");
|
||||
assert!(
|
||||
writes.retirement_checks.values().all(|value| *value == (started, false)),
|
||||
"every group stores the single time captured before either await"
|
||||
);
|
||||
assert_eq!(
|
||||
storage
|
||||
.calls()
|
||||
.iter()
|
||||
.map(|call| (&call.bucket, call.incarnation))
|
||||
.collect::<HashSet<_>>()
|
||||
.len(),
|
||||
2
|
||||
writes.plan_maintenance(false, false).0.is_none(),
|
||||
"a busy worker reserves no other generation"
|
||||
);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
admit(&mut writes, &bucket, "new-generation", Some(sources[2]), true);
|
||||
let second = writes.plan_maintenance(true, false).0.expect("next due generation");
|
||||
let third = writes.plan_maintenance(true, false).0.expect("newly seen generation");
|
||||
assert_ne!(first.1, second.1);
|
||||
assert_eq!(third.1, sources[2]);
|
||||
assert!(
|
||||
storage.calls()[0].at < storage.calls()[1].at,
|
||||
"the callback really spans different instants"
|
||||
writes.plan_maintenance(true, false).0.is_none(),
|
||||
"every issued lookup observes its cooldown"
|
||||
);
|
||||
let next = Instant::now();
|
||||
assert!(next.duration_since(started) >= Duration::from_secs(6));
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 4, "both false groups expire from the same pre-await timestamp");
|
||||
assert!(writes.retirement_checks.values().all(|value| *value == (next, false)));
|
||||
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
|
||||
storage.result.store(1, Ordering::Relaxed);
|
||||
// The preceding callbacks took six seconds, so both false entries expire.
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
assert_eq!(storage.calls().len(), 6);
|
||||
writes.note_bucket_retired(&first);
|
||||
writes.note_bucket_retired(&second);
|
||||
writes.plan_maintenance(false, false);
|
||||
let events = take_mrf_verified_repair_events_for(&bucket);
|
||||
assert_eq!(events.len(), 4);
|
||||
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
|
||||
assert_eq!(events[0].bucket_incarnation_id, events[1].bucket_incarnation_id);
|
||||
assert_eq!(events[2].bucket_incarnation_id, events[3].bucket_incarnation_id);
|
||||
for source in sources {
|
||||
assert_ne!(events[0].bucket_incarnation_id, events[2].bucket_incarnation_id);
|
||||
for source in [first.1, second.1] {
|
||||
let actual = events
|
||||
.iter()
|
||||
.filter(|event| event.bucket_incarnation_id == source)
|
||||
@@ -295,14 +299,15 @@ async fn retirement_keeps_one_preawait_now_and_one_query_per_generation() {
|
||||
.entries
|
||||
.values()
|
||||
.filter(|entry| entry.source_bucket_incarnation_id == Some(source))
|
||||
.map(|entry| expected_event(entry, source))
|
||||
.map(|entry| {
|
||||
assert!(entry.anchor.is_some(), "an undispatched responsibility needs an exact anchor");
|
||||
expected_event(entry, source)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
actual, expected,
|
||||
"each original generation group remains contiguous and keeps its entry order"
|
||||
);
|
||||
assert_eq!(storage.calls().iter().filter(|call| call.incarnation == source).count(), 3);
|
||||
assert_eq!(actual, expected, "each generation keeps the exact current lease and entry order");
|
||||
}
|
||||
tokio::time::advance(MRF_RETIREMENT_PROOF_RECHECK_INTERVAL).await;
|
||||
assert_eq!(writes.plan_maintenance(true, false).0, Some(third));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -347,7 +352,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
|
||||
}
|
||||
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::ZERO));
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert_eq!(writes.retirement_checks.len(), 1);
|
||||
assert!(writes.retirement_checks.contains_key(&(Arc::from(bucket.as_str()), valid)));
|
||||
assert!(storage.calls().is_empty(), "the only eligible generation uses its sticky true cache");
|
||||
@@ -356,7 +361,7 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
|
||||
vec![expected_event(&writes.entries[&valid_key], valid)]
|
||||
);
|
||||
writes.entries.remove(&valid_key);
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert!(
|
||||
writes.retirement_checks.is_empty(),
|
||||
"None and ineligible entries cannot keep an old cache generation alive"
|
||||
@@ -366,8 +371,9 @@ async fn retirement_cache_membership_uses_only_exact_eligible_persisted_sources(
|
||||
.get_mut(&unpersisted_key)
|
||||
.expect("activate persisted source")
|
||||
.persisted = true;
|
||||
writes.note_retired_generation_proofs(&manager).await;
|
||||
check_retirement_once(&mut writes, &manager).await;
|
||||
assert_eq!(storage.calls().len(), 1, "a newly eligible source needs a real retirement lookup");
|
||||
assert_eq!(storage.calls()[0].bucket, bucket);
|
||||
assert_eq!(storage.calls()[0].incarnation, unpersisted);
|
||||
assert_eq!(
|
||||
writes
|
||||
@@ -388,12 +394,112 @@ async fn retirement_cancellation_cannot_publish_an_unfinished_retirement() {
|
||||
storage.result.store(1, Ordering::Relaxed);
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_secs(1), writes.note_retired_generation_proofs(&manager))
|
||||
tokio::time::timeout(Duration::from_secs(1), check_retirement_once(&mut writes, &manager))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(storage.calls().len(), 1);
|
||||
assert!(writes.retirement_checks.is_empty());
|
||||
assert!(writes.retirement_checks.values().all(|(_, retired)| !retired));
|
||||
assert!(take_mrf_verified_repair_events_for(&bucket).is_empty());
|
||||
assert_eq!(writes.checkpoint_records(super::super::super::intent_digest), original);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn held_absence_probe_rotates_due_keys_and_rejects_a_superseded_lease() {
|
||||
let bucket = format!("held-probe-{}", Uuid::new_v4());
|
||||
let source = Uuid::new_v4();
|
||||
let mut writes = PartialWrites::default();
|
||||
let first = admit(&mut writes, &bucket, "first", Some(source), true);
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
let second = admit(&mut writes, &bucket, "second", Some(source), true);
|
||||
let uncommitted = admit(&mut writes, &bucket, "uncommitted", Some(source), false);
|
||||
for key in [&first, &second, &uncommitted] {
|
||||
let entry = writes.entries.get_mut(key).expect("retained entry");
|
||||
entry.state = ResponsibilityState::HeldUnverifiedLegacy {
|
||||
bucket_incarnation_id: source,
|
||||
since_ms: 0,
|
||||
};
|
||||
}
|
||||
assert!(writes.plan_maintenance(false, false).1.is_none());
|
||||
let old = writes.plan_maintenance(false, true).1.expect("oldest due hold");
|
||||
assert_eq!(old.object.as_ref(), "first");
|
||||
let next = writes.plan_maintenance(false, true).1.expect("second due hold");
|
||||
assert_eq!(next.object.as_ref(), "second");
|
||||
assert!(writes.plan_maintenance(false, true).1.is_none());
|
||||
|
||||
let mut replacement = writes.entries[&first].intent.clone();
|
||||
replacement.lease = None;
|
||||
writes
|
||||
.admit_with_source_incarnation(replacement, Some(source), 256, usize::MAX)
|
||||
.expect("admit new write");
|
||||
writes.mark_persisted();
|
||||
assert!(
|
||||
!writes.note_held_absence_proof(old),
|
||||
"an older incarnation lease cannot clear a new write"
|
||||
);
|
||||
assert!(writes.note_held_absence_proof(next.clone()));
|
||||
let events = take_mrf_verified_repair_events_for(&bucket);
|
||||
assert_eq!(events.len(), 1);
|
||||
assert!(next.is_proven_by(&events[0]));
|
||||
assert_eq!(writes.depth(), 3, "proof recording precedes durable discharge");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn stalled_retirement_lookup_does_not_delay_durable_admission() {
|
||||
use super::super::super::{MrfDurableSubmission, run_mrf_consumer_with_stop};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
let _env = rustfs_test_utils::TestECStoreEnv::builder()
|
||||
.prefix("mrf_retirement_ack")
|
||||
.build()
|
||||
.await;
|
||||
let storage = Arc::new(RetirementStorage::new(Vec::new(), Duration::from_secs(60)));
|
||||
let manager = Arc::new(HealManager::new_without_root_recovery_for_test(storage.clone(), None));
|
||||
let (_best_effort, hints) = mpsc::channel(1);
|
||||
let (durable, submissions) = mpsc::channel(2);
|
||||
let (_lifecycle, commands) = mpsc::channel(1);
|
||||
let stop = tokio_util::sync::CancellationToken::new();
|
||||
let worker = tokio::spawn(run_mrf_consumer_with_stop(manager, hints, submissions, commands, Some(stop.clone())));
|
||||
|
||||
let source = Uuid::new_v4();
|
||||
let submit = |object| {
|
||||
let (response, receipt) = oneshot::channel();
|
||||
(
|
||||
MrfDurableSubmission {
|
||||
intent: intent(object),
|
||||
source_bucket_incarnation_id: Some(source),
|
||||
response,
|
||||
},
|
||||
receipt,
|
||||
)
|
||||
};
|
||||
|
||||
let (first, first_receipt) = submit("first-ack");
|
||||
durable.send(first).await.expect("enqueue first durable write");
|
||||
tokio::time::timeout(Duration::from_secs(3), first_receipt)
|
||||
.await
|
||||
.expect("first checkpoint receipt deadline")
|
||||
.expect("consumer receipt")
|
||||
.expect("first checkpoint");
|
||||
tokio::time::timeout(Duration::from_secs(3), storage.started.notified())
|
||||
.await
|
||||
.expect("the background retirement lookup must actually start");
|
||||
|
||||
let (second, second_receipt) = submit("second-ack");
|
||||
durable
|
||||
.send(second)
|
||||
.await
|
||||
.expect("enqueue another durable write during the stalled lookup");
|
||||
let second_result = tokio::time::timeout(Duration::from_secs(3), second_receipt).await;
|
||||
stop.cancel();
|
||||
tokio::time::timeout(Duration::from_secs(3), worker)
|
||||
.await
|
||||
.expect("shutdown must cancel the outstanding read")
|
||||
.expect("consumer joins");
|
||||
second_result
|
||||
.expect("the pending retirement lookup cannot block the checkpoint")
|
||||
.expect("consumer receipt")
|
||||
.expect("second checkpoint");
|
||||
assert_eq!(storage.calls().len(), 1, "one retirement lookup can be in flight");
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
#[derive(Clone, Copy)]
|
||||
enum Lookup {
|
||||
Identity(Option<Uuid>),
|
||||
DelayedIdentity(Uuid, Duration),
|
||||
PermissionDenied,
|
||||
Quorum,
|
||||
Transport,
|
||||
@@ -44,6 +45,10 @@ impl HealStorageAPI for ProbeStorage {
|
||||
let lookup = *self.lookup.lock().expect("lookup outcome");
|
||||
match lookup {
|
||||
Lookup::Identity(value) => Ok(value),
|
||||
Lookup::DelayedIdentity(value, duration) => {
|
||||
tokio::time::sleep(duration).await;
|
||||
Ok(Some(value))
|
||||
}
|
||||
Lookup::PermissionDenied => Err(Error::Io(std::io::ErrorKind::PermissionDenied.into())),
|
||||
Lookup::Quorum => Err(Error::Storage(EcstoreError::ErasureReadQuorum)),
|
||||
Lookup::Transport => Err(Error::Io(std::io::ErrorKind::ConnectionReset.into())),
|
||||
@@ -879,7 +884,7 @@ fn unknown_source_deleted_bucket_writer_lost_result_is_resolved_by_exact_commit_
|
||||
let record = pending.record.clone();
|
||||
runtime.partial_writes.pending_lifecycle_transition = Some(pending);
|
||||
let sequence = runtime.next_checkpoint_sequence;
|
||||
let (payload, _) = runtime.snapshot();
|
||||
let payload = runtime.snapshot().authoritative;
|
||||
let lifecycle = encode_mrf_lifecycle_checkpoint(
|
||||
2,
|
||||
runtime.checkpoint_owner,
|
||||
@@ -1009,3 +1014,114 @@ fn unknown_source_deleted_bucket_writer_failed_mirror_cannot_downgrade_a_committ
|
||||
assert_eq!(retried.records, committed.records);
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn durable_dispatch_reads_one_incarnation_per_bucket_and_refreshes_the_next_batch() {
|
||||
let source = Uuid::new_v4();
|
||||
let storage = Arc::new(ProbeStorage {
|
||||
lookup: Mutex::new(Lookup::Identity(Some(source))),
|
||||
calls: AtomicUsize::new(0),
|
||||
});
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
let mut writes = PartialWrites::default();
|
||||
let config = MrfConsumerConfig::default();
|
||||
|
||||
for index in 0..32 {
|
||||
writes
|
||||
.admit_with_source_incarnation(intent(&format!("batch-{index}")), Some(source), 64, usize::MAX)
|
||||
.expect("admit a distinct responsibility in the same bucket");
|
||||
}
|
||||
let mut other = intent("another-bucket");
|
||||
other.bucket = Arc::from("other-bucket");
|
||||
writes
|
||||
.admit_with_source_incarnation(other, Some(source), 64, usize::MAX)
|
||||
.expect("admit a responsibility in a different bucket");
|
||||
writes.mark_persisted();
|
||||
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(manager.get_queue_length().await, 33);
|
||||
|
||||
let changed = Uuid::new_v4();
|
||||
*storage.lookup.lock().expect("lookup outcome") = Lookup::Identity(Some(changed));
|
||||
let next = intent("next-batch");
|
||||
let key = PartialWriteKey::new(&next, Some(source));
|
||||
writes
|
||||
.admit_with_source_incarnation(next, Some(source), 64, usize::MAX)
|
||||
.expect("admit another responsibility from the original incarnation");
|
||||
writes.mark_persisted();
|
||||
assert!(writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(manager.get_queue_length().await, 33);
|
||||
assert!(matches!(
|
||||
writes.entries[&key].state,
|
||||
ResponsibilityState::BucketIncarnationChanged {
|
||||
source_bucket_incarnation_id,
|
||||
observed_bucket_incarnation_id,
|
||||
..
|
||||
} if source_bucket_incarnation_id == source && observed_bucket_incarnation_id == changed
|
||||
));
|
||||
assert!(writes.entries[&key].anchor.is_none(), "the replacement incarnation cannot own this lease");
|
||||
*storage.lookup.lock().expect("lookup outcome") = Lookup::PermissionDenied;
|
||||
for object in ["failed-first", "failed-second"] {
|
||||
writes
|
||||
.admit_with_source_incarnation(intent(object), Some(source), 64, usize::MAX)
|
||||
.expect("admit a due responsibility");
|
||||
}
|
||||
writes.mark_persisted();
|
||||
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 4, "a failed lookup is shared within the batch");
|
||||
assert_eq!(manager.get_queue_length().await, 33, "a failed lookup authorizes no additional work");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn durable_dispatch_completes_slow_reads_and_leaves_unexamined_work_due() {
|
||||
let source = Uuid::new_v4();
|
||||
let storage = Arc::new(ProbeStorage {
|
||||
lookup: Mutex::new(Lookup::DelayedIdentity(source, Duration::from_secs(3))),
|
||||
calls: AtomicUsize::new(0),
|
||||
});
|
||||
let manager = HealManager::new_without_root_recovery_for_test(storage.clone(), None);
|
||||
let mut writes = PartialWrites::default();
|
||||
let config = MrfConsumerConfig::default();
|
||||
let first = intent("slow-first");
|
||||
let first_key = PartialWriteKey::new(&first, Some(source));
|
||||
let same = intent("slow-second");
|
||||
let same_key = PartialWriteKey::new(&same, Some(source));
|
||||
let mut later = intent("later");
|
||||
later.bucket = Arc::from("later-bucket");
|
||||
let later_key = PartialWriteKey::new(&later, Some(source));
|
||||
let mut purge = intent("purge");
|
||||
purge.kind = MrfKind::DeleteMarkerPurge;
|
||||
purge.version_id = Some([1; 16]);
|
||||
purge.delete_marker_purge = rustfs_common::mrf_channel::MrfDeleteMarkerPurge::new(source, source, [2; 32], vec![3]);
|
||||
for item in [first, same, later, purge] {
|
||||
writes
|
||||
.admit_with_source_incarnation(item, Some(source), 8, usize::MAX)
|
||||
.expect("admit a persisted responsibility");
|
||||
}
|
||||
writes.mark_persisted();
|
||||
let later_due = writes.entries[&later_key].next_attempt;
|
||||
let start = Instant::now();
|
||||
assert!(
|
||||
!tokio::time::timeout(Duration::from_secs(4), writes.dispatch_collecting_lifecycle_change(&manager, &config))
|
||||
.await
|
||||
.expect("bucket identity wait is bounded")
|
||||
);
|
||||
assert!(start.elapsed() >= Duration::from_secs(3), "give the in-progress lookup time to finish");
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 1, "share the slow lookup and defer unseen buckets");
|
||||
assert!(writes.entries[&first_key].attempt_in_flight);
|
||||
assert!(writes.entries[&same_key].attempt_in_flight);
|
||||
assert_eq!(writes.entries[&later_key].consecutive_unverified_attempts, 0);
|
||||
assert_eq!(writes.entries[&later_key].next_attempt, later_due);
|
||||
assert_eq!(
|
||||
manager.get_queue_length().await,
|
||||
3,
|
||||
"the lookup covers both objects and the marker carries its own incarnation"
|
||||
);
|
||||
|
||||
*storage.lookup.lock().expect("lookup outcome") = Lookup::Identity(Some(source));
|
||||
assert!(!writes.dispatch_collecting_lifecycle_change(&manager, &config).await);
|
||||
assert_eq!(storage.calls.load(Ordering::Relaxed), 2);
|
||||
assert!(writes.entries[&later_key].attempt_in_flight);
|
||||
assert_eq!(manager.get_queue_length().await, 4);
|
||||
}
|
||||
|
||||
@@ -537,3 +537,42 @@ fn empty_events_real_consumer_stop_retains_unresolved_journal() {
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors() {
|
||||
if isolated("lifecycle_encoding_failure_preserves_the_previous_checkpoint_and_mirrors") {
|
||||
return;
|
||||
}
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("runtime")
|
||||
.block_on(async {
|
||||
let (_env, _manager, mut runtime, anchor) = bound_runtime().await;
|
||||
let previous = runtime.runtime_checkpoint;
|
||||
let authoritative = read_journal(MRF_SCOPED_JOURNAL_PATH).await;
|
||||
let legacy = read_journal(MRF_JOURNAL_PATH).await;
|
||||
assert!(authoritative.is_some(), "fixture has a published authoritative mirror");
|
||||
|
||||
let mut hint = partial_intent("next-bucket");
|
||||
hint.kind = MrfKind::DecodeFailure;
|
||||
hint.scope = None;
|
||||
runtime.admit_best_effort(hint);
|
||||
runtime
|
||||
.admit_partial_write(partial_intent("next-bucket"), Some(anchor.bucket_incarnation_id))
|
||||
.expect("admit a new durable responsibility");
|
||||
let original_limit = runtime.config.journal_max_bytes;
|
||||
runtime.config.journal_max_bytes = 1;
|
||||
assert!(!runtime.flush().await, "an oversized companion cannot acknowledge publication");
|
||||
assert_eq!(runtime.runtime_checkpoint, previous);
|
||||
assert_eq!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
|
||||
assert_eq!(read_journal(MRF_JOURNAL_PATH).await, legacy);
|
||||
assert!(runtime.dirty, "the next flush must retain pending work");
|
||||
|
||||
runtime.config.journal_max_bytes = original_limit;
|
||||
assert!(runtime.flush().await, "the prior state remains retryable");
|
||||
assert_ne!(runtime.runtime_checkpoint, previous);
|
||||
assert_ne!(read_journal(MRF_SCOPED_JOURNAL_PATH).await, authoritative);
|
||||
assert_ne!(read_journal(MRF_JOURNAL_PATH).await, legacy);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -582,6 +582,10 @@ pub trait HealStorageAPI: Send + Sync {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn probe_mrf_unversioned_absence(&self, _anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Heal object using ecstore
|
||||
async fn heal_object(
|
||||
&self,
|
||||
@@ -1415,6 +1419,26 @@ impl HealStorageAPI for ECStoreHealStorage {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn probe_mrf_unversioned_absence(&self, anchor: &rustfs_common::mrf_channel::MrfDurableRepairAnchor) -> Result<bool> {
|
||||
let Some(scope) = anchor.scope else {
|
||||
return Ok(false);
|
||||
};
|
||||
let opts = HealOpts {
|
||||
pool: Some(scope.pool_index as usize),
|
||||
set: Some(scope.set_index as usize),
|
||||
..Default::default()
|
||||
};
|
||||
let store = self.live_ecstore();
|
||||
run_background_object(
|
||||
self.admission.as_ref(),
|
||||
|| store.physical_heal_plan(&anchor.object, &opts).map_err(Error::Storage),
|
||||
&opts,
|
||||
|_| true,
|
||||
boxed_object_operation(|| async { store.probe_mrf_unversioned_absence(anchor).await.map_err(Error::Storage) }),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_object_meta(&self, bucket: &str, object: &str) -> Result<Option<HealObjectInfo>> {
|
||||
debug!(
|
||||
target: "rustfs::heal::storage",
|
||||
|
||||
@@ -513,37 +513,35 @@ impl HealTask {
|
||||
);
|
||||
let receipt_missing = storage_result.receipt.is_none();
|
||||
if !self.record_verified_storage_receipt(&expected, storage_result.receipt).await {
|
||||
let ok_drive_state = DriveState::Ok.to_string();
|
||||
let selected_version_matches = storage_result.item.resolved_version_id.is_some_and(|resolved| {
|
||||
let requested = version_id.filter(|version| !version.is_empty());
|
||||
match requested {
|
||||
let item = &storage_result.item;
|
||||
// A legacy heal can restore redundancy without verifying the original
|
||||
// content. Only the complete report for the selected version can park it.
|
||||
let proof_rejection = if !receipt_missing {
|
||||
Some("storage receipt did not verify the requested identity and disposition")
|
||||
} else if !item.legacy_identity_unverified {
|
||||
Some("storage returned no verified receipt or legacy identity observation")
|
||||
} else if !item
|
||||
.resolved_version_id
|
||||
.is_some_and(|resolved| match version_id.filter(|version| !version.is_empty()) {
|
||||
Some(requested) => Uuid::parse_str(requested).is_ok_and(|version| version.as_bytes() == &resolved),
|
||||
None => resolved == [0; 16],
|
||||
}
|
||||
});
|
||||
// A completed legacy repair can restore redundancy without proving
|
||||
// original content. Keep the same durable responsibility as an
|
||||
// already-healthy Deep result, including when this attempt repaired
|
||||
// a shard. Storage errors and invalid receipts never qualify.
|
||||
let healthy_legacy = receipt_missing
|
||||
&& storage_result.item.legacy_identity_unverified
|
||||
&& selected_version_matches
|
||||
&& storage_result.item.drives_healed().is_some()
|
||||
&& storage_result.item.after.drives.len() == storage_result.item.disk_count
|
||||
&& storage_result
|
||||
.item
|
||||
.before
|
||||
.drives
|
||||
.iter()
|
||||
.zip(&storage_result.item.after.drives)
|
||||
.all(|(before, after)| before.endpoint == after.endpoint)
|
||||
&& storage_result
|
||||
.item
|
||||
.after
|
||||
.drives
|
||||
.iter()
|
||||
.all(|drive| drive.state == ok_drive_state);
|
||||
if healthy_legacy {
|
||||
})
|
||||
{
|
||||
Some("selected version does not match")
|
||||
} else if item.drives_reported() != Some(item.disk_count) || item.before.drives.len() != item.disk_count {
|
||||
Some("drive report is incomplete")
|
||||
} else {
|
||||
item.before.drives.iter().zip(&item.after.drives).find_map(|(before, after)| {
|
||||
if before.endpoint != after.endpoint {
|
||||
Some("drive report endpoints changed")
|
||||
} else if after.state != DriveState::Ok.to_str() {
|
||||
Some("a reported drive is not healthy")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
};
|
||||
if proof_rejection.is_none() {
|
||||
self.outcome.write().await.record(HealObjectOutcome {
|
||||
deep_check_observed: false,
|
||||
quorum_selected_data_dir: None,
|
||||
@@ -553,14 +551,10 @@ impl HealTask {
|
||||
});
|
||||
}
|
||||
self.record_result_item(storage_result.item).await;
|
||||
return Err(if healthy_legacy {
|
||||
Error::LegacyMrfUnverified {
|
||||
target: format!("{bucket}/{object}"),
|
||||
}
|
||||
} else {
|
||||
Error::TaskExecutionFailed {
|
||||
message: format!("{}{bucket}/{object}", crate::error::MRF_MISSING_PROOF_PREFIX),
|
||||
}
|
||||
let target = format!("{bucket}/{object}");
|
||||
return Err(match proof_rejection {
|
||||
Some(reason) => Error::MrfStorageProofUnavailable { target, reason },
|
||||
None => Error::LegacyMrfUnverified { target },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -3338,13 +3338,18 @@ async fn durable_mrf_grace_remains_owned_by_the_responsibility() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn durable_mrf_unverified_object_names_cannot_change_retry_classification() {
|
||||
for object in ["ordinary", "timed out", "network error"] {
|
||||
for object in ["ordinary", "timed out", "network error", "file not found"] {
|
||||
let (task, _) = mrf_task_for_item(object, HealResultItem::default());
|
||||
let error = task
|
||||
.execute()
|
||||
.await
|
||||
.expect_err("missing proof must retain the responsibility");
|
||||
assert!(!error.is_recoverable_heal(), "object name must not change retry classification: {object}");
|
||||
assert!(
|
||||
matches!(crate::error::classify_heal_error(&error), crate::error::HealErrorClass::Permanent),
|
||||
"case={object}: {error}"
|
||||
);
|
||||
assert!(!error.is_recoverable_heal(), "case={object}: {error}");
|
||||
assert!(!error.is_object_absent(), "case={object}: {error}");
|
||||
assert_eq!(task.get_outcome().await.counters.healed, 0);
|
||||
}
|
||||
}
|
||||
@@ -3480,6 +3485,25 @@ async fn mrf_legacy_pause_requires_storage_owned_healthy_deep_result() {
|
||||
assert_eq!(opts[0].scan_mode, HealScanMode::Deep);
|
||||
} else {
|
||||
assert!(matches!(task.get_status().await, HealTaskStatus::Failed { .. }), "case={case}");
|
||||
let reason = match case {
|
||||
"text_only" => "storage returned no verified receipt or legacy identity observation",
|
||||
"empty" | "unaligned" | "wrong_disk_count" => "drive report is incomplete",
|
||||
"unhealthy" => "a reported drive is not healthy",
|
||||
"wrong_endpoint" => "drive report endpoints changed",
|
||||
"wrong_version" | "unknown_version" | "versioned_mismatch" => "selected version does not match",
|
||||
"receipt" => "storage receipt did not verify the requested identity and disposition",
|
||||
"storage_error" | "dry_run" => continue,
|
||||
_ => panic!("unexpected case {case}"),
|
||||
};
|
||||
assert!(
|
||||
matches!(
|
||||
&error,
|
||||
Error::MrfStorageProofUnavailable { target, reason: actual }
|
||||
if target == "bucket-a/object" && *actual == reason
|
||||
),
|
||||
"case={case}: {error:?}"
|
||||
);
|
||||
assert!(error.to_string().ends_with(reason), "case={case}: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -737,6 +737,176 @@ async fn degraded_deleted_partial_write_is_discharged_by_an_absence_proof_inner(
|
||||
.await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_unversioned_partial_write_is_discharged_automatically_after_delete() {
|
||||
const STACK_SIZE: usize = 8 * 1024 * 1024;
|
||||
std::thread::Builder::new()
|
||||
.name("mrf-held-absence".to_owned())
|
||||
.stack_size(STACK_SIZE)
|
||||
.spawn(|| {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.thread_stack_size(STACK_SIZE)
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("held absence runtime should build");
|
||||
runtime.block_on(held_unversioned_partial_write_is_discharged_automatically_after_delete_inner());
|
||||
})
|
||||
.expect("spawn held absence test thread")
|
||||
.join()
|
||||
.expect("held absence test thread should finish");
|
||||
}
|
||||
|
||||
async fn held_unversioned_partial_write_is_discharged_automatically_after_delete_inner() {
|
||||
use rustfs_common::mrf_channel::{MrfDurableRepairAnchor, MrfIntent, MrfKind, MrfScope, try_rearm_mrf_replay_intent};
|
||||
use storage_api::integration::{DeleteOptions, NamespaceLocking as _, lookup_config_for_pools};
|
||||
|
||||
const BUCKET: &str = "held-absence";
|
||||
const OBJECT: &str = "chunks/held-then-deleted";
|
||||
temp_env::async_with_vars(
|
||||
[
|
||||
("RUSTFS_HEAL_MRF_ENABLE", Some("true")),
|
||||
("RUSTFS_SHARD_INTEGRITY_WRITE", Some("false")),
|
||||
("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", Some("false")),
|
||||
],
|
||||
async {
|
||||
let env = TestECStoreEnv::builder().disk_count(9).build().await;
|
||||
env.ecstore
|
||||
.set_storage_class(lookup_config_for_pools(&Default::default(), &[9]).expect("EC:3 for nine drives"));
|
||||
env.make_bucket(BUCKET, false).await;
|
||||
let set = env.ecstore.pools[0].get_disks(0);
|
||||
let manager = manager(&env);
|
||||
mrf_queue::spawn_mrf_consumer(manager.clone());
|
||||
let offline = set.disks.write().await[8].take();
|
||||
assert!(offline.is_some(), "the ninth drive must start connected");
|
||||
let payload = vec![7; 2 * 1024 * 1024];
|
||||
put(&env, BUCKET, OBJECT, &payload, false).await;
|
||||
assert!(snapshot_contains(OBJECT).await, "the degraded PUT must commit a durable obligation");
|
||||
set.disks.write().await[8] = offline;
|
||||
manager.start().await.expect("start the MRF manager");
|
||||
assert!(
|
||||
wait_until(|| async {
|
||||
mrf_queue::list_legacy_responsibilities(None, 32).await.is_ok_and(|listing| {
|
||||
listing
|
||||
.responsibilities
|
||||
.iter()
|
||||
.any(|row| row.bucket == BUCKET && row.object == OBJECT && row.status == "held_unverified_legacy")
|
||||
})
|
||||
})
|
||||
.await,
|
||||
"legacy repair must park the responsibility before the DELETE"
|
||||
);
|
||||
|
||||
let incarnation = env
|
||||
.ecstore
|
||||
.bucket_incarnation_id_from_disk(BUCKET)
|
||||
.await
|
||||
.expect("load the bucket incarnation");
|
||||
let mut intent = MrfIntent {
|
||||
bucket: Arc::from(BUCKET),
|
||||
object: Arc::from(OBJECT),
|
||||
version_id: None,
|
||||
kind: MrfKind::PartialWrite,
|
||||
scope: Some(MrfScope {
|
||||
pool_index: 0,
|
||||
set_index: 0,
|
||||
}),
|
||||
lease: None,
|
||||
enqueued_at_ms: 0,
|
||||
attempts: 0,
|
||||
delete_marker_purge: None,
|
||||
};
|
||||
assert_eq!(
|
||||
try_rearm_mrf_replay_intent(&mut intent),
|
||||
rustfs_common::mrf_channel::MrfIngressResult::Enqueued
|
||||
);
|
||||
let mut anchor = MrfDurableRepairAnchor::from_intent(&intent, incarnation).expect("valid exact test anchor");
|
||||
let namespace = set.new_ns_lock(BUCKET, OBJECT).await.expect("object namespace lock");
|
||||
let writer = namespace
|
||||
.get_write_lock(Duration::from_secs(2))
|
||||
.await
|
||||
.expect("hold object write lock");
|
||||
assert!(
|
||||
!tokio::time::timeout(Duration::from_secs(2), env.ecstore.probe_mrf_unversioned_absence(&anchor))
|
||||
.await
|
||||
.expect("a present object must finish the probe while the writer owns its namespace")
|
||||
.expect("check the present object")
|
||||
);
|
||||
drop(writer);
|
||||
assert!(snapshot_contains(OBJECT).await, "a healthy legacy object cannot retire the obligation");
|
||||
|
||||
const PREPARED: &str = "chunks/prepared-delete";
|
||||
put(&env, BUCKET, PREPARED, &payload, false).await;
|
||||
let transaction = uuid::Uuid::new_v4();
|
||||
let disks = set.disks.read().await.clone();
|
||||
for disk in disks.iter().flatten() {
|
||||
disk.delete_version_recoverable(
|
||||
BUCKET,
|
||||
PREPARED,
|
||||
rustfs_filemeta::FileInfo {
|
||||
name: PREPARED.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
false,
|
||||
DeleteOptions {
|
||||
old_data_dir: Some(transaction),
|
||||
delete_recovery_bucket_incarnation: Some(incarnation),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("prepare the transaction without publishing its commit");
|
||||
assert!(matches!(
|
||||
disk.read_version("", BUCKET, PREPARED, "", &ReadOptions::default()).await,
|
||||
Err(DiskError::FileNotFound | DiskError::FileVersionNotFound)
|
||||
));
|
||||
}
|
||||
let mut prepared = anchor.clone();
|
||||
prepared.object = Arc::from(PREPARED);
|
||||
assert!(
|
||||
!env.ecstore
|
||||
.probe_mrf_unversioned_absence(&prepared)
|
||||
.await
|
||||
.expect("inspect prepared delete"),
|
||||
"recovery evidence must prevent false absence when every live path is missing"
|
||||
);
|
||||
|
||||
env.ecstore
|
||||
.delete_object(BUCKET, OBJECT, ObjectOptions::default())
|
||||
.await
|
||||
.expect("delete the parked object");
|
||||
let offline = set.disks.write().await[8].take();
|
||||
assert!(
|
||||
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
|
||||
"one unavailable drive prevents exact absence verification"
|
||||
);
|
||||
set.disks.write().await[8] = offline;
|
||||
anchor.bucket_incarnation_id = uuid::Uuid::new_v4();
|
||||
assert!(
|
||||
!matches!(env.ecstore.probe_mrf_unversioned_absence(&anchor).await, Ok(true)),
|
||||
"another bucket incarnation cannot authorize absence"
|
||||
);
|
||||
assert!(
|
||||
wait_until(|| async { !snapshot_contains(OBJECT).await }).await,
|
||||
"a held responsibility with proven absence must clear automatically"
|
||||
);
|
||||
assert_eq!(
|
||||
manager.get_statistics().await.unverified_tasks,
|
||||
1,
|
||||
"absence probes must not enqueue another Deep heal"
|
||||
);
|
||||
assert!(
|
||||
env.ecstore
|
||||
.get_object_info(BUCKET, OBJECT, &ObjectOptions::default())
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
manager.stop().await.expect("stop the MRF manager");
|
||||
},
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn wait_until<F: FnMut() -> Fut, Fut: Future<Output = bool>>(mut probe: F) -> bool {
|
||||
tokio::time::timeout(Duration::from_secs(60), async {
|
||||
loop {
|
||||
|
||||
@@ -294,6 +294,13 @@ pub(crate) fn list_keys_page_size(limit: Option<u32>) -> Option<usize> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop directory entries (such as Vault KV2 version sub-paths `"my-key/"` or
|
||||
/// Vault Transit BYOK `"import/"`) from a key listing; only real key records
|
||||
/// may be listed.
|
||||
pub(crate) fn filter_key_directory_entries(keys: Vec<String>) -> Vec<String> {
|
||||
keys.into_iter().filter(|key| !key.ends_with('/')).collect()
|
||||
}
|
||||
|
||||
/// The response to a request for zero keys.
|
||||
///
|
||||
/// `truncated` is false even when keys exist: a zero-length page carries no
|
||||
|
||||
@@ -423,15 +423,6 @@ enum CasMutation<T> {
|
||||
Skip(T),
|
||||
}
|
||||
|
||||
/// Drop KV2 directory entries from a key listing.
|
||||
///
|
||||
/// Once a key has version records, listing the key prefix returns both the key
|
||||
/// record itself ("my-key") and a directory entry for its version sub-path
|
||||
/// ("my-key/"); only the former is a key.
|
||||
fn filter_key_directory_entries(keys: Vec<String>) -> Vec<String> {
|
||||
keys.into_iter().filter(|key| !key.ends_with('/')).collect()
|
||||
}
|
||||
|
||||
/// Resolve which master key version wrapped an envelope.
|
||||
///
|
||||
/// `Some` versions are honored verbatim: if the record for that version is missing
|
||||
@@ -1122,7 +1113,7 @@ impl VaultKmsClient {
|
||||
|
||||
match keys {
|
||||
Some(keys) => {
|
||||
let keys = filter_key_directory_entries(keys);
|
||||
let keys = crate::backends::filter_key_directory_entries(keys);
|
||||
debug!("Found {} keys in Vault", keys.len());
|
||||
Ok(keys)
|
||||
}
|
||||
@@ -3170,7 +3161,10 @@ mod tests {
|
||||
// Listing the key prefix returns "my-key/" as a directory entry once
|
||||
// my-key has version records; only real key records may be listed.
|
||||
let listed = vec!["alpha".to_string(), "alpha/".to_string(), "beta".to_string()];
|
||||
assert_eq!(filter_key_directory_entries(listed), vec!["alpha".to_string(), "beta".to_string()]);
|
||||
assert_eq!(
|
||||
crate::backends::filter_key_directory_entries(listed),
|
||||
vec!["alpha".to_string(), "beta".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -22,8 +22,8 @@ use crate::backends::vault_credentials::{
|
||||
use crate::backends::{
|
||||
BackendCapabilities, ExpiredKeyRemoval, KmsBackend, ListedKeyFailure, StateGatedOperation, UnreadableKeys,
|
||||
classify_listed_key_failure, destruction_requires_pending_deletion, empty_key_page, ensure_key_state_permits,
|
||||
ensure_rewrap_context_matches, ensure_tag_keys_are_mutable, list_keys_page_size, paginate_keys, started_at_the_first_key,
|
||||
validate_key_id_segment,
|
||||
ensure_rewrap_context_matches, ensure_tag_keys_are_mutable, filter_key_directory_entries, list_keys_page_size, paginate_keys,
|
||||
started_at_the_first_key, validate_key_id_segment,
|
||||
};
|
||||
use crate::config::{KmsConfig, VaultTransitConfig};
|
||||
use crate::encryption::{DataKeyEnvelope, generate_key_material};
|
||||
@@ -1418,7 +1418,7 @@ impl VaultTransitKmsClient {
|
||||
.run("vault_transit_list_keys", OpClass::ReadIdempotent, move || async move {
|
||||
let vault = self.vault().map_err(AttemptError::fatal)?;
|
||||
match key::list(&vault.client, &self.config.mount_path).await {
|
||||
Ok(response) => Ok(response.keys),
|
||||
Ok(response) => Ok(filter_key_directory_entries(response.keys)),
|
||||
// An empty transit engine answers LIST with a bare 404;
|
||||
// that is an empty listing, not a backend failure.
|
||||
Err(error) if is_empty_transit_list(&error) => Ok(Vec::new()),
|
||||
@@ -2416,6 +2416,43 @@ mod tests {
|
||||
assert_eq!(response.next_marker, None);
|
||||
}
|
||||
|
||||
/// Regression test for rustfs/rustfs#9846.
|
||||
///
|
||||
/// Once BYOK key import is used on a Transit mount, Vault/OpenBao includes
|
||||
/// the directory entry `"import/"` in `LIST /v1/transit/keys`. It is not a
|
||||
/// key ID and must be filtered out before `key_info()` validates key names.
|
||||
#[tokio::test]
|
||||
async fn list_keys_ignores_byok_import_directory_entry() {
|
||||
let metadata = TransitKeyMetadata::from_create_request(&CreateKeyRequest::default());
|
||||
let (vault, client) = scripted_client(vec![
|
||||
ScriptedResponse::ok(serde_json::json!({
|
||||
"keys": ["import/", "my-key"]
|
||||
})),
|
||||
ScriptedResponse::ok(transit_key_read_data("my-key")),
|
||||
ScriptedResponse::ok(metadata_read_data(&metadata)),
|
||||
])
|
||||
.await;
|
||||
|
||||
let response = client
|
||||
.list_keys(&ListKeysRequest::default(), None)
|
||||
.await
|
||||
.expect("directory entries like import/ must be ignored when listing transit keys");
|
||||
assert_eq!(response.keys.len(), 1);
|
||||
assert_eq!(response.keys[0].key_id, "my-key");
|
||||
assert!(response.unreadable_key_ids.is_empty());
|
||||
assert!(!response.truncated);
|
||||
|
||||
let requests = vault.requests();
|
||||
assert_eq!(
|
||||
requests,
|
||||
vec![
|
||||
"LIST /v1/transit/keys".to_string(),
|
||||
"GET /v1/transit/keys/my-key".to_string(),
|
||||
"GET /v1/secret/data/rustfs/kms/transit-metadata/my-key".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn test_vault_transit_config() -> VaultTransitConfig {
|
||||
VaultTransitConfig {
|
||||
address: "http://127.0.0.1:8200".to_string(),
|
||||
|
||||
@@ -277,6 +277,7 @@ pub struct LockLostSignal {
|
||||
lost: AtomicBool,
|
||||
valid_until: Mutex<Option<Instant>>,
|
||||
notify: Notify,
|
||||
voters: Option<Box<(usize, Vec<Arc<LockLostSignal>>)>>,
|
||||
}
|
||||
|
||||
impl LockLostSignal {
|
||||
@@ -308,6 +309,12 @@ impl LockLostSignal {
|
||||
if self.lost.load(Ordering::SeqCst) {
|
||||
return true;
|
||||
}
|
||||
if let Some((quorum, votes)) = self.voters.as_deref()
|
||||
&& votes.iter().filter(|vote| !vote.is_lost()).count() < *quorum
|
||||
{
|
||||
self.mark_lost();
|
||||
return true;
|
||||
}
|
||||
let expired = match self.valid_until.lock() {
|
||||
Ok(deadline) => deadline.is_some_and(|valid_until| Instant::now() >= valid_until),
|
||||
Err(_) => true,
|
||||
@@ -320,6 +327,22 @@ impl LockLostSignal {
|
||||
|
||||
/// Resolves once the lock is declared lost (immediately if already lost).
|
||||
pub async fn notified(&self) {
|
||||
if let Some((_, votes)) = self.voters.as_deref() {
|
||||
let mut losses: FuturesUnordered<_> = votes.iter().map(|vote| Box::pin(vote.notified())).collect();
|
||||
loop {
|
||||
let notified = self.notify.notified();
|
||||
tokio::pin!(notified);
|
||||
notified.as_mut().enable();
|
||||
if self.is_lost() {
|
||||
break;
|
||||
}
|
||||
tokio::select! {
|
||||
_ = notified => {}
|
||||
_ = losses.next() => {}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.notified_after_registration(|| {}).await;
|
||||
}
|
||||
|
||||
@@ -439,6 +462,20 @@ struct LockRefreshStats {
|
||||
refresh_errors: usize,
|
||||
}
|
||||
|
||||
/// One confirmed writer grant, renewed only by the guard that acquired it.
|
||||
#[derive(Clone, Debug)]
|
||||
struct WriteVote {
|
||||
client: Arc<dyn LockClient>,
|
||||
lock_id: LockId,
|
||||
lease: Arc<LockLostSignal>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct WriteDomainOwnership {
|
||||
votes: Arc<[WriteVote]>,
|
||||
owners: Vec<Arc<crate::namespace::NamespaceLockGuard>>,
|
||||
}
|
||||
|
||||
/// A RAII guard for distributed locks that releases the lock asynchronously when dropped.
|
||||
#[derive(Debug)]
|
||||
pub struct DistributedLockGuard {
|
||||
@@ -454,6 +491,7 @@ pub struct DistributedLockGuard {
|
||||
refresh_task: Option<JoinHandle<()>>,
|
||||
/// Lock-loss signal, shared with the heartbeat task.
|
||||
lock_lost: Arc<LockLostSignal>,
|
||||
write_domain: Option<Box<WriteDomainOwnership>>,
|
||||
cache_fence_proof: Option<CacheFenceProof>,
|
||||
}
|
||||
|
||||
@@ -464,7 +502,13 @@ impl DistributedLockGuard {
|
||||
/// - `entries` is the full list of underlying leases that should be refreshed and released
|
||||
/// with this guard.
|
||||
/// - `heartbeat`: lease TTL, optional renewal cadence, quorum, and diagnostics.
|
||||
fn new(lock_id: LockId, entries: Vec<HeldLockEntry>, lock_type: LockType, heartbeat: LockHeartbeatConfig) -> Self {
|
||||
fn new(
|
||||
lock_id: LockId,
|
||||
entries: Vec<HeldLockEntry>,
|
||||
lock_type: LockType,
|
||||
heartbeat: LockHeartbeatConfig,
|
||||
track_write_votes: bool,
|
||||
) -> Self {
|
||||
record_lock_held_acquire(lock_type);
|
||||
let cache_fence_proof = (lock_type == LockType::Shared)
|
||||
.then(|| {
|
||||
@@ -481,14 +525,34 @@ impl DistributedLockGuard {
|
||||
None => lock_lost.mark_lost(),
|
||||
}
|
||||
// Non-renewable guards are fenced directly by LockLostSignal's deadline checks.
|
||||
let write_votes: Option<Arc<[WriteVote]>> = track_write_votes.then(|| {
|
||||
entries
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let lease = Arc::new(LockLostSignal::default());
|
||||
lease.set_valid_until(entry.valid_until);
|
||||
WriteVote {
|
||||
client: Arc::clone(&entry.client),
|
||||
lock_id: entry.lock_id.clone(),
|
||||
lease,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let refresh_task = heartbeat.interval.and_then(|_| {
|
||||
tokio::runtime::Handle::try_current().ok().map(|handle| {
|
||||
let entries = entries.clone();
|
||||
let lock_lost = lock_lost.clone();
|
||||
handle.spawn(Self::run_heartbeat(entries, heartbeat, lock_lost))
|
||||
handle.spawn(Self::run_heartbeat(entries, heartbeat, lock_lost, write_votes.clone()))
|
||||
})
|
||||
});
|
||||
Self {
|
||||
write_domain: write_votes.map(|votes| {
|
||||
Box::new(WriteDomainOwnership {
|
||||
votes,
|
||||
owners: Vec::new(),
|
||||
})
|
||||
}),
|
||||
lock_id,
|
||||
entries,
|
||||
lock_type,
|
||||
@@ -535,7 +599,12 @@ impl DistributedLockGuard {
|
||||
/// retain the previous deadline, so transient jitter is tolerated but an unconfirmed lease
|
||||
/// can never remain valid beyond its backend TTL. Waiting for a slow refresh is also fenced
|
||||
/// by the current quorum deadline.
|
||||
async fn run_heartbeat(mut entries: Vec<HeldLockEntry>, config: LockHeartbeatConfig, lock_lost: Arc<LockLostSignal>) {
|
||||
async fn run_heartbeat(
|
||||
mut entries: Vec<HeldLockEntry>,
|
||||
config: LockHeartbeatConfig,
|
||||
lock_lost: Arc<LockLostSignal>,
|
||||
write_votes: Option<Arc<[WriteVote]>>,
|
||||
) {
|
||||
let Some(interval) = config.interval else {
|
||||
return;
|
||||
};
|
||||
@@ -598,10 +667,16 @@ impl DistributedLockGuard {
|
||||
Ok(true) => {
|
||||
stats.refreshed += 1;
|
||||
entries[idx].valid_until = refresh_started.checked_add(config.ttl).unwrap_or(refresh_started);
|
||||
if let Some(vote) = write_votes.as_deref().and_then(|votes| votes.get(idx)) {
|
||||
vote.lease.set_valid_until(entries[idx].valid_until);
|
||||
}
|
||||
}
|
||||
Ok(false) => {
|
||||
stats.not_found += 1;
|
||||
entries[idx].valid_until = Instant::now();
|
||||
if let Some(vote) = write_votes.as_deref().and_then(|votes| votes.get(idx)) {
|
||||
vote.lease.mark_lost();
|
||||
}
|
||||
}
|
||||
Err(_) => stats.refresh_errors += 1,
|
||||
}
|
||||
@@ -614,9 +689,18 @@ impl DistributedLockGuard {
|
||||
&self.lock_id
|
||||
}
|
||||
|
||||
fn write_votes(&self) -> &[WriteVote] {
|
||||
self.write_domain.as_deref().map_or(&[], |domain| &domain.votes)
|
||||
}
|
||||
|
||||
/// Actual granted peer identities, which may differ from the logical guard ID.
|
||||
pub fn granted_lock_ids(&self) -> impl Iterator<Item = &LockId> {
|
||||
self.entries.iter().map(|entry| &entry.lock_id)
|
||||
self.entries.iter().map(|entry| &entry.lock_id).chain(
|
||||
self.write_domain
|
||||
.iter()
|
||||
.filter(|domain| !domain.owners.is_empty())
|
||||
.flat_map(|domain| domain.votes.iter().map(|vote| &vote.lock_id)),
|
||||
)
|
||||
}
|
||||
|
||||
/// Read-quorum cache-fence proof carried by this guard, when every required
|
||||
@@ -646,12 +730,24 @@ impl DistributedLockGuard {
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_write_votes(&mut self) {
|
||||
if let Some(domain) = self.write_domain.take() {
|
||||
self.lock_lost.mark_lost();
|
||||
if domain.owners.is_empty() {
|
||||
for vote in domain.votes.iter() {
|
||||
vote.lease.mark_lost();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Manually disarm the guard so dropping it won't release the lock.
|
||||
/// Call this if you explicitly released the lock elsewhere.
|
||||
pub fn disarm(&mut self) {
|
||||
// Stop renewing a lock the caller says it released elsewhere.
|
||||
self.stop_heartbeat();
|
||||
if !self.disarmed {
|
||||
self.invalidate_write_votes();
|
||||
record_lock_held_release(self.lock_type);
|
||||
}
|
||||
self.disarmed = true;
|
||||
@@ -678,6 +774,7 @@ impl DistributedLockGuard {
|
||||
|
||||
let entries = self.entries.iter().map(HeldLockEntry::release_entry).collect();
|
||||
DistributedLock::spawn_release_cleanup(entries, "distributed_lock_guard_release");
|
||||
self.invalidate_write_votes();
|
||||
|
||||
// Disarm to prevent double-release on drop
|
||||
self.disarmed = true;
|
||||
@@ -697,7 +794,7 @@ impl Drop for DistributedLockGuard {
|
||||
|
||||
/// Distributed lock handler for distributed use cases
|
||||
/// Uses quorum-based acquisition and aggregate lock ID mapping
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DistributedLock {
|
||||
/// Lock clients for this namespace
|
||||
clients: Arc<[Arc<dyn LockClient>]>,
|
||||
@@ -744,7 +841,20 @@ struct LockAcquireQuorumResult {
|
||||
attempt_timed_out: bool,
|
||||
}
|
||||
|
||||
/// Whether both domains contain the same nonempty set of distinct write voters.
|
||||
pub fn same_write_voters(left: &[Arc<dyn LockClient>], right: &[Arc<dyn LockClient>]) -> bool {
|
||||
!left.is_empty()
|
||||
&& left.len() == right.len()
|
||||
&& left.iter().enumerate().all(|(idx, client)| {
|
||||
!left[..idx].iter().any(|other| Arc::ptr_eq(client, other)) && right.iter().any(|other| Arc::ptr_eq(client, other))
|
||||
})
|
||||
}
|
||||
|
||||
impl DistributedLock {
|
||||
pub(crate) fn shares_write_backend(&self, other: &Self) -> bool {
|
||||
self.quorum == other.quorum && same_write_voters(&self.clients, &other.clients)
|
||||
}
|
||||
|
||||
/// Create new distributed lock
|
||||
pub fn new(namespace: String, clients: Vec<Arc<dyn LockClient>>, quorum: usize) -> Self {
|
||||
Self::new_shared(namespace.into(), clients.into(), quorum)
|
||||
@@ -799,6 +909,14 @@ impl DistributedLock {
|
||||
/// Acquire a lock and return a RAII guard
|
||||
#[hotpath::measure]
|
||||
pub(crate) async fn acquire_guard(&self, request: &LockRequest) -> Result<Option<DistributedLockGuard>> {
|
||||
self.acquire_guard_for_domain(request, false).await
|
||||
}
|
||||
|
||||
async fn acquire_guard_for_domain(
|
||||
&self,
|
||||
request: &LockRequest,
|
||||
track_write_votes: bool,
|
||||
) -> Result<Option<DistributedLockGuard>> {
|
||||
if self.clients.is_empty() {
|
||||
return Err(LockError::internal("No lock clients available"));
|
||||
}
|
||||
@@ -834,6 +952,7 @@ impl DistributedLock {
|
||||
individual_locks,
|
||||
request.lock_type,
|
||||
heartbeat,
|
||||
track_write_votes,
|
||||
)))
|
||||
} else {
|
||||
// Check if it's a timeout or quorum failure
|
||||
@@ -898,6 +1017,109 @@ impl DistributedLock {
|
||||
self.acquire_guard(&req).await
|
||||
}
|
||||
|
||||
/// Acquire this domain's write quorum, retaining any same-key peer leases
|
||||
/// already owned by the enclosing publication.
|
||||
pub(crate) async fn extend_write_lock(
|
||||
&self,
|
||||
resource: ObjectKey,
|
||||
owner: &str,
|
||||
timeout: Duration,
|
||||
held: &[Arc<crate::namespace::NamespaceLockGuard>],
|
||||
) -> Result<DistributedLockGuard> {
|
||||
use crate::namespace::NamespaceLockGuard;
|
||||
for owner in held {
|
||||
if let NamespaceLockGuard::Standard(guard) = owner.as_ref()
|
||||
&& guard.lock_id.resource == resource
|
||||
&& !guard.disarmed
|
||||
&& guard.write_domain.is_none()
|
||||
&& guard
|
||||
.entries
|
||||
.iter()
|
||||
.any(|entry| self.clients.iter().any(|client| Arc::ptr_eq(client, &entry.client)))
|
||||
{
|
||||
return Err(LockError::invalid_handle(guard.lock_id.to_string()));
|
||||
}
|
||||
}
|
||||
let mut votes: Vec<WriteVote> = Vec::new();
|
||||
let mut missing = Vec::new();
|
||||
let mut owners = Vec::new();
|
||||
for client in self.clients.iter() {
|
||||
if votes.iter().any(|vote| Arc::ptr_eq(&vote.client, client)) || missing.iter().any(|peer| Arc::ptr_eq(peer, client))
|
||||
{
|
||||
return Err(LockError::internal("write lock domain has a duplicate voter"));
|
||||
}
|
||||
let grant = held.iter().find_map(|owner| match owner.as_ref() {
|
||||
NamespaceLockGuard::Standard(guard)
|
||||
if !guard.disarmed && !guard.is_lock_lost() && guard.lock_id.resource == resource =>
|
||||
{
|
||||
guard
|
||||
.write_votes()
|
||||
.iter()
|
||||
.find(|vote| Arc::ptr_eq(&vote.client, client) && !vote.lease.is_lost())
|
||||
.map(|vote| (owner, vote))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
if let Some((owner, vote)) = grant {
|
||||
if !owners.iter().any(|held| Arc::ptr_eq(held, owner)) {
|
||||
owners.push(Arc::clone(owner));
|
||||
}
|
||||
votes.push(vote.clone());
|
||||
} else {
|
||||
missing.push(Arc::clone(client));
|
||||
}
|
||||
}
|
||||
let request = LockRequest::new(resource.clone(), LockType::Exclusive, owner)
|
||||
.with_acquire_timeout(timeout)
|
||||
.with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
|
||||
if votes.is_empty() {
|
||||
return self
|
||||
.acquire_guard_for_domain(&request, true)
|
||||
.await?
|
||||
.ok_or_else(|| LockError::timeout(resource.to_string(), timeout));
|
||||
}
|
||||
if votes.len() + missing.len() < self.quorum {
|
||||
return Err(LockError::QuorumNotReached {
|
||||
required: self.quorum,
|
||||
achieved: votes.len(),
|
||||
});
|
||||
}
|
||||
if votes.len() < self.quorum {
|
||||
let remaining = Self::new_shared(Arc::clone(&self.namespace), missing.into(), self.quorum - votes.len());
|
||||
let additional = remaining
|
||||
.acquire_guard_for_domain(&request, true)
|
||||
.await?
|
||||
.ok_or_else(|| LockError::timeout(resource.to_string(), timeout))?;
|
||||
votes.extend(additional.write_votes().iter().cloned());
|
||||
owners.push(Arc::new(NamespaceLockGuard::Standard(additional)));
|
||||
}
|
||||
let live = votes.iter().filter(|vote| !vote.lease.is_lost()).count();
|
||||
if live < self.quorum {
|
||||
return Err(LockError::QuorumNotReached {
|
||||
required: self.quorum,
|
||||
achieved: live,
|
||||
});
|
||||
}
|
||||
let lock_lost = Arc::new(LockLostSignal {
|
||||
voters: Some(Box::new((self.quorum, votes.iter().map(|vote| Arc::clone(&vote.lease)).collect()))),
|
||||
..Default::default()
|
||||
});
|
||||
record_lock_held_acquire(LockType::Exclusive);
|
||||
Ok(DistributedLockGuard {
|
||||
lock_id: LockId::new_unique(&resource),
|
||||
entries: Vec::new(),
|
||||
lock_type: LockType::Exclusive,
|
||||
disarmed: false,
|
||||
refresh_task: None,
|
||||
lock_lost,
|
||||
cache_fence_proof: None,
|
||||
write_domain: Some(Box::new(WriteDomainOwnership {
|
||||
votes: votes.into(),
|
||||
owners,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
/// Convenience: acquire exclusive lock with expected contention logs suppressed
|
||||
#[hotpath::measure]
|
||||
pub async fn lock_guard_quiet(
|
||||
@@ -1204,6 +1426,7 @@ impl DistributedLock {
|
||||
entries,
|
||||
LockType::Exclusive,
|
||||
heartbeat,
|
||||
false,
|
||||
)));
|
||||
}
|
||||
}
|
||||
@@ -2500,6 +2723,110 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extending_a_write_quorum_rejects_overlapping_untracked_owners() {
|
||||
use crate::namespace::NamespaceLockGuard;
|
||||
let clients = stamped_voters(2);
|
||||
let fixed = DistributedLock::new("fixed".into(), vec![clients[0].clone()], 1);
|
||||
let disjoint = DistributedLock::new("disjoint".into(), vec![clients[1].clone()], 1);
|
||||
let target = DistributedLock::new("target".into(), clients, 2);
|
||||
let key = ObjectKey::new("bucket", "object");
|
||||
let timeout = Duration::from_secs(10);
|
||||
let owner = fixed
|
||||
.lock_guard(key.clone(), "fixed", timeout, timeout)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let held = [Arc::new(NamespaceLockGuard::Standard(owner))];
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_millis(200),
|
||||
target.extend_write_lock(key.clone(), "extend", timeout, &held),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(result, Err(LockError::InvalidHandle { .. })));
|
||||
assert!(disjoint.extend_write_lock(key, "disjoint", timeout, &held).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn overlapping_write_domains_reuse_only_live_same_key_grants() {
|
||||
use crate::namespace::NamespaceLockGuard;
|
||||
let clients = stamped_voters(4);
|
||||
let fixed = DistributedLock::new("fixed".into(), clients[..3].to_vec(), 3);
|
||||
let target = DistributedLock::new("target".into(), clients[1..].to_vec(), 3);
|
||||
let key = ObjectKey::new("bucket", "catalog");
|
||||
let timeout = Duration::from_secs(1);
|
||||
let owner = fixed.extend_write_lock(key.clone(), "catalog", timeout, &[]).await.unwrap();
|
||||
let original: Vec<_> = owner.granted_lock_ids().cloned().collect();
|
||||
let fixed_guard = Arc::new(NamespaceLockGuard::Standard(owner));
|
||||
let held = [fixed_guard];
|
||||
let group = target.extend_write_lock(key.clone(), "put", timeout, &held).await.unwrap();
|
||||
assert_eq!(group.granted_lock_ids().count(), 3);
|
||||
assert_eq!(group.granted_lock_ids().filter(|id| original.contains(id)).count(), 2);
|
||||
drop(held);
|
||||
assert!(!group.is_lock_lost(), "the publication must retain its original owners");
|
||||
let different = ObjectKey::new("bucket", "another-key");
|
||||
let group = Arc::new(NamespaceLockGuard::Standard(group));
|
||||
let independent = target
|
||||
.extend_write_lock(different.clone(), "another", timeout, std::slice::from_ref(&group))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(independent.granted_lock_ids().all(|id| id.resource == different));
|
||||
let NamespaceLockGuard::Standard(group) = group.as_ref() else { unreachable!() };
|
||||
group.write_votes()[0].lease.mark_lost();
|
||||
assert!(group.is_lock_lost(), "the target requires every member of its three-vote quorum");
|
||||
tokio::time::timeout(timeout, group.lock_lost.notified()).await.unwrap();
|
||||
assert!(!independent.is_lock_lost());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn releasing_extended_quorum_wakes_waiters_and_preserves_borrowed_voter() {
|
||||
use crate::namespace::NamespaceLockGuard;
|
||||
let clients = stamped_voters(2);
|
||||
let fixed = DistributedLock::new("fixed".into(), vec![clients[0].clone()], 1);
|
||||
let target = DistributedLock::new("target".into(), clients.clone(), 2);
|
||||
let duplicate = DistributedLock::new("duplicate".into(), vec![clients[0].clone(), clients[0].clone()], 2);
|
||||
let key = ObjectKey::new("bucket", "release");
|
||||
let timeout = Duration::from_secs(1);
|
||||
let original = Arc::new(NamespaceLockGuard::Standard(
|
||||
fixed.extend_write_lock(key.clone(), "fixed", timeout, &[]).await.unwrap(),
|
||||
));
|
||||
let held = std::slice::from_ref(&original);
|
||||
assert!(
|
||||
duplicate
|
||||
.extend_write_lock(key.clone(), "target", timeout, held)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
for disarm in [false, true] {
|
||||
let mut group = target.extend_write_lock(key.clone(), "target", timeout, held).await.unwrap();
|
||||
let signal = group.lock_lost();
|
||||
let wait = signal.notified();
|
||||
tokio::pin!(wait);
|
||||
assert!(futures::poll!(&mut wait).is_pending());
|
||||
if disarm {
|
||||
group.disarm();
|
||||
} else {
|
||||
assert!(group.release());
|
||||
}
|
||||
tokio::time::timeout(timeout, wait)
|
||||
.await
|
||||
.expect("invalidate the active waiter");
|
||||
assert!(!original.is_lock_lost());
|
||||
let independent = DistributedLock::new("extra".into(), vec![clients[1].clone()], 1);
|
||||
let _extra = independent
|
||||
.extend_write_lock(key.clone(), "next", timeout, &[])
|
||||
.await
|
||||
.expect("dropping the supplementary lease must not depend on dropping the extended guard");
|
||||
}
|
||||
let regular = fixed
|
||||
.lock_guard(ObjectKey::new("bucket", "ordinary"), "ordinary", timeout, Duration::from_secs(30))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(regular.write_domain.is_none(), "ordinary locks do not track per-voter proofs");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_guard_exposes_complete_cache_fence_quorum_proof() {
|
||||
let lock = DistributedLock::new("cache-proof".to_owned(), stamped_voters(3), 2);
|
||||
|
||||
@@ -77,6 +77,10 @@ impl FastLockGuard {
|
||||
&self.key
|
||||
}
|
||||
|
||||
pub(crate) fn is_held_on(&self, shard: &Arc<LockShard>) -> bool {
|
||||
!self.released && self.shard.as_ref().is_some_and(|held| Arc::ptr_eq(held, shard))
|
||||
}
|
||||
|
||||
/// Get the lock mode (Shared or Exclusive)
|
||||
pub fn mode(&self) -> LockMode {
|
||||
self.mode
|
||||
|
||||
@@ -23,7 +23,7 @@ use std::time::Duration;
|
||||
|
||||
/// Local lock handler using GlobalLockManager
|
||||
/// Directly uses FastObjectLockManager for high-performance local locking
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LocalLock {
|
||||
/// Global lock manager for fast local locks
|
||||
manager: Arc<GlobalLockManager>,
|
||||
@@ -32,6 +32,14 @@ pub struct LocalLock {
|
||||
}
|
||||
|
||||
impl LocalLock {
|
||||
pub(crate) fn shares_write_backend(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.manager, &other.manager)
|
||||
}
|
||||
|
||||
pub(crate) fn holds_guard(&self, guard: &FastLockGuard) -> bool {
|
||||
matches!(self.manager.as_ref(), GlobalLockManager::Enabled(manager) if guard.is_held_on(manager.get_shard(guard.key())))
|
||||
}
|
||||
|
||||
/// Create new local lock
|
||||
pub fn new(namespace: String, manager: Arc<GlobalLockManager>) -> Self {
|
||||
Self::new_shared(namespace.into(), manager)
|
||||
|
||||
@@ -46,7 +46,21 @@ pub struct NamespaceLockWrapper {
|
||||
owner: String,
|
||||
}
|
||||
|
||||
/// Identifies the acquisition backend without granting access to other resources.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WriteLockBackend(NamespaceLock);
|
||||
|
||||
impl WriteLockBackend {
|
||||
pub fn matches(&self, lock: &NamespaceLockWrapper) -> bool {
|
||||
self.0.shares_write_backend(&lock.lock)
|
||||
}
|
||||
}
|
||||
|
||||
impl NamespaceLockWrapper {
|
||||
pub fn write_backend(&self) -> WriteLockBackend {
|
||||
WriteLockBackend(self.lock.clone())
|
||||
}
|
||||
|
||||
/// Create a new wrapper with the lock, resource, and owner
|
||||
pub fn new(lock: NamespaceLock, resource: ObjectKey, owner: String) -> Self {
|
||||
Self { lock, resource, owner }
|
||||
@@ -73,6 +87,36 @@ impl NamespaceLockWrapper {
|
||||
self.lock.get_write_lock(self.resource.clone(), &self.owner, timeout).await
|
||||
}
|
||||
|
||||
/// Extend a publication's existing same-key grants to this write domain.
|
||||
///
|
||||
/// Acquire the initial distributed guard with this method and an empty slice
|
||||
/// so that individual grants can be reused. A local guard already covering
|
||||
/// this key, or an overlapping untracked distributed guard, returns an error
|
||||
/// immediately. The caller retains ownership of every guard in `held`.
|
||||
pub async fn get_write_lock_extending(
|
||||
&self,
|
||||
timeout: Duration,
|
||||
held: &[Arc<NamespaceLockGuard>],
|
||||
) -> crate::error::Result<NamespaceLockGuard> {
|
||||
match &self.lock {
|
||||
NamespaceLock::Distributed(lock) => lock
|
||||
.extend_write_lock(self.resource.clone(), &self.owner, timeout, held)
|
||||
.await
|
||||
.map(NamespaceLockGuard::Standard),
|
||||
NamespaceLock::Local(lock) => {
|
||||
for owner in held {
|
||||
if let NamespaceLockGuard::Fast(guard) = owner.as_ref()
|
||||
&& guard.key() == &self.resource
|
||||
&& lock.holds_guard(guard)
|
||||
{
|
||||
return Err(crate::LockError::already_locked(self.resource.to_string(), guard.owner().as_ref()));
|
||||
}
|
||||
}
|
||||
self.get_write_lock(timeout).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire write lock with expected contention logs suppressed
|
||||
pub async fn get_write_lock_quiet(
|
||||
&self,
|
||||
@@ -196,7 +240,7 @@ impl NamespaceLockGuard {
|
||||
|
||||
/// Namespace lock for managing locks by resource namespaces
|
||||
/// Supports DistributedLock and LocalLock
|
||||
#[derive(Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum NamespaceLock {
|
||||
/// Distributed lock (distributed use case)
|
||||
Distributed(DistributedLock),
|
||||
@@ -205,6 +249,15 @@ pub enum NamespaceLock {
|
||||
}
|
||||
|
||||
impl NamespaceLock {
|
||||
/// Whether both handles acquire the same exclusive lock for a given resource.
|
||||
fn shares_write_backend(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Local(left), Self::Local(right)) => left.shares_write_backend(right),
|
||||
(Self::Distributed(left), Self::Distributed(right)) => left.shares_write_backend(right),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create new namespace lock with single client (local use case)
|
||||
/// Uses DistributedLock with quorum=1 for single client
|
||||
pub fn new(namespace: String, client: Arc<dyn LockClient>) -> Self {
|
||||
|
||||
@@ -22,6 +22,43 @@ use std::sync::{
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn borrowed_catalog_guard_requires_identical_write_backends() {
|
||||
let manager = Arc::new(GlobalLockManager::new());
|
||||
let local = NamespaceLock::with_local_manager("first".into(), manager.clone());
|
||||
assert!(local.shares_write_backend(&NamespaceLock::with_local_manager("second".into(), manager)));
|
||||
let unrelated = NamespaceLock::with_local_manager("first".into(), Arc::new(GlobalLockManager::new()));
|
||||
assert!(!local.shares_write_backend(&unrelated));
|
||||
|
||||
let clients: Vec<Arc<dyn LockClient>> = vec![Arc::new(FailingClient), Arc::new(FailingClient)];
|
||||
let distributed = NamespaceLock::with_clients_and_quorum("first".into(), clients.clone(), 2);
|
||||
let reordered = vec![clients[1].clone(), clients[0].clone()];
|
||||
assert!(distributed.shares_write_backend(&NamespaceLock::with_clients_and_quorum("second".into(), reordered, 2)));
|
||||
let repeated = NamespaceLock::with_clients_and_quorum("second".into(), vec![clients[0].clone(), clients[0].clone()], 2);
|
||||
assert!(!distributed.shares_write_backend(&repeated));
|
||||
assert!(!repeated.shares_write_backend(&repeated));
|
||||
assert!(!distributed.shares_write_backend(&NamespaceLock::with_clients_and_quorum("first".into(), clients, 1)));
|
||||
assert!(!distributed.shares_write_backend(&local));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn extending_a_local_write_rejects_only_the_held_key_and_manager() {
|
||||
let key = ObjectKey::new("bucket", "object");
|
||||
let manager = || Arc::new(GlobalLockManager::Enabled(Arc::new(crate::FastObjectLockManager::new())));
|
||||
let wrapper = |manager| {
|
||||
NamespaceLockWrapper::new(NamespaceLock::with_local_manager("local".into(), manager), key.clone(), "writer".into())
|
||||
};
|
||||
let original = wrapper(manager());
|
||||
let other = wrapper(manager());
|
||||
let timeout = Duration::from_secs(10);
|
||||
let held = [Arc::new(original.get_write_lock(timeout).await.unwrap())];
|
||||
let result = tokio::time::timeout(Duration::from_millis(200), original.get_write_lock_extending(timeout, &held))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(matches!(result, Err(LockError::AlreadyLocked { .. })));
|
||||
assert!(other.get_write_lock_extending(timeout, &held).await.is_ok());
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct FailingClient;
|
||||
|
||||
|
||||
@@ -415,6 +415,10 @@ pub struct AccountInfo {
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
pub struct BucketAccessInfo {
|
||||
pub name: String,
|
||||
/// Whether the snapshot view authorizes displaying initial progress for this bucket incarnation.
|
||||
/// Older servers and requests without `view=snapshot` leave this field absent.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub initial_scan: Option<bool>,
|
||||
/// Display-only accepted scan progress, never a replacement for total usage.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scan_progress: Option<BucketScanProgress>,
|
||||
@@ -454,6 +458,14 @@ pub struct BucketScanProgress {
|
||||
pub size: Option<u64>,
|
||||
pub sources_observed: u64,
|
||||
pub sources_total: u64,
|
||||
/// Whether the sample lacks an authoritative complete sweep, when reported by the server.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub partial: Option<bool>,
|
||||
/// Whether every expected source completed and agreed, when reported by the server.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub converged: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub blocker: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
@@ -781,6 +793,7 @@ mod tests {
|
||||
assert!(!obj.contains_key("objects"));
|
||||
assert!(!obj.contains_key("object_sizes_histogram"));
|
||||
assert!(!obj.contains_key("object_versions_histogram"));
|
||||
assert!(!obj.contains_key("initial_scan"));
|
||||
assert!(!obj.contains_key("scan_progress"));
|
||||
assert!(!obj.contains_key("usage_value_state"));
|
||||
assert!(!obj.contains_key("usage_updated_at"));
|
||||
@@ -805,6 +818,10 @@ mod tests {
|
||||
"stage": "future_stage", "updated_at": 1000, "objects": null, "size": null,
|
||||
"sources_observed": 1, "sources_total": 2,
|
||||
});
|
||||
wire["initial_scan"] = serde_json::json!(true);
|
||||
wire["scan_progress"]["partial"] = serde_json::json!(true);
|
||||
wire["scan_progress"]["converged"] = serde_json::json!(false);
|
||||
wire["scan_progress"]["blocker"] = serde_json::json!("future_blocker");
|
||||
wire["usage_value_state"] = serde_json::json!("future_provenance");
|
||||
let bucket: BucketAccessInfo = serde_json::from_value(wire.clone()).expect("SDK accepts future diagnostic labels");
|
||||
assert_eq!(serde_json::to_value(bucket).expect("preserve diagnostic labels"), wire);
|
||||
@@ -1173,6 +1190,7 @@ mod tests {
|
||||
|
||||
let bucket_info = BucketAccessInfo {
|
||||
name: "test-bucket".to_string(),
|
||||
initial_scan: None,
|
||||
scan_progress: None,
|
||||
usage_value_state: None,
|
||||
usage_updated_at: None,
|
||||
|
||||
@@ -113,6 +113,7 @@ rustfs-common = { workspace = true }
|
||||
rustfs-heal-contracts = { workspace = true }
|
||||
rustfs-scanner-metrics = { workspace = true }
|
||||
rustfs-config = { workspace = true, features = ["observability"] }
|
||||
rustfs-data-usage = { workspace = true }
|
||||
# NOTE: This dependency on rustfs-ecstore is a known architectural limitation.
|
||||
# The obs crate imports types from ecstore for metrics collection.
|
||||
# Breaking this dependency would require defining traits in obs and
|
||||
|
||||
@@ -50,28 +50,22 @@ pub fn collect_bucket_metrics(buckets: &[BucketStats]) -> Vec<PrometheusMetric>
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let size_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_USAGE_BYTES_MD);
|
||||
let objects_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_OBJECTS_TOTAL_MD);
|
||||
let quota_metric = PrometheusMetric::prepare_static_descriptor(&BUCKET_QUOTA_BYTES_MD);
|
||||
let mut metrics = Vec::with_capacity(buckets.len() * 3);
|
||||
for bucket in buckets {
|
||||
let bucket_label: Cow<'static, str> = Cow::Owned(bucket.name.clone());
|
||||
|
||||
if let Some(size_bytes) = bucket.size_bytes {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&BUCKET_USAGE_BYTES_MD, size_bytes as f64)
|
||||
.with_label("bucket", bucket_label.clone()),
|
||||
);
|
||||
metrics.push(size_metric(size_bytes as f64).with_label("bucket", bucket_label.clone()));
|
||||
}
|
||||
|
||||
if let Some(objects_count) = bucket.objects_count {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&BUCKET_OBJECTS_TOTAL_MD, objects_count as f64)
|
||||
.with_label("bucket", bucket_label.clone()),
|
||||
);
|
||||
metrics.push(objects_metric(objects_count as f64).with_label("bucket", bucket_label.clone()));
|
||||
}
|
||||
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&BUCKET_QUOTA_BYTES_MD, bucket.quota_bytes as f64)
|
||||
.with_label("bucket", bucket_label),
|
||||
);
|
||||
metrics.push(quota_metric(bucket.quota_bytes as f64).with_label("bucket", bucket_label));
|
||||
}
|
||||
|
||||
metrics
|
||||
|
||||
@@ -119,36 +119,32 @@ pub fn usage_since_last_update_seconds(last_update: Option<SystemTime>, now: Sys
|
||||
///
|
||||
/// Returns a vector of Prometheus metrics for bucket usage.
|
||||
pub fn collect_bucket_usage_metrics(stats: &[BucketUsageStats]) -> Vec<PrometheusMetric> {
|
||||
let mut metrics = Vec::new();
|
||||
if stats.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let total_bytes = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_TOTAL_BYTES_MD);
|
||||
let objects = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECTS_TOTAL_MD);
|
||||
let versions = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_VERSIONS_COUNT_MD);
|
||||
let delete_markers = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_DELETE_MARKERS_COUNT_MD);
|
||||
let quota = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD);
|
||||
let size_distribution = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD);
|
||||
let version_distribution = PrometheusMetric::prepare_static_descriptor(&USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD);
|
||||
let mut metrics = Vec::with_capacity(stats.len() * 5);
|
||||
|
||||
for stat in stats {
|
||||
let bucket_label = stat.bucket.clone();
|
||||
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_TOTAL_BYTES_MD, stat.total_bytes as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECTS_TOTAL_MD, stat.objects_count as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_VERSIONS_COUNT_MD, stat.versions_count as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_DELETE_MARKERS_COUNT_MD, stat.delete_markers_count as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD, stat.quota_bytes as f64)
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
metrics.push(total_bytes(stat.total_bytes as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(objects(stat.objects_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(versions(stat.versions_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(delete_markers(stat.delete_markers_count as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
metrics.push(quota(stat.quota_bytes as f64).with_label_owned(BUCKET_LABEL, bucket_label.clone()));
|
||||
|
||||
// Object size distribution per bucket
|
||||
for (range, count) in &stat.object_size_distribution {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD, *count as f64)
|
||||
size_distribution(*count as f64)
|
||||
.with_label_owned(RANGE_LABEL, range.clone())
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
@@ -157,7 +153,7 @@ pub fn collect_bucket_usage_metrics(stats: &[BucketUsageStats]) -> Vec<Prometheu
|
||||
// Version count distribution per bucket
|
||||
for (range, count) in &stat.version_count_distribution {
|
||||
metrics.push(
|
||||
PrometheusMetric::from_descriptor(&USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD, *count as f64)
|
||||
version_distribution(*count as f64)
|
||||
.with_label_owned(RANGE_LABEL, range.clone())
|
||||
.with_label_owned(BUCKET_LABEL, bucket_label.clone()),
|
||||
);
|
||||
@@ -225,8 +221,33 @@ mod tests {
|
||||
let metrics = collect_bucket_usage_metrics(&stats);
|
||||
report_metrics(&metrics);
|
||||
|
||||
// 5 base metrics + 1 size distribution + 1 version distribution = 7
|
||||
assert_eq!(metrics.len(), 7);
|
||||
let expected = [
|
||||
(&*USAGE_BUCKET_TOTAL_BYTES_MD, stats[0].total_bytes, None),
|
||||
(&*USAGE_BUCKET_OBJECTS_TOTAL_MD, stats[0].objects_count, None),
|
||||
(&*USAGE_BUCKET_VERSIONS_COUNT_MD, stats[0].versions_count, None),
|
||||
(&*USAGE_BUCKET_DELETE_MARKERS_COUNT_MD, stats[0].delete_markers_count, None),
|
||||
(&*USAGE_BUCKET_QUOTA_TOTAL_BYTES_MD, stats[0].quota_bytes, None),
|
||||
(&*USAGE_BUCKET_OBJECT_SIZE_DISTRIBUTION_MD, 500, Some("0-1KB")),
|
||||
(&*USAGE_BUCKET_OBJECT_VERSION_COUNT_DISTRIBUTION_MD, 800, Some("1")),
|
||||
];
|
||||
assert_eq!(metrics.len(), expected.len());
|
||||
for (metric, (descriptor, value, range)) in metrics.iter().zip(expected) {
|
||||
assert!(matches!(metric.name, std::borrow::Cow::Borrowed(_)));
|
||||
assert_eq!(metric.name, descriptor.get_full_metric_name());
|
||||
assert_eq!(metric.help, descriptor.help);
|
||||
assert_eq!(metric.metric_type, descriptor.metric_type);
|
||||
assert_eq!(metric.value, value as f64);
|
||||
assert_eq!(metric.labels.len(), if range.is_some() { 2 } else { 1 });
|
||||
assert!(
|
||||
metric
|
||||
.labels
|
||||
.iter()
|
||||
.any(|(key, value)| *key == BUCKET_LABEL && value == "test-bucket")
|
||||
);
|
||||
if let Some(range) = range {
|
||||
assert!(metric.labels.iter().any(|(key, value)| *key == RANGE_LABEL && value == range));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -32,9 +32,9 @@ pub use scheduler::{
|
||||
metrics_runtime_controller_snapshot, metrics_runtime_status_snapshot,
|
||||
};
|
||||
pub(crate) use storage_api::metrics::{
|
||||
BucketOperations, BucketOptions, ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore,
|
||||
ObsTierCounter, StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
|
||||
obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity,
|
||||
BucketOperations, BucketOptions, ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsStore, ObsTierCounter,
|
||||
StorageAdminApi, obs_bucket_quota_limits_for_metrics, obs_bucket_replication_stats_snapshot,
|
||||
obs_configured_remote_tier_types, obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_total_usable_capacity,
|
||||
obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
|
||||
@@ -144,6 +144,14 @@ impl PrometheusMetric {
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare a fixed descriptor once before emitting a family of samples.
|
||||
pub(crate) fn prepare_static_descriptor(descriptor: &'static MetricDescriptor) -> impl Fn(f64) -> Self {
|
||||
let name = intern_string(&NAME_CACHE, &descriptor.get_full_metric_name());
|
||||
let kind = descriptor.metric_type;
|
||||
let help = descriptor.help.as_str();
|
||||
move |value| Self::new(name, kind, help, value)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn with_label(mut self, key: &'static str, value: impl Into<Cow<'static, str>>) -> Self {
|
||||
self.labels.push((key, value.into()));
|
||||
|
||||
@@ -141,11 +141,11 @@ use crate::metrics::schema::system_process::{PROCESS_EXECUTABLE_NAME_LABEL, PROC
|
||||
use crate::metrics::stats_collector::{
|
||||
ProcessMetricBundle, collect_api_request_stats, collect_bucket_replication_bandwidth_stats,
|
||||
collect_bucket_replication_stats_bundle, collect_bucket_stats, collect_cluster_config_stats,
|
||||
collect_cluster_storage_snapshot, collect_compression_cluster_stats, collect_disk_and_system_drive_runtime_stats,
|
||||
collect_cluster_storage_and_usage, collect_compression_cluster_stats, collect_disk_and_system_drive_runtime_stats,
|
||||
collect_host_network_stats, collect_iam_stats, collect_ilm_runtime_metric_stats, collect_internode_network_stats,
|
||||
collect_on_demand_migration_backfill_stats, collect_on_demand_migration_stats, collect_process_metric_bundle_with,
|
||||
collect_replication_stats, collect_scanner_runtime_metric_stats, collect_supplementary_usage_metric_stats,
|
||||
collect_system_cpu_and_memory_stats_with, collect_tier_request_metric_stats,
|
||||
collect_replication_stats, collect_scanner_runtime_metric_stats, collect_system_cpu_and_memory_stats_with,
|
||||
collect_tier_request_metric_stats, collect_tier_usage_metric_stats,
|
||||
};
|
||||
use crate::metrics::storage_snapshot::StorageSnapshotMetrics;
|
||||
use crate::node_identity::{SERVER_LABEL, current_local_node_identity};
|
||||
@@ -165,6 +165,7 @@ use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use sysinfo::{Networks, System};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{Instant, Interval, MissedTickBehavior};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::{error, warn};
|
||||
@@ -1578,6 +1579,10 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
let notification_interval = config.notification_interval;
|
||||
let compression_enabled = obs_is_disk_compression_enabled();
|
||||
|
||||
// Keep quota and histogram work off the capacity collector. Bound pending
|
||||
// work to one observation and carry the original collection timestamp.
|
||||
let (usage_tx, mut usage_rx) = mpsc::channel(1);
|
||||
|
||||
// Spawn task for cluster metrics
|
||||
let token_clone = token.clone();
|
||||
tokio::spawn(async move {
|
||||
@@ -1588,7 +1593,10 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
_ = interval.tick() => {
|
||||
run_metrics_collector_tick(health, MetricsCollectorTaskId::ClusterStats, "cluster_stats", async {
|
||||
let collection_started = std::time::Instant::now();
|
||||
if let Some(stats) = collect_cluster_storage_snapshot().await {
|
||||
let storage = collect_cluster_storage_and_usage(|usage| {
|
||||
let _ = usage_tx.try_send((collection_started, usage));
|
||||
}).await;
|
||||
if let Some(stats) = storage {
|
||||
let mut metrics = collect_cluster_metrics(&stats.cluster);
|
||||
metrics.extend(collect_cluster_health_metrics(&stats.health));
|
||||
metrics.extend(collect_cluster_drive_metrics(&stats.drives));
|
||||
@@ -1631,19 +1639,43 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
"supplementary_cluster_stats",
|
||||
async {
|
||||
let mut metrics = Vec::new();
|
||||
let mut usage_metrics_update = None;
|
||||
|
||||
if let Some(stats) = collect_cluster_config_stats().await {
|
||||
metrics.extend(collect_cluster_config_metrics(&stats));
|
||||
}
|
||||
|
||||
if let Some(stats) = collect_iam_stats().await {
|
||||
metrics.extend(collect_iam_metrics(&stats));
|
||||
}
|
||||
if !metrics.is_empty() {
|
||||
report_metrics(&metrics);
|
||||
}
|
||||
},
|
||||
).await;
|
||||
}
|
||||
sample = usage_rx.recv() => {
|
||||
let Some((usage_collection_started, usage)) = sample else {
|
||||
return;
|
||||
};
|
||||
if bucket_usage_snapshot.collection_expired(usage_collection_started) {
|
||||
continue;
|
||||
}
|
||||
run_metrics_collector_tick(
|
||||
health,
|
||||
MetricsCollectorTaskId::SupplementaryClusterStats,
|
||||
"supplementary_cluster_stats",
|
||||
async {
|
||||
let tier_usage = collect_tier_usage_metric_stats(usage.as_ref()).await;
|
||||
let tier_metrics = tier_usage.as_ref().map(collect_tier_usage_metrics).unwrap_or_default();
|
||||
if let Err(error) = tier_usage_snapshot.replace_collected(tier_metrics, usage_collection_started) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_tier_snapshot", error = %error, "tier usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
let usage_collection_started = std::time::Instant::now();
|
||||
let (cluster_bucket_usage, tier_usage) = collect_supplementary_usage_metric_stats().await;
|
||||
if let Some((cluster_usage, bucket_usage)) = cluster_bucket_usage {
|
||||
let cluster_bucket_usage = match usage {
|
||||
Some(usage) => usage.into_metrics(bucket_usage_snapshot.collection_deadline(usage_collection_started)).await,
|
||||
None => None,
|
||||
};
|
||||
if let Some((cluster_usage, bucket_usage)) = cluster_bucket_usage
|
||||
&& !bucket_usage_snapshot.collection_expired(usage_collection_started)
|
||||
{
|
||||
let mut usage_metrics = collect_cluster_usage_metrics(&cluster_usage);
|
||||
usage_metrics.extend(collect_bucket_usage_metrics(&bucket_usage));
|
||||
update_series_zero_tombstones(
|
||||
@@ -1675,22 +1707,9 @@ pub fn init_metrics_runtime(token: CancellationToken) {
|
||||
let _ = expire_series_zero_tombstones(&mut bucket_usage_zero_tombstones);
|
||||
let _ = expire_series_zero_tombstones(&mut bucket_usage_object_size_zero_tombstones);
|
||||
let _ = expire_series_zero_tombstones(&mut bucket_usage_version_zero_tombstones);
|
||||
usage_metrics_update = Some(usage_metrics);
|
||||
}
|
||||
|
||||
if let Some(usage_metrics) = usage_metrics_update
|
||||
&& let Err(error) = bucket_usage_snapshot.replace_collected(usage_metrics, usage_collection_started)
|
||||
{
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_bucket_snapshot", error = %error, "bucket usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
let tier_metrics = tier_usage.as_ref().map(collect_tier_usage_metrics).unwrap_or_default();
|
||||
if let Err(error) = tier_usage_snapshot.replace_collected(tier_metrics, usage_collection_started) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_tier_snapshot", error = %error, "tier usage metrics snapshot rejected");
|
||||
}
|
||||
|
||||
if !metrics.is_empty() {
|
||||
report_metrics(&metrics);
|
||||
if let Err(error) = bucket_usage_snapshot.replace_collected(usage_metrics, usage_collection_started) {
|
||||
error!(event = EVENT_METRICS_RUNTIME_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_RUNTIME, collector = "supplementary_cluster_stats", result = "invalid_bucket_snapshot", error = %error, "bucket usage metrics snapshot rejected");
|
||||
}
|
||||
}
|
||||
},
|
||||
).await;
|
||||
|
||||
@@ -33,14 +33,15 @@ use crate::metrics::collectors::{
|
||||
};
|
||||
use crate::metrics::runtime_sources::{ObsIlmRuntimeSnapshot, bucket_monitor_handle, iam_metrics_snapshot, ilm_runtime_snapshot};
|
||||
use crate::metrics::{
|
||||
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
|
||||
StorageAdminApi, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_get_quota_config,
|
||||
BucketOperations, BucketOptions, ObsBucketReplicationStatsSnapshot, ObsStore, ObsTierCounter, StorageAdminApi,
|
||||
obs_bucket_quota_limits_for_metrics, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
|
||||
obs_get_total_usable_capacity, obs_get_total_usable_capacity_free, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
};
|
||||
use crate::node_identity::current_local_node_identity;
|
||||
use jiff::Timestamp;
|
||||
use rustfs_data_usage::{DataUsageInfo, TierStats};
|
||||
use rustfs_heal_contracts::heal_channel::HealScanMode;
|
||||
use rustfs_io_metrics::internode_metrics::global_internode_metrics;
|
||||
use rustfs_io_metrics::{
|
||||
@@ -66,30 +67,6 @@ const EVENT_METRICS_COLLECTOR_STATE: &str = "metrics_collector_state";
|
||||
type ObsStorageInfo = <ObsStore as StorageAdminApi>::StorageInfo;
|
||||
type ObsBackendInfo = <ObsStore as StorageAdminApi>::BackendInfo;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ObsDataUsageInfo {
|
||||
last_update: Option<SystemTime>,
|
||||
usage_snapshot_complete: bool,
|
||||
usage_snapshot_converged: bool,
|
||||
buckets_count: u64,
|
||||
objects_total_count: u64,
|
||||
versions_total_count: u64,
|
||||
delete_markers_total_count: u64,
|
||||
objects_total_size: u64,
|
||||
buckets_usage: HashMap<String, ObsBucketUsageInfo>,
|
||||
tier_stats: Option<HashMap<String, ObsTierCounter>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ObsBucketUsageInfo {
|
||||
size: u64,
|
||||
objects_count: u64,
|
||||
object_size_histogram: HashMap<String, u64>,
|
||||
object_versions_histogram: HashMap<String, u64>,
|
||||
versions_count: u64,
|
||||
delete_markers_count: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct ObsBucketReplicationBandwidthStats {
|
||||
bucket: String,
|
||||
@@ -102,68 +79,31 @@ fn usize_to_u64_saturating(value: usize) -> u64 {
|
||||
u64::try_from(value).unwrap_or(u64::MAX)
|
||||
}
|
||||
|
||||
async fn load_obs_data_usage_from_backend(store: Arc<ObsStore>) -> ObsEcstoreResult<ObsDataUsageInfo> {
|
||||
let data_usage = obs_load_data_usage_from_backend(store).await?;
|
||||
let usage_snapshot_complete = data_usage.is_complete_bucket_usage_snapshot();
|
||||
|
||||
Ok(ObsDataUsageInfo {
|
||||
last_update: data_usage.last_update,
|
||||
usage_snapshot_complete,
|
||||
usage_snapshot_converged: data_usage.usage_snapshot_converged == Some(true),
|
||||
buckets_count: data_usage.buckets_count,
|
||||
objects_total_count: data_usage.objects_total_count,
|
||||
versions_total_count: data_usage.versions_total_count,
|
||||
delete_markers_total_count: data_usage.delete_markers_total_count,
|
||||
objects_total_size: data_usage.objects_total_size,
|
||||
buckets_usage: data_usage
|
||||
.buckets_usage
|
||||
.into_iter()
|
||||
.map(|(bucket, usage)| {
|
||||
(
|
||||
bucket,
|
||||
ObsBucketUsageInfo {
|
||||
size: usage.size,
|
||||
objects_count: usage.objects_count,
|
||||
object_size_histogram: usage.object_size_histogram,
|
||||
object_versions_histogram: usage.object_versions_histogram,
|
||||
versions_count: usage.versions_count,
|
||||
delete_markers_count: usage.delete_markers_count,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
tier_stats: data_usage.tier_stats.map(|all_tiers| {
|
||||
all_tiers
|
||||
.tiers
|
||||
.into_iter()
|
||||
.map(|(tier, stats)| {
|
||||
(
|
||||
tier,
|
||||
ObsTierCounter {
|
||||
total_size: stats.total_size,
|
||||
num_objects: stats.num_objects,
|
||||
num_versions: stats.num_versions,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
})
|
||||
fn projected_usage_has_source_generations(usage: &DataUsageInfo) -> bool {
|
||||
if !usage.usage_snapshot_admin_projection || usage.last_update.is_none() {
|
||||
return false;
|
||||
}
|
||||
let mut sources = usage
|
||||
.usage_snapshot_set_states
|
||||
.iter()
|
||||
.filter(|state| !state.tombstone)
|
||||
.peekable();
|
||||
sources.peek().is_some() && sources.all(|state| state.scanner_epoch.is_some() && state.scanner_cycle.is_some())
|
||||
}
|
||||
|
||||
fn bucket_usage_metric_values(data_usage: Option<&ObsDataUsageInfo>, bucket: &str) -> (Option<u64>, Option<u64>) {
|
||||
data_usage
|
||||
.filter(|usage| usage.usage_snapshot_complete)
|
||||
fn bucket_usage_metric_values(usage: Option<&DataUsageInfo>, bucket: &str) -> (Option<u64>, Option<u64>) {
|
||||
usage
|
||||
.and_then(|usage| usage.buckets_usage.get(bucket))
|
||||
.map(|usage| (Some(usage.size), Some(usage.objects_count)))
|
||||
.unwrap_or((None, None))
|
||||
}
|
||||
|
||||
fn data_usage_snapshot_covers_bucket_namespace(data_usage: &ObsDataUsageInfo, buckets: &HashSet<String>) -> bool {
|
||||
data_usage.usage_snapshot_complete
|
||||
&& u64::try_from(buckets.len()).ok() == Some(data_usage.buckets_count)
|
||||
&& buckets.len() == data_usage.buckets_usage.len()
|
||||
&& buckets.iter().all(|bucket| data_usage.buckets_usage.contains_key(bucket))
|
||||
fn usage_covers_bucket_namespace<'a>(usage: &DataUsageInfo, names: impl Iterator<Item = &'a str>) -> bool {
|
||||
let mut names = names.filter(|name| !name.starts_with('.'));
|
||||
let measured = usage.buckets_usage.len();
|
||||
u64::try_from(measured).ok() == Some(usage.buckets_count)
|
||||
&& (measured > 0 || usage.is_complete_bucket_usage_snapshot())
|
||||
&& names.try_fold(0, |count, name| usage.buckets_usage.contains_key(name).then_some(count + 1)) == Some(measured)
|
||||
}
|
||||
|
||||
fn resolve_obs_object_store_handle() -> Option<Arc<ObsStore>> {
|
||||
@@ -191,14 +131,6 @@ fn usable_capacity_used_bytes(usable_capacity: u64, free_bytes: u64) -> u64 {
|
||||
usable_capacity.saturating_sub(free_bytes)
|
||||
}
|
||||
|
||||
async fn obs_bucket_quota_limit_bytes(bucket: &str) -> u64 {
|
||||
obs_get_quota_config(bucket)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(|(quota, _)| quota.get_quota_limit())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn obs_bucket_replication_bandwidth_stats() -> Option<Vec<ObsBucketReplicationBandwidthStats>> {
|
||||
let monitor = bucket_monitor_handle()?;
|
||||
Some(
|
||||
@@ -551,11 +483,8 @@ fn cluster_drive_stats_from_storage(storage: &ObsStorageInfo, local_server: &str
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Collect cluster and cluster-health statistics from a single storage snapshot.
|
||||
pub(crate) async fn collect_cluster_storage_snapshot() -> Option<ClusterStorageSnapshot> {
|
||||
let store = resolve_obs_object_store_handle()?;
|
||||
|
||||
let storage_info = StorageAdminApi::storage_info(store.as_ref()).await;
|
||||
async fn collect_cluster_storage_snapshot(store: &ObsStore) -> Option<ClusterStorageSnapshot> {
|
||||
let storage_info = StorageAdminApi::storage_info(store).await;
|
||||
if storage_info.disks.is_empty() && storage_info.backend.drives_per_set.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -582,17 +511,6 @@ pub(crate) async fn collect_cluster_storage_snapshot() -> Option<ClusterStorageS
|
||||
})
|
||||
.count() as u64;
|
||||
|
||||
let data_usage = match load_obs_data_usage_from_backend(store).await {
|
||||
Ok(data_usage) if data_usage.usage_snapshot_complete => Some(data_usage),
|
||||
Ok(_) => None,
|
||||
Err(error) => {
|
||||
warn!(event = EVENT_METRICS_COLLECTOR_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_COLLECTOR, collector = "cluster_stats", result = "data_usage_load_failed", error = %error, "metrics collector state changed");
|
||||
None
|
||||
}
|
||||
};
|
||||
let buckets_count = data_usage.as_ref().map(|usage| usage.buckets_count);
|
||||
let objects_count = data_usage.as_ref().map(|usage| usage.objects_total_count);
|
||||
|
||||
let mut online = 0u64;
|
||||
let mut offline = 0u64;
|
||||
for disk in &storage_info.disks {
|
||||
@@ -611,8 +529,7 @@ pub(crate) async fn collect_cluster_storage_snapshot() -> Option<ClusterStorageS
|
||||
free_bytes: free,
|
||||
stale_capacity_drives,
|
||||
missing_capacity_drives,
|
||||
objects_count,
|
||||
buckets_count,
|
||||
..Default::default()
|
||||
},
|
||||
health: ClusterHealthStats {
|
||||
drives_offline_count: offline,
|
||||
@@ -624,9 +541,45 @@ pub(crate) async fn collect_cluster_storage_snapshot() -> Option<ClusterStorageS
|
||||
})
|
||||
}
|
||||
|
||||
/// Share one usage projection while storage capacity and usage settle independently.
|
||||
pub(crate) async fn collect_cluster_storage_and_usage(
|
||||
publish_usage: impl FnOnce(Option<ClusterUsageObservation>),
|
||||
) -> Option<ClusterStorageSnapshot> {
|
||||
let Some(store) = resolve_obs_object_store_handle() else {
|
||||
publish_usage(None);
|
||||
return None;
|
||||
};
|
||||
let collect_usage = async {
|
||||
let mut usage = match obs_load_data_usage_from_backend(store.clone()).await {
|
||||
Ok(usage) => Some(ClusterUsageObservation::new(store.clone(), usage)),
|
||||
Err(error) => {
|
||||
warn!(event = EVENT_METRICS_COLLECTOR_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_COLLECTOR, collector = "cluster_stats", result = "data_usage_load_failed", error = %error, "metrics collector state changed");
|
||||
None
|
||||
}
|
||||
};
|
||||
let counts = if let Some(usage) = &mut usage
|
||||
&& (usage.data.is_complete_bucket_usage_snapshot() || usage.covers_namespace().await)
|
||||
{
|
||||
Some((usage.data.objects_total_count, usage.data.buckets_count))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
publish_usage(usage);
|
||||
counts
|
||||
};
|
||||
|
||||
let (storage, counts) = tokio::join!(collect_cluster_storage_snapshot(&store), collect_usage);
|
||||
let mut storage = storage?;
|
||||
if let Some((objects, buckets)) = counts {
|
||||
storage.cluster.objects_count = Some(objects);
|
||||
storage.cluster.buckets_count = Some(buckets);
|
||||
}
|
||||
Some(storage)
|
||||
}
|
||||
|
||||
/// Collect cluster statistics using the same observer snapshot as topology and health.
|
||||
pub async fn collect_cluster_and_health_stats() -> (ClusterStats, ClusterHealthStats) {
|
||||
collect_cluster_storage_snapshot()
|
||||
collect_cluster_storage_and_usage(drop)
|
||||
.await
|
||||
.map(|snapshot| (snapshot.cluster, snapshot.health))
|
||||
.unwrap_or_default()
|
||||
@@ -641,8 +594,13 @@ pub async fn collect_cluster_stats() -> ClusterStats {
|
||||
|
||||
/// Collect cluster health statistics from the storage layer.
|
||||
pub async fn collect_cluster_health_stats() -> ClusterHealthStats {
|
||||
let (_, cluster_health_stats) = collect_cluster_and_health_stats().await;
|
||||
cluster_health_stats
|
||||
let Some(store) = resolve_obs_object_store_handle() else {
|
||||
return ClusterHealthStats::default();
|
||||
};
|
||||
collect_cluster_storage_snapshot(&store)
|
||||
.await
|
||||
.map(|snapshot| snapshot.health)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Collect bucket statistics from the storage layer.
|
||||
@@ -654,8 +612,10 @@ pub async fn collect_bucket_stats() -> Option<Vec<BucketStats>> {
|
||||
let store = resolve_obs_object_store_handle()?;
|
||||
|
||||
// Load data usage info from backend to get bucket sizes and object counts
|
||||
let data_usage = match load_obs_data_usage_from_backend(store.clone()).await {
|
||||
Ok(info) => Some(info),
|
||||
let data_usage = match obs_load_data_usage_from_backend(store.clone()).await {
|
||||
Ok(info) => {
|
||||
Some(info).filter(|usage| usage.is_complete_bucket_usage_snapshot() || projected_usage_has_source_generations(usage))
|
||||
}
|
||||
Err(e) => {
|
||||
warn!(event = EVENT_METRICS_COLLECTOR_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_METRICS_COLLECTOR, collector = "bucket_stats", result = "data_usage_load_failed", error = %e, "metrics collector state changed");
|
||||
None
|
||||
@@ -666,6 +626,7 @@ pub async fn collect_bucket_stats() -> Option<Vec<BucketStats>> {
|
||||
let buckets = match store
|
||||
.list_bucket(&BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
@@ -687,17 +648,18 @@ pub async fn collect_bucket_stats() -> Option<Vec<BucketStats>> {
|
||||
// Get size and objects_count from data usage info
|
||||
let (size_bytes, objects_count) = bucket_usage_metric_values(data_usage.as_ref(), &bucket.name);
|
||||
|
||||
// Get quota from bucket metadata
|
||||
let quota_bytes = obs_bucket_quota_limit_bytes(&bucket.name).await;
|
||||
|
||||
stats.push(BucketStats {
|
||||
name: bucket.name,
|
||||
size_bytes,
|
||||
objects_count,
|
||||
quota_bytes,
|
||||
quota_bytes: 0,
|
||||
});
|
||||
}
|
||||
|
||||
let limits = obs_bucket_quota_limits_for_metrics(stats.iter().map(|bucket| bucket.name.as_str()), None).await?;
|
||||
for (bucket, quota_bytes) in stats.iter_mut().zip(limits) {
|
||||
bucket.quota_bytes = quota_bytes;
|
||||
}
|
||||
Some(stats)
|
||||
}
|
||||
|
||||
@@ -1246,87 +1208,105 @@ pub async fn collect_iam_stats() -> Option<IamStats> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Collect cluster and per-bucket usage metrics from backend usage snapshots.
|
||||
///
|
||||
/// This reads persisted usage data via `load_data_usage_from_backend()` and
|
||||
/// builds cluster totals plus per-bucket distributions from the returned
|
||||
/// histograms. It does not trigger an inline object-data rescan.
|
||||
/// Collect cluster and per-bucket usage metrics from a measured usage snapshot.
|
||||
pub async fn collect_cluster_usage_metric_stats() -> Option<(ClusterUsageStats, Vec<BucketUsageStats>)> {
|
||||
let store = resolve_obs_object_store_handle()?;
|
||||
let data_usage = load_obs_data_usage_from_backend(store.clone()).await.ok()?;
|
||||
let bucket_namespace = store
|
||||
.list_bucket(&BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.ok()?
|
||||
.into_iter()
|
||||
.filter(|bucket| !bucket.name.starts_with('.'))
|
||||
.map(|bucket| bucket.name)
|
||||
.collect::<HashSet<_>>();
|
||||
collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await
|
||||
let usage = obs_load_data_usage_from_backend(store.clone()).await.ok()?;
|
||||
ClusterUsageObservation::new(store, usage).into_metrics(None).await
|
||||
}
|
||||
|
||||
/// Collect cluster/bucket usage and configured remote-tier usage from one
|
||||
/// shared backend data-usage snapshot read.
|
||||
///
|
||||
/// Remote-tier inventory is extracted before the bucket-namespace completeness
|
||||
/// check so OTLP tier metrics match `GET /rustfs/admin/v3/tier-stats`, and a
|
||||
/// backend usage read failure still yields `inventory_accounted = false` plus
|
||||
/// node-local 24-hour transition counters when remote tiers are configured.
|
||||
pub(crate) async fn collect_supplementary_usage_metric_stats()
|
||||
-> (Option<(ClusterUsageStats, Vec<BucketUsageStats>)>, Option<TierUsageSnapshot>) {
|
||||
let configured_tiers = obs_configured_remote_tier_types().await;
|
||||
let store = resolve_obs_object_store_handle();
|
||||
let data_usage = match store.as_ref() {
|
||||
Some(store) => load_obs_data_usage_from_backend(store.clone()).await.ok(),
|
||||
None => None,
|
||||
};
|
||||
pub(crate) struct ClusterUsageObservation {
|
||||
store: Arc<ObsStore>,
|
||||
data: DataUsageInfo,
|
||||
namespace_covered: Option<bool>,
|
||||
}
|
||||
|
||||
let tier_usage = if configured_tiers.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let local_daily_stats = obs_local_tier_daily_stats();
|
||||
tier_usage_snapshot_from_parts(
|
||||
&configured_tiers,
|
||||
data_usage.as_ref().and_then(|usage| usage.tier_stats.as_ref()),
|
||||
&local_daily_stats,
|
||||
)
|
||||
};
|
||||
|
||||
let cluster_bucket_usage = match (store, data_usage) {
|
||||
(Some(store), Some(data_usage)) => {
|
||||
let bucket_namespace = store
|
||||
.list_bucket(&BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.map(|buckets| {
|
||||
buckets
|
||||
.into_iter()
|
||||
.filter(|bucket| !bucket.name.starts_with('.'))
|
||||
.map(|bucket| bucket.name)
|
||||
.collect::<HashSet<_>>()
|
||||
});
|
||||
match bucket_namespace {
|
||||
Some(bucket_namespace) => collect_cluster_usage_metric_stats_from_data_usage(data_usage, &bucket_namespace).await,
|
||||
None => None,
|
||||
}
|
||||
impl ClusterUsageObservation {
|
||||
fn new(store: Arc<ObsStore>, data: DataUsageInfo) -> Self {
|
||||
Self {
|
||||
store,
|
||||
data,
|
||||
namespace_covered: None,
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
|
||||
(cluster_bucket_usage, tier_usage)
|
||||
async fn covers_namespace(&mut self) -> bool {
|
||||
if let Some(covered) = self.namespace_covered {
|
||||
return covered;
|
||||
}
|
||||
let covered = usage_covers_live_namespace(&self.store, &self.data).await;
|
||||
self.namespace_covered = Some(covered);
|
||||
covered
|
||||
}
|
||||
|
||||
pub(crate) async fn into_metrics(
|
||||
mut self,
|
||||
deadline: Option<tokio::time::Instant>,
|
||||
) -> Option<(ClusterUsageStats, Vec<BucketUsageStats>)> {
|
||||
if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) || !self.covers_namespace().await {
|
||||
return None;
|
||||
}
|
||||
collect_cluster_usage_metrics_from_snapshot(self.data, deadline).await
|
||||
}
|
||||
}
|
||||
|
||||
async fn usage_covers_live_namespace(store: &ObsStore, usage: &DataUsageInfo) -> bool {
|
||||
let opts = BucketOptions {
|
||||
cached: true,
|
||||
no_metadata: true,
|
||||
..Default::default()
|
||||
};
|
||||
let buckets = if usage.is_complete_bucket_usage_snapshot() {
|
||||
store.list_bucket(&opts).await.ok()
|
||||
} else if !usage.buckets_usage.is_empty() && projected_usage_has_source_generations(usage) {
|
||||
// ECStore supplies the live set layout from this same namespace read.
|
||||
store.list_bucket_for_scanner(&opts).await.ok().and_then(|listing| {
|
||||
let sources = listing.set_buckets.iter().map(|scope| (scope.pool_index, scope.set_index));
|
||||
projected_usage_covers_live_sets(usage, listing.topology_complete, sources).then_some(listing.buckets)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Both listings deduplicate names before returning them.
|
||||
buckets.is_some_and(|buckets| usage_covers_bucket_namespace(usage, buckets.iter().map(|bucket| bucket.name.as_str())))
|
||||
}
|
||||
|
||||
fn projected_usage_covers_live_sets(
|
||||
usage: &DataUsageInfo,
|
||||
topology_complete: bool,
|
||||
mut live_sources: impl Iterator<Item = (usize, usize)>,
|
||||
) -> bool {
|
||||
if !topology_complete {
|
||||
return false;
|
||||
}
|
||||
let mut expected = HashSet::with_capacity(usage.usage_snapshot_set_states.len());
|
||||
usage
|
||||
.usage_snapshot_set_states
|
||||
.iter()
|
||||
.filter(|state| !state.tombstone)
|
||||
.all(|state| expected.insert((state.pool_index, state.set_index)))
|
||||
&& live_sources.all(|(pool, set)| {
|
||||
u64::try_from(pool)
|
||||
.ok()
|
||||
.zip(u64::try_from(set).ok())
|
||||
.is_some_and(|source| expected.remove(&source))
|
||||
})
|
||||
&& expected.is_empty()
|
||||
}
|
||||
|
||||
/// Tier inventory and transitions remain available independently of bucket coverage.
|
||||
pub(crate) async fn collect_tier_usage_metric_stats(usage: Option<&ClusterUsageObservation>) -> Option<TierUsageSnapshot> {
|
||||
let configured_tiers = obs_configured_remote_tier_types().await;
|
||||
if configured_tiers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let stats = usage.and_then(|usage| usage.data.tier_stats.as_ref());
|
||||
tier_usage_snapshot_from_parts(&configured_tiers, stats.map(|stats| &stats.tiers), &obs_local_tier_daily_stats())
|
||||
}
|
||||
|
||||
fn tier_usage_snapshot_from_parts(
|
||||
configured_tiers: &HashMap<String, String>,
|
||||
data_usage_tier_stats: Option<&HashMap<String, ObsTierCounter>>,
|
||||
data_usage_tier_stats: Option<&HashMap<String, TierStats>>,
|
||||
local_daily_stats: &HashMap<String, ObsTierCounter>,
|
||||
) -> Option<TierUsageSnapshot> {
|
||||
if configured_tiers.is_empty() {
|
||||
@@ -1372,82 +1352,68 @@ fn tier_usage_snapshot_from_parts(
|
||||
})
|
||||
}
|
||||
|
||||
async fn collect_cluster_usage_metric_stats_from_data_usage(
|
||||
data_usage: ObsDataUsageInfo,
|
||||
bucket_namespace: &HashSet<String>,
|
||||
async fn collect_cluster_usage_metrics_from_snapshot(
|
||||
usage: DataUsageInfo,
|
||||
deadline: Option<tokio::time::Instant>,
|
||||
) -> Option<(ClusterUsageStats, Vec<BucketUsageStats>)> {
|
||||
if !data_usage_snapshot_covers_bucket_namespace(&data_usage, bucket_namespace) {
|
||||
if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
|
||||
return None;
|
||||
}
|
||||
let mut buckets = Vec::with_capacity(usage.buckets_usage.len());
|
||||
let mut object_sizes = HashMap::new();
|
||||
let mut object_versions = HashMap::new();
|
||||
|
||||
let mut buckets = Vec::with_capacity(data_usage.buckets_usage.len());
|
||||
|
||||
for (bucket_name, usage) in &data_usage.buckets_usage {
|
||||
if bucket_name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
|
||||
let quota_bytes = obs_bucket_quota_limit_bytes(bucket_name).await;
|
||||
|
||||
for (bucket, measured) in usage.buckets_usage {
|
||||
add_usage_histogram(&mut object_sizes, &measured.object_size_histogram)?;
|
||||
add_usage_histogram(&mut object_versions, &measured.object_versions_histogram)?;
|
||||
buckets.push(BucketUsageStats {
|
||||
bucket: bucket_name.clone(),
|
||||
total_bytes: usage.size,
|
||||
objects_count: usage.objects_count,
|
||||
versions_count: usage.versions_count,
|
||||
delete_markers_count: usage.delete_markers_count,
|
||||
quota_bytes,
|
||||
object_size_distribution: usage
|
||||
.object_size_histogram
|
||||
.iter()
|
||||
.map(|(range, count)| (range.clone(), *count))
|
||||
.collect(),
|
||||
version_count_distribution: usage
|
||||
.object_versions_histogram
|
||||
.iter()
|
||||
.map(|(range, count)| (range.clone(), *count))
|
||||
.collect(),
|
||||
bucket,
|
||||
total_bytes: measured.size,
|
||||
objects_count: measured.objects_count,
|
||||
versions_count: measured.versions_count,
|
||||
delete_markers_count: measured.delete_markers_count,
|
||||
quota_bytes: 0,
|
||||
object_size_distribution: measured.object_size_histogram.into_iter().collect(),
|
||||
version_count_distribution: measured.object_versions_histogram.into_iter().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
buckets.sort_by(|a, b| a.bucket.cmp(&b.bucket));
|
||||
buckets.sort_unstable_by(|a, b| a.bucket.cmp(&b.bucket));
|
||||
let limits = obs_bucket_quota_limits_for_metrics(buckets.iter().map(|bucket| bucket.bucket.as_str()), deadline).await?;
|
||||
for (bucket, quota_bytes) in buckets.iter_mut().zip(limits) {
|
||||
bucket.quota_bytes = quota_bytes;
|
||||
}
|
||||
|
||||
Some((
|
||||
ClusterUsageStats {
|
||||
since_last_update_seconds: crate::metrics::collectors::cluster_usage::usage_since_last_update_seconds(
|
||||
data_usage.last_update,
|
||||
usage.last_update,
|
||||
SystemTime::now(),
|
||||
),
|
||||
total_bytes: data_usage.objects_total_size,
|
||||
objects_count: data_usage.objects_total_count,
|
||||
versions_count: data_usage.versions_total_count,
|
||||
delete_markers_count: data_usage.delete_markers_total_count,
|
||||
buckets_count: data_usage.buckets_count,
|
||||
snapshot_converged: data_usage.usage_snapshot_converged,
|
||||
object_size_distribution: data_usage
|
||||
.buckets_usage
|
||||
.values()
|
||||
.flat_map(|usage| usage.object_size_histogram.iter())
|
||||
.fold(HashMap::<String, u64>::new(), |mut acc, (range, count)| {
|
||||
*acc.entry(range.clone()).or_default() += *count;
|
||||
acc
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
versions_distribution: data_usage
|
||||
.buckets_usage
|
||||
.values()
|
||||
.flat_map(|usage| usage.object_versions_histogram.iter())
|
||||
.fold(HashMap::<String, u64>::new(), |mut acc, (range, count)| {
|
||||
*acc.entry(range.clone()).or_default() += *count;
|
||||
acc
|
||||
})
|
||||
.into_iter()
|
||||
.collect(),
|
||||
total_bytes: usage.objects_total_size,
|
||||
objects_count: usage.objects_total_count,
|
||||
versions_count: usage.versions_total_count,
|
||||
delete_markers_count: usage.delete_markers_total_count,
|
||||
buckets_count: usage.buckets_count,
|
||||
snapshot_converged: usage.usage_snapshot_converged == Some(true),
|
||||
object_size_distribution: object_sizes.into_iter().collect(),
|
||||
versions_distribution: object_versions.into_iter().collect(),
|
||||
},
|
||||
buckets,
|
||||
))
|
||||
}
|
||||
|
||||
fn add_usage_histogram(totals: &mut HashMap<String, u64>, histogram: &HashMap<String, u64>) -> Option<()> {
|
||||
for (range, &count) in histogram {
|
||||
match totals.get_mut(range) {
|
||||
Some(total) => *total = total.checked_add(count)?,
|
||||
None => {
|
||||
totals.insert(range.clone(), count);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn ilm_action_task_stats(ilm: &ObsIlmRuntimeSnapshot) -> Vec<IlmActionTaskStats> {
|
||||
vec![
|
||||
IlmActionTaskStats {
|
||||
@@ -1990,81 +1956,130 @@ mod tests {
|
||||
assert_eq!(counts.total_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bucket_usage_metrics_distinguish_unknown_from_confirmed_zero() {
|
||||
assert_eq!(bucket_usage_metric_values(None, "bucket"), (None, None));
|
||||
fn usage_source(pool_index: u64, set_index: u64) -> rustfs_data_usage::DataUsageSnapshotSetState {
|
||||
rustfs_data_usage::DataUsageSnapshotSetState {
|
||||
pool_index,
|
||||
set_index,
|
||||
scanner_epoch: Some(4),
|
||||
scanner_cycle: Some(8),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
let mut data_usage = ObsDataUsageInfo {
|
||||
usage_snapshot_complete: true,
|
||||
#[tokio::test]
|
||||
async fn usage_metrics_publish_projected_values_with_current_namespace_coverage() {
|
||||
let mut usage = DataUsageInfo {
|
||||
last_update: Some(SystemTime::now()),
|
||||
usage_snapshot_admin_projection: true,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_set_states: vec![usage_source(0, 0)],
|
||||
buckets_count: 2,
|
||||
objects_total_count: 3,
|
||||
versions_total_count: 5,
|
||||
delete_markers_total_count: 2,
|
||||
objects_total_size: 42,
|
||||
buckets_usage: HashMap::from([
|
||||
(
|
||||
"busy-bucket".to_string(),
|
||||
rustfs_data_usage::BucketUsageInfo {
|
||||
size: 42,
|
||||
objects_count: 3,
|
||||
versions_count: 5,
|
||||
delete_markers_count: 2,
|
||||
object_size_histogram: HashMap::from([("range".to_string(), 3)]),
|
||||
object_versions_histogram: HashMap::from([("versions".to_string(), 2)]),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"quiet-bucket".to_string(),
|
||||
rustfs_data_usage::BucketUsageInfo {
|
||||
object_size_histogram: HashMap::from([("range".to_string(), 1)]),
|
||||
object_versions_histogram: HashMap::from([("versions".to_string(), 1)]),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]),
|
||||
..Default::default()
|
||||
};
|
||||
data_usage
|
||||
.buckets_usage
|
||||
.insert("bucket".to_string(), ObsBucketUsageInfo::default());
|
||||
|
||||
assert_eq!(bucket_usage_metric_values(Some(&data_usage), "bucket"), (Some(0), Some(0)));
|
||||
assert_eq!(bucket_usage_metric_values(Some(&data_usage), "missing"), (None, None));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cluster_usage_metrics_skip_incomplete_snapshot() {
|
||||
assert!(
|
||||
collect_cluster_usage_metric_stats_from_data_usage(ObsDataUsageInfo::default(), &HashSet::new())
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cluster_usage_metrics_publish_complete_empty_snapshot() {
|
||||
let (cluster, buckets) = collect_cluster_usage_metric_stats_from_data_usage(
|
||||
ObsDataUsageInfo {
|
||||
usage_snapshot_complete: true,
|
||||
usage_snapshot_converged: true,
|
||||
..Default::default()
|
||||
},
|
||||
&HashSet::new(),
|
||||
)
|
||||
.await
|
||||
.expect("complete empty usage should remain publishable");
|
||||
|
||||
assert_eq!(cluster.buckets_count, 0);
|
||||
assert_eq!(cluster.objects_count, 0);
|
||||
assert_eq!(cluster.total_bytes, 0);
|
||||
assert!(cluster.snapshot_converged);
|
||||
assert!(buckets.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cluster_usage_metrics_publish_unknown_convergence_as_unconverged() {
|
||||
let (cluster, _) = collect_cluster_usage_metric_stats_from_data_usage(
|
||||
ObsDataUsageInfo {
|
||||
usage_snapshot_complete: true,
|
||||
usage_snapshot_converged: false,
|
||||
..Default::default()
|
||||
},
|
||||
&HashSet::new(),
|
||||
)
|
||||
.await
|
||||
.expect("complete usage with unknown convergence should remain publishable");
|
||||
|
||||
assert!(projected_usage_has_source_generations(&usage));
|
||||
usage.usage_snapshot_set_states[0].scanner_cycle = None;
|
||||
assert!(!projected_usage_has_source_generations(&usage));
|
||||
usage.usage_snapshot_set_states[0].scanner_cycle = Some(8);
|
||||
assert_eq!(bucket_usage_metric_values(None, "busy-bucket"), (None, None));
|
||||
assert_eq!(bucket_usage_metric_values(Some(&usage), "busy-bucket"), (Some(42), Some(3)));
|
||||
assert_eq!(bucket_usage_metric_values(Some(&usage), "quiet-bucket"), (Some(0), Some(0)));
|
||||
assert_eq!(bucket_usage_metric_values(Some(&usage), "missing"), (None, None));
|
||||
assert!(usage_covers_bucket_namespace(
|
||||
&usage,
|
||||
["busy-bucket", "quiet-bucket", ".internal"].into_iter()
|
||||
));
|
||||
assert!(!usage_covers_bucket_namespace(&usage, ["replaced-bucket", "quiet-bucket"].into_iter()));
|
||||
assert!(!usage_covers_bucket_namespace(
|
||||
&usage,
|
||||
["busy-bucket", "quiet-bucket", "unmeasured"].into_iter()
|
||||
));
|
||||
assert!(!usage_covers_bucket_namespace(&usage, ["busy-bucket"].into_iter()));
|
||||
let (cluster, buckets) = collect_cluster_usage_metrics_from_snapshot(usage, None)
|
||||
.await
|
||||
.expect("representable scanner histograms");
|
||||
assert_eq!((cluster.buckets_count, cluster.objects_count, cluster.total_bytes), (2, 3, 42));
|
||||
assert!(!cluster.snapshot_converged);
|
||||
assert_eq!((buckets[0].versions_count, buckets[0].delete_markers_count), (5, 2));
|
||||
assert_eq!(buckets[0].object_size_distribution, vec![("range".to_string(), 3)]);
|
||||
assert_eq!(buckets[0].version_count_distribution, vec![("versions".to_string(), 2)]);
|
||||
assert_eq!(cluster.object_size_distribution, vec![("range".to_string(), 4)]);
|
||||
assert_eq!(cluster.versions_distribution, vec![("versions".to_string(), 3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_usage_requires_the_same_complete_live_topology() {
|
||||
let usage = DataUsageInfo {
|
||||
usage_snapshot_set_states: vec![usage_source(0, 0), usage_source(0, 1)],
|
||||
..Default::default()
|
||||
};
|
||||
let sources = [(0, 0), (0, 1)];
|
||||
assert!(projected_usage_covers_live_sets(&usage, true, sources.into_iter()));
|
||||
assert!(projected_usage_covers_live_sets(&usage, true, sources.into_iter().rev()));
|
||||
assert!(!projected_usage_covers_live_sets(&usage, true, [(0, 0), (0, 0)].into_iter()));
|
||||
assert!(!projected_usage_covers_live_sets(&usage, true, std::iter::empty()));
|
||||
assert!(!projected_usage_covers_live_sets(&usage, false, sources.into_iter()));
|
||||
assert!(!projected_usage_covers_live_sets(&usage, true, [(0, 0), (1, 0)].into_iter()));
|
||||
assert!(!projected_usage_covers_live_sets(&usage, true, [(0, 0), (0, 1), (1, 0)].into_iter()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cluster_usage_metrics_skip_snapshot_for_a_different_bucket_namespace() {
|
||||
let data_usage = ObsDataUsageInfo {
|
||||
usage_snapshot_complete: true,
|
||||
buckets_count: 1,
|
||||
buckets_usage: HashMap::from([("stale-bucket".to_string(), ObsBucketUsageInfo::default())]),
|
||||
async fn only_complete_usage_can_publish_empty_namespace() {
|
||||
let projected = DataUsageInfo {
|
||||
last_update: Some(SystemTime::now()),
|
||||
usage_snapshot_admin_projection: true,
|
||||
usage_snapshot_set_states: vec![usage_source(0, 0)],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(
|
||||
collect_cluster_usage_metric_stats_from_data_usage(data_usage, &HashSet::from(["live-bucket".to_string()]))
|
||||
assert!(!usage_covers_bucket_namespace(&projected, std::iter::empty()));
|
||||
for (converged, expected) in [(None, false), (Some(true), true)] {
|
||||
let usage = DataUsageInfo {
|
||||
last_update: projected.last_update,
|
||||
usage_snapshot_complete: true,
|
||||
usage_snapshot_converged: converged,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(usage_covers_bucket_namespace(&usage, std::iter::empty()));
|
||||
assert!(!usage_covers_bucket_namespace(&usage, ["unmeasured"].into_iter()));
|
||||
let (cluster, buckets) = collect_cluster_usage_metrics_from_snapshot(usage, None)
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
.expect("complete empty usage snapshot");
|
||||
assert_eq!((cluster.buckets_count, cluster.objects_count, cluster.total_bytes), (0, 0, 0));
|
||||
assert_eq!(cluster.snapshot_converged, expected);
|
||||
assert!(buckets.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_histogram_rejects_cluster_count_overflow() {
|
||||
let mut totals = HashMap::from([("range".to_string(), u64::MAX)]);
|
||||
let histogram = HashMap::from([("range".to_string(), 1)]);
|
||||
assert!(add_usage_histogram(&mut totals, &histogram).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2072,7 +2087,7 @@ mod tests {
|
||||
let configured = HashMap::new();
|
||||
let data_usage_tiers = HashMap::from([(
|
||||
"STANDARD".to_string(),
|
||||
ObsTierCounter {
|
||||
TierStats {
|
||||
total_size: 4096,
|
||||
num_objects: 2,
|
||||
num_versions: 2,
|
||||
@@ -2092,7 +2107,7 @@ mod tests {
|
||||
let data_usage_tiers = HashMap::from([
|
||||
(
|
||||
"STANDARD".to_string(),
|
||||
ObsTierCounter {
|
||||
TierStats {
|
||||
total_size: 99_999,
|
||||
num_objects: 99,
|
||||
num_versions: 120,
|
||||
@@ -2100,7 +2115,7 @@ mod tests {
|
||||
),
|
||||
(
|
||||
"REMOVED_TIER".to_string(),
|
||||
ObsTierCounter {
|
||||
TierStats {
|
||||
total_size: 8_192,
|
||||
num_objects: 4,
|
||||
num_versions: 4,
|
||||
@@ -2108,7 +2123,7 @@ mod tests {
|
||||
),
|
||||
(
|
||||
"ARCHIVE".to_string(),
|
||||
ObsTierCounter {
|
||||
TierStats {
|
||||
total_size: 2048,
|
||||
num_objects: 5,
|
||||
num_versions: 7,
|
||||
|
||||
@@ -17,7 +17,7 @@ use std::time::Duration;
|
||||
|
||||
pub(crate) use rustfs_ecstore::api::bucket::bandwidth::monitor::Monitor as ObsBucketBandwidthMonitor;
|
||||
use rustfs_ecstore::api::bucket::lifecycle::tier_last_day_stats::LastDayTierStats as ObsLastDayTierStats;
|
||||
pub(crate) use rustfs_ecstore::api::bucket::metadata_sys::get_quota_config as obs_get_quota_config;
|
||||
use rustfs_ecstore::api::bucket::metadata_sys::get_global_bucket_metadata_sys;
|
||||
use rustfs_ecstore::api::bucket::replication::{
|
||||
BucketReplicationStats as SourceBucketReplicationStats, DurableMrfBucketBacklog, DurableMrfTargetBacklog,
|
||||
MrfBucketBacklogObservability, RuntimeReplicationTargetBacklog, durable_mrf_backlog_summary_snapshot,
|
||||
@@ -30,7 +30,6 @@ pub(crate) use rustfs_ecstore::api::capacity::{
|
||||
pub(crate) use rustfs_ecstore::api::compression::is_disk_compression_enabled as obs_is_disk_compression_enabled;
|
||||
pub(crate) use rustfs_ecstore::api::data_usage::load_admin_data_usage_from_backend_cached as obs_load_data_usage_from_backend;
|
||||
pub(crate) use rustfs_ecstore::api::data_usage::load_compression_total_from_memory as obs_load_compression_total_from_memory;
|
||||
pub(crate) use rustfs_ecstore::api::error::Result as ObsEcstoreResult;
|
||||
pub(crate) use rustfs_ecstore::api::runtime::{
|
||||
bucket_monitor as obs_get_global_bucket_monitor, expiry_state_handle as obs_expiry_state_handle,
|
||||
global_tier_config_mgr as obs_global_tier_config_mgr, object_store_handle as obs_resolve_object_store_handle,
|
||||
@@ -881,15 +880,33 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn obs_bucket_quota_limits_for_metrics<'a>(
|
||||
buckets: impl ExactSizeIterator<Item = &'a str> + Send,
|
||||
deadline: Option<tokio::time::Instant>,
|
||||
) -> Option<Vec<u64>> {
|
||||
if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
|
||||
return None;
|
||||
}
|
||||
if buckets.len() == 0 {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let Some(metadata) = get_global_bucket_metadata_sys() else {
|
||||
return Some(vec![0; buckets.len()]);
|
||||
};
|
||||
let metadata = metadata.read().await.clone();
|
||||
metadata.quota_limits_for_metrics(buckets, deadline).await
|
||||
}
|
||||
|
||||
pub(crate) mod metrics {
|
||||
pub(crate) use super::storage_contracts::{BucketOperations, BucketOptions, StorageAdminApi};
|
||||
|
||||
pub(crate) use super::{
|
||||
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsEcstoreResult, ObsStore, ObsTierCounter,
|
||||
obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types, obs_expiry_state_handle,
|
||||
obs_get_global_bucket_monitor, obs_get_quota_config, obs_get_total_usable_capacity, obs_get_total_usable_capacity_free,
|
||||
obs_is_disk_compression_enabled, obs_load_compression_total_from_memory, obs_load_data_usage_from_backend,
|
||||
obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot, obs_on_demand_migration_snapshot,
|
||||
obs_replication_site_stats_snapshot, obs_resolve_object_store_handle, obs_transition_state_handle,
|
||||
ObsBucketBandwidthMonitor, ObsBucketReplicationStatsSnapshot, ObsStore, ObsTierCounter,
|
||||
obs_bucket_quota_limits_for_metrics, obs_bucket_replication_stats_snapshot, obs_configured_remote_tier_types,
|
||||
obs_expiry_state_handle, obs_get_global_bucket_monitor, obs_get_total_usable_capacity,
|
||||
obs_get_total_usable_capacity_free, obs_is_disk_compression_enabled, obs_load_compression_total_from_memory,
|
||||
obs_load_data_usage_from_backend, obs_local_tier_daily_stats, obs_on_demand_migration_backfill_snapshot,
|
||||
obs_on_demand_migration_snapshot, obs_replication_site_stats_snapshot, obs_resolve_object_store_handle,
|
||||
obs_transition_state_handle,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
use super::report::{PrometheusMetric, counter_value_from_f64};
|
||||
use super::schema::MetricType;
|
||||
use opentelemetry::{KeyValue, metrics::Meter};
|
||||
use std::collections::HashMap;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{HashMap, hash_map::Entry};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -41,9 +42,15 @@ struct Point {
|
||||
attributes: Vec<KeyValue>,
|
||||
}
|
||||
|
||||
struct Series {
|
||||
metric_type: MetricType,
|
||||
help: Cow<'static, str>,
|
||||
points: Vec<Point>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Snapshot {
|
||||
points: HashMap<String, Vec<Point>>,
|
||||
series: HashMap<Cow<'static, str>, Series>,
|
||||
collected_at: Option<Instant>,
|
||||
timestamp_seconds: f64,
|
||||
remaining_age: Duration,
|
||||
@@ -60,7 +67,10 @@ pub(crate) struct StorageSnapshotMetrics {
|
||||
|
||||
impl StorageSnapshotMetrics {
|
||||
pub(crate) fn new(meter: Meter, scope: &'static str, observer: String, max_age: Duration) -> Self {
|
||||
let labels = vec![KeyValue::new(COLLECTION_SCOPE, scope), KeyValue::new(OBSERVER, observer)];
|
||||
let labels = vec![
|
||||
KeyValue::new(COLLECTION_SCOPE, scope),
|
||||
KeyValue::new(OBSERVER, Arc::<str>::from(observer)),
|
||||
];
|
||||
Self::new_with_labels(meter, labels, max_age, true)
|
||||
}
|
||||
|
||||
@@ -109,6 +119,14 @@ impl StorageSnapshotMetrics {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn collection_deadline(&self, started: Instant) -> Option<tokio::time::Instant> {
|
||||
started.checked_add(self.max_age).map(tokio::time::Instant::from_std)
|
||||
}
|
||||
|
||||
pub(crate) fn collection_expired(&self, started: Instant) -> bool {
|
||||
started.elapsed() >= self.max_age
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn replace(&mut self, metrics: Vec<PrometheusMetric>) -> Result<(), SnapshotError> {
|
||||
self.replace_collected(metrics, Instant::now())
|
||||
@@ -119,56 +137,66 @@ impl StorageSnapshotMetrics {
|
||||
metrics: Vec<PrometheusMetric>,
|
||||
collection_started: Instant,
|
||||
) -> Result<(), SnapshotError> {
|
||||
// Validate the entire update before changing membership or publishing any values.
|
||||
let mut types = self.instruments.clone();
|
||||
for metric in &metrics {
|
||||
match metric.metric_type {
|
||||
MetricType::Gauge if metric.value.is_finite() => (),
|
||||
MetricType::Counter if counter_value_from_f64(metric.value).is_some() => (),
|
||||
let mut series: HashMap<_, Series> = HashMap::new();
|
||||
for metric in metrics {
|
||||
let counter = match metric.metric_type {
|
||||
MetricType::Gauge if metric.value.is_finite() => None,
|
||||
MetricType::Counter => Some(counter_value_from_f64(metric.value).ok_or(SnapshotError::InvalidValue)?),
|
||||
_ => return Err(SnapshotError::InvalidValue),
|
||||
}
|
||||
if types
|
||||
.insert(metric.name.to_string(), metric.metric_type)
|
||||
.is_some_and(|kind| kind != metric.metric_type)
|
||||
{
|
||||
return Err(SnapshotError::ChangedType);
|
||||
}
|
||||
};
|
||||
let group = match series.entry(metric.name) {
|
||||
Entry::Occupied(entry) if entry.get().metric_type == metric.metric_type => entry.into_mut(),
|
||||
Entry::Occupied(_) => return Err(SnapshotError::ChangedType),
|
||||
Entry::Vacant(entry) => {
|
||||
if self
|
||||
.instruments
|
||||
.get(entry.key().as_ref())
|
||||
.is_some_and(|kind| *kind != metric.metric_type)
|
||||
{
|
||||
return Err(SnapshotError::ChangedType);
|
||||
}
|
||||
entry.insert(Series {
|
||||
metric_type: metric.metric_type,
|
||||
help: metric.help,
|
||||
points: Vec::new(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
let mut attributes = Vec::with_capacity(self.labels.len() + metric.labels.len());
|
||||
attributes.extend_from_slice(&self.labels);
|
||||
attributes.extend(metric.labels.into_iter().map(|(key, value)| KeyValue::new(key, value)));
|
||||
group.points.push(Point {
|
||||
value: metric.value,
|
||||
counter,
|
||||
attributes,
|
||||
});
|
||||
}
|
||||
|
||||
let mut points: HashMap<String, Vec<Point>> = HashMap::new();
|
||||
for metric in metrics {
|
||||
let name = metric.name.to_string();
|
||||
if !self.instruments.contains_key(&name) {
|
||||
self.register(&name, metric.metric_type, metric.help.as_ref())?;
|
||||
self.instruments.insert(name.clone(), metric.metric_type);
|
||||
// No SDK registration or published state changes until the batch is valid.
|
||||
for (name, group) in &series {
|
||||
if !self.instruments.contains_key(name.as_ref()) {
|
||||
self.register(name, group.metric_type, &group.help)?;
|
||||
self.instruments.insert(name.to_string(), group.metric_type);
|
||||
}
|
||||
let mut attributes = self.labels.clone();
|
||||
attributes.extend(
|
||||
metric
|
||||
.labels
|
||||
.iter()
|
||||
.map(|(key, value)| KeyValue::new(*key, value.to_string())),
|
||||
);
|
||||
let point = Point {
|
||||
value: metric.value,
|
||||
counter: (metric.metric_type == MetricType::Counter)
|
||||
.then(|| counter_value_from_f64(metric.value))
|
||||
.flatten(),
|
||||
attributes,
|
||||
};
|
||||
points.entry(name).or_default().push(point);
|
||||
}
|
||||
let timestamp_seconds = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs_f64();
|
||||
let mut snapshot = self.snapshot.write().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
*snapshot = Snapshot {
|
||||
points,
|
||||
collected_at: Some(collection_started),
|
||||
timestamp_seconds,
|
||||
// The publication timestamp withdraws cached fields from the previous
|
||||
// snapshot. Deduct collection time separately so a slow RPC or usage
|
||||
// read cannot make an old observation fresh merely by completing.
|
||||
remaining_age: self.max_age.saturating_sub(collection_started.elapsed()),
|
||||
let retired = {
|
||||
let mut snapshot = self.snapshot.write().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
std::mem::replace(
|
||||
&mut *snapshot,
|
||||
Snapshot {
|
||||
series,
|
||||
collected_at: Some(collection_started),
|
||||
timestamp_seconds,
|
||||
// The timestamp withdraws cached fields from the previous
|
||||
// snapshot. A slow collection consumes its validity budget.
|
||||
remaining_age: self.max_age.saturating_sub(collection_started.elapsed()),
|
||||
},
|
||||
)
|
||||
};
|
||||
// Destroying a high-cardinality snapshot must not block export readers.
|
||||
drop(retired);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -187,8 +215,8 @@ impl StorageSnapshotMetrics {
|
||||
if snapshot.collected_at.is_none_or(|when| when.elapsed() > max_age) {
|
||||
return;
|
||||
}
|
||||
if let Some(points) = snapshot.points.get(&name_owned) {
|
||||
for point in points {
|
||||
if let Some(group) = snapshot.series.get(name_owned.as_str()) {
|
||||
for point in &group.points {
|
||||
if let Some(value) = point.counter {
|
||||
observer.observe(value, &point.attributes);
|
||||
}
|
||||
@@ -207,8 +235,8 @@ impl StorageSnapshotMetrics {
|
||||
if snapshot.collected_at.is_none_or(|when| when.elapsed() > max_age) {
|
||||
return;
|
||||
}
|
||||
if let Some(points) = snapshot.points.get(&name_owned) {
|
||||
for point in points {
|
||||
if let Some(group) = snapshot.series.get(name_owned.as_str()) {
|
||||
for point in &group.points {
|
||||
observer.observe(point.value, &point.attributes);
|
||||
}
|
||||
}
|
||||
@@ -324,6 +352,54 @@ mod tests {
|
||||
exporter.0.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_snapshot_does_not_register_new_metrics_or_replace_active_values() {
|
||||
let (provider, exporter, mut snapshot) = setup();
|
||||
snapshot
|
||||
.replace(vec![drive("test_existing", MetricType::Gauge, "drive-a", 7.0)])
|
||||
.expect("publish baseline gauge");
|
||||
|
||||
assert!(matches!(
|
||||
snapshot.replace(vec![
|
||||
drive("test_new", MetricType::Gauge, "drive-a", 8.0),
|
||||
drive("test_existing", MetricType::Counter, "drive-a", 9.0),
|
||||
]),
|
||||
Err(SnapshotError::ChangedType)
|
||||
));
|
||||
assert!(matches!(
|
||||
snapshot.replace(vec![
|
||||
drive("test_new", MetricType::Gauge, "drive-a", 8.0),
|
||||
drive("test_new", MetricType::Counter, "drive-b", 9.0),
|
||||
]),
|
||||
Err(SnapshotError::ChangedType)
|
||||
));
|
||||
assert!(matches!(
|
||||
snapshot.replace(vec![
|
||||
drive("test_new", MetricType::Gauge, "drive-a", 8.0),
|
||||
drive("test_bad_counter", MetricType::Counter, "drive-a", -1.0),
|
||||
]),
|
||||
Err(SnapshotError::InvalidValue)
|
||||
));
|
||||
assert_eq!(snapshot.instruments.len(), 1);
|
||||
let points = flush(&provider, &exporter);
|
||||
assert!(points.iter().any(|point| point.name == "test_existing" && point.value == 7.0));
|
||||
assert!(
|
||||
!points
|
||||
.iter()
|
||||
.any(|point| point.name == "test_new" || point.name == "test_bad_counter")
|
||||
);
|
||||
|
||||
snapshot
|
||||
.replace(vec![drive("test_new", MetricType::Counter, "drive-a", 9.0)])
|
||||
.expect("rejecting a gauge does not reserve its instrument type");
|
||||
assert!(
|
||||
flush(&provider, &exporter)
|
||||
.iter()
|
||||
.any(|point| point.name == "test_new" && point.value == 9.0)
|
||||
);
|
||||
provider.shutdown().expect("shutdown test provider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_sdk_drops_removed_gauges_counters_and_replaced_disk_identity() {
|
||||
let (provider, exporter, mut snapshot) = setup();
|
||||
@@ -690,6 +766,17 @@ mod tests {
|
||||
provider.shutdown().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_storage_observation_keeps_its_original_validity_budget() {
|
||||
let (provider, _, snapshot) = setup();
|
||||
assert!(!snapshot.collection_expired(Instant::now()));
|
||||
let expired = Instant::now()
|
||||
.checked_sub(snapshot.max_age)
|
||||
.expect("clock supports snapshot age");
|
||||
assert!(snapshot.collection_expired(expired));
|
||||
provider.shutdown().expect("shutdown test provider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_successful_collection_cannot_publish_an_already_expired_observation() {
|
||||
let (provider, exporter, mut snapshot) = setup();
|
||||
|
||||
@@ -140,6 +140,11 @@ impl Principal {
|
||||
pub fn is_public(&self) -> bool {
|
||||
self.is_match("*") || self.is_match("")
|
||||
}
|
||||
|
||||
/// Whether an AWS entry is empty or uses a wildcard in a name or ARN.
|
||||
pub fn has_non_exact_aws_principal(&self) -> bool {
|
||||
self.aws.iter().any(|entry| entry.is_empty() || entry.contains(['*', '?']))
|
||||
}
|
||||
}
|
||||
|
||||
impl Validator for Principal {
|
||||
@@ -265,4 +270,18 @@ mod test {
|
||||
// matching it must be classified as public.
|
||||
assert!(!principal.is_match("") || principal.is_public(), "input: {json}");
|
||||
}
|
||||
|
||||
#[test_case(r#""*""#, true ; "wildcard_root")]
|
||||
#[test_case(r#"{"AWS": ""}"#, true ; "empty_aws_string")]
|
||||
#[test_case(r#"{"AWS": [""]}"#, true ; "empty_aws_array")]
|
||||
#[test_case(r#"{"AWS": "?"}"#, true ; "question_mark")]
|
||||
#[test_case(r#"{"AWS": ["alice*"]}"#, true ; "prefix_wildcard")]
|
||||
#[test_case(r#"{"AWS": ["user-?"]}"#, true ; "single_char_pattern")]
|
||||
#[test_case(r#"{"AWS": ["alice", "arn:aws:iam::123456789012:user/*"]}"#, true ; "mixed_exact_and_arn_pattern")]
|
||||
#[test_case(r#"{"AWS": ["alice"]}"#, false ; "exact_user")]
|
||||
#[test_case(r#"{"Service": "logging.s3.amazonaws.com"}"#, false ; "exact_service")]
|
||||
fn test_principal_has_non_exact_aws_principal(json: &str, expected: bool) {
|
||||
let principal: Principal = serde_json::from_str(json).expect("Should parse");
|
||||
assert_eq!(principal.has_non_exact_aws_principal(), expected, "input: {json}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,17 +169,29 @@ fn vector_condition_is_supported(action: S3VectorsAction, key: &KeyName) -> bool
|
||||
}
|
||||
|
||||
fn validate_vector_statement(
|
||||
effect: &Effect,
|
||||
actions: &ActionSet,
|
||||
not_actions: &ActionSet,
|
||||
resources: &ResourceSet,
|
||||
not_resources: &ResourceSet,
|
||||
conditions: &Functions,
|
||||
) -> Result<()> {
|
||||
let has_vector_action = actions.iter().any(|action| matches!(action, Action::S3VectorsAction(_)));
|
||||
// Allow/NotAction is limited to the named families. Deny/NotAction covers the
|
||||
// complement across services, so its exceptions do not scope the resources.
|
||||
let exclusions_scope_grant = matches!(effect, Effect::Allow) && !not_actions.is_empty();
|
||||
let scoped_actions = if exclusions_scope_grant { not_actions } else { actions };
|
||||
let has_vector_action = scoped_actions
|
||||
.iter()
|
||||
.any(|action| matches!(action, Action::S3VectorsAction(_)));
|
||||
let has_vector_resource = resources
|
||||
.iter()
|
||||
.chain(not_resources.iter())
|
||||
.any(|resource| matches!(resource, Resource::S3Vectors(_)));
|
||||
if has_vector_action && actions.iter().any(|action| !matches!(action, Action::S3VectorsAction(_))) {
|
||||
if has_vector_action
|
||||
&& scoped_actions
|
||||
.iter()
|
||||
.any(|action| !matches!(action, Action::S3VectorsAction(_)))
|
||||
{
|
||||
return Err(IamError::MixedActionFamilies.into());
|
||||
}
|
||||
if (has_vector_action
|
||||
@@ -188,7 +200,7 @@ fn validate_vector_statement(
|
||||
.chain(not_resources.iter())
|
||||
.any(|resource| !matches!(resource, Resource::S3Vectors(_) | Resource::All)))
|
||||
|| (has_vector_resource
|
||||
&& actions
|
||||
&& scoped_actions
|
||||
.iter()
|
||||
.any(|action| !matches!(action, Action::S3VectorsAction(_) | Action::All)))
|
||||
{
|
||||
@@ -197,7 +209,7 @@ fn validate_vector_statement(
|
||||
if has_vector_action || has_vector_resource {
|
||||
for key in conditions.keys() {
|
||||
key.is_valid()?;
|
||||
let supported = if has_vector_action {
|
||||
let supported = if has_vector_action && !exclusions_scope_grant {
|
||||
actions.iter().any(|action| {
|
||||
matches!(action, Action::S3VectorsAction(action) if vector_condition_is_supported(*action, &key.name))
|
||||
})
|
||||
@@ -513,7 +525,16 @@ impl Statement {
|
||||
let Some(resource) = requested_vector_resource(action, args.bucket, args.object, args.conditions) else {
|
||||
return false;
|
||||
};
|
||||
if validate_vector_statement(&self.actions, &self.resources, &self.not_resources, &self.conditions).is_err() {
|
||||
if validate_vector_statement(
|
||||
&self.effect,
|
||||
&self.actions,
|
||||
&self.not_actions,
|
||||
&self.resources,
|
||||
&self.not_resources,
|
||||
&self.conditions,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let dyn_resolver = resolver.map(|r| r as &dyn super::variables::PolicyVariableResolver);
|
||||
@@ -641,7 +662,14 @@ impl Validator for Statement {
|
||||
self.not_actions.is_valid()?;
|
||||
self.resources.is_valid()?;
|
||||
self.not_resources.is_valid()?;
|
||||
validate_vector_statement(&self.actions, &self.resources, &self.not_resources, &self.conditions)?;
|
||||
validate_vector_statement(
|
||||
&self.effect,
|
||||
&self.actions,
|
||||
&self.not_actions,
|
||||
&self.resources,
|
||||
&self.not_resources,
|
||||
&self.conditions,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -713,7 +741,16 @@ impl BPStatement {
|
||||
let Some(resource) = requested_vector_resource(action, args.bucket, args.object, args.conditions) else {
|
||||
return false;
|
||||
};
|
||||
if validate_vector_statement(&self.actions, &self.resources, &self.not_resources, &self.conditions).is_err() {
|
||||
if validate_vector_statement(
|
||||
&self.effect,
|
||||
&self.actions,
|
||||
&self.not_actions,
|
||||
&self.resources,
|
||||
&self.not_resources,
|
||||
&self.conditions,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return vector_scope_matches(&self.resources, &self.not_resources, &resource, args.conditions, None).await;
|
||||
@@ -809,7 +846,14 @@ impl Validator for BPStatement {
|
||||
self.not_actions.is_valid()?;
|
||||
self.resources.is_valid()?;
|
||||
self.not_resources.is_valid()?;
|
||||
validate_vector_statement(&self.actions, &self.resources, &self.not_resources, &self.conditions)?;
|
||||
validate_vector_statement(
|
||||
&self.effect,
|
||||
&self.actions,
|
||||
&self.not_actions,
|
||||
&self.resources,
|
||||
&self.not_resources,
|
||||
&self.conditions,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1279,4 +1323,57 @@ mod s3vectors_tests {
|
||||
.expect("named principal policy must deserialize");
|
||||
assert!(!policy.statements[0].principal.is_match("*"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn s3vectors_deny_not_action_preserves_cross_service_exceptions() {
|
||||
let policy = policy(json!([
|
||||
{"Effect":"Allow","Action":"s3vectors:*","Resource":INDEX},
|
||||
{"Effect":"Deny","NotAction":["s3:GetObject","s3vectors:GetVectors"],"Resource":INDEX}
|
||||
]));
|
||||
let context = conditions();
|
||||
assert!(allowed(&policy, "s3vectors:GetVectors", "media", "embeddings.v1", &context).await);
|
||||
assert!(!allowed(&policy, "s3vectors:QueryVectors", "media", "embeddings.v1", &context).await);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn s3vectors_allow_not_action_enforces_family_resource_and_condition_isolation() {
|
||||
for invalid in [
|
||||
json!({
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{"Effect":"Allow","NotAction":["s3vectors:GetVectors","s3:GetObject"],"Resource":"*"}]
|
||||
}),
|
||||
json!({
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{"Effect":"Allow","NotAction":"s3vectors:GetVectors","Resource":"arn:aws:s3:::my-bucket"}]
|
||||
}),
|
||||
json!({
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{"Effect":"Allow","NotAction":"s3:GetObject","Resource":INDEX}]
|
||||
}),
|
||||
json!({
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{
|
||||
"Effect":"Allow",
|
||||
"NotAction":"s3vectors:GetVectors",
|
||||
"Resource":"*",
|
||||
"Condition":{"StringEquals":{"s3:prefix":"secret"}}
|
||||
}]
|
||||
}),
|
||||
] {
|
||||
let policy: Policy = parse_json(invalid.clone()).expect("statement shape parses");
|
||||
assert!(policy.is_valid().is_err(), "expected invalid NotAction statement: {invalid}");
|
||||
}
|
||||
|
||||
let valid: Policy = parse_json(json!({
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{
|
||||
"Effect":"Allow",
|
||||
"NotAction":"s3vectors:GetVectors",
|
||||
"Resource":"*",
|
||||
"Condition":{"StringEquals":{"aws:RequestedRegion":"us-east-1"}}
|
||||
}]
|
||||
}))
|
||||
.expect("valid NotAction policy must parse");
|
||||
valid.is_valid().expect("valid NotAction policy must validate");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1120,6 +1120,9 @@ pub struct Metrics {
|
||||
scanner_checkpoint: Mutex<Option<ScannerCheckpointReport>>,
|
||||
scanner_checkpoints_persisted: Mutex<BTreeMap<(usize, usize), ScannerPersistedCheckpointReport>>,
|
||||
scanner_checkpoint_save_failures: AtomicU64,
|
||||
scanner_progress_prepare_timeouts: AtomicU64,
|
||||
scanner_progress_writes: AtomicU64,
|
||||
scanner_progress_write_failures: AtomicU64,
|
||||
scanner_checkpoint_used: AtomicU64,
|
||||
scanner_checkpoint_cleared: AtomicU64,
|
||||
scanner_checkpoint_ignored: AtomicU64,
|
||||
@@ -1717,6 +1720,13 @@ pub struct ScannerMetricsReport {
|
||||
pub scan_checkpoint_save_failures: u64,
|
||||
#[serde(default)]
|
||||
pub scan_checkpoint_used: u64,
|
||||
/// Initial/display progress failures do not invalidate a saved checkpoint.
|
||||
#[serde(default)]
|
||||
pub scan_progress_prepare_timeouts: u64,
|
||||
#[serde(default)]
|
||||
pub scan_progress_writes: u64,
|
||||
#[serde(default)]
|
||||
pub scan_progress_write_failures: u64,
|
||||
#[serde(default)]
|
||||
pub scan_checkpoint_cleared: u64,
|
||||
#[serde(default)]
|
||||
@@ -2337,6 +2347,9 @@ impl Metrics {
|
||||
scanner_checkpoint: Mutex::new(None),
|
||||
scanner_checkpoints_persisted: Mutex::new(BTreeMap::new()),
|
||||
scanner_checkpoint_save_failures: AtomicU64::new(0),
|
||||
scanner_progress_prepare_timeouts: AtomicU64::new(0),
|
||||
scanner_progress_writes: AtomicU64::new(0),
|
||||
scanner_progress_write_failures: AtomicU64::new(0),
|
||||
scanner_checkpoint_used: AtomicU64::new(0),
|
||||
scanner_checkpoint_cleared: AtomicU64::new(0),
|
||||
scanner_checkpoint_ignored: AtomicU64::new(0),
|
||||
@@ -2703,6 +2716,18 @@ impl Metrics {
|
||||
self.update_scanner_checkpoint_event(SCANNER_CHECKPOINT_EVENT_USED);
|
||||
}
|
||||
|
||||
pub fn record_scanner_progress_prepare_timeout(&self) {
|
||||
self.scanner_progress_prepare_timeouts.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn record_scanner_progress_write(&self, success: bool) {
|
||||
if success {
|
||||
self.scanner_progress_writes.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
self.scanner_progress_write_failures.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_scanner_checkpoint_cleared(&self) {
|
||||
self.scanner_checkpoint_cleared.fetch_add(1, Ordering::Relaxed);
|
||||
match self.scanner_checkpoint.lock() {
|
||||
@@ -4109,6 +4134,9 @@ impl Metrics {
|
||||
.collect();
|
||||
m.scan_checkpoint_save_failures = self.scanner_checkpoint_save_failures.load(Ordering::Relaxed);
|
||||
m.scan_checkpoint_used = self.scanner_checkpoint_used.load(Ordering::Relaxed);
|
||||
m.scan_progress_prepare_timeouts = self.scanner_progress_prepare_timeouts.load(Ordering::Relaxed);
|
||||
m.scan_progress_writes = self.scanner_progress_writes.load(Ordering::Relaxed);
|
||||
m.scan_progress_write_failures = self.scanner_progress_write_failures.load(Ordering::Relaxed);
|
||||
m.scan_checkpoint_cleared = self.scanner_checkpoint_cleared.load(Ordering::Relaxed);
|
||||
m.scan_checkpoint_ignored = self.scanner_checkpoint_ignored.load(Ordering::Relaxed);
|
||||
m.scan_checkpoint_stale = self.scanner_checkpoint_stale.load(Ordering::Relaxed);
|
||||
@@ -6312,8 +6340,23 @@ mod tests {
|
||||
assert_eq!(report.usage_publication.pending_bucket_count, None);
|
||||
let mut legacy = serde_json::to_value(report).expect("serialize scanner report");
|
||||
legacy.as_object_mut().expect("report object").remove("usage_publication");
|
||||
for field in [
|
||||
"scan_progress_prepare_timeouts",
|
||||
"scan_progress_writes",
|
||||
"scan_progress_write_failures",
|
||||
] {
|
||||
legacy.as_object_mut().expect("report object").remove(field);
|
||||
}
|
||||
let legacy: ScannerMetricsReport = serde_json::from_value(legacy).expect("decode legacy report");
|
||||
assert_eq!(legacy.usage_publication, ScannerUsagePublicationStatus::default());
|
||||
assert_eq!(
|
||||
(
|
||||
legacy.scan_progress_prepare_timeouts,
|
||||
legacy.scan_progress_writes,
|
||||
legacy.scan_progress_write_failures
|
||||
),
|
||||
(0, 0, 0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -28,12 +28,12 @@ use metrics::{counter, describe_counter, describe_histogram, histogram};
|
||||
#[cfg(test)]
|
||||
use rustfs_config::ENV_SCANNER_CACHE_SAVE_TIMEOUT_SECS;
|
||||
pub use rustfs_data_usage::{
|
||||
AllTierStats, BucketTargetUsageInfo, BucketUsageInfo, DATA_USAGE_OBJECT_NAME, DATA_USAGE_OBSERVED_OBJECT_NAME,
|
||||
DataUsageEntry, DataUsageHash, DataUsageHashMap, DataUsageInfo, DataUsageSegmentInvalidationProof, DataUsageSnapshotSetState,
|
||||
LEGACY_DATA_USAGE_OBJECT_NAME, PrefixUsageEntry, PrefixUsageQuery, PrefixUsageSummary, ReplTargetSizeSummary,
|
||||
SizeReconciliationEntry, SizeReconciliationScope, SizeSummary, TierAccountingProof, TierStats, UNKNOWN_TIER,
|
||||
UNKNOWN_TIER_DIAGNOSTIC_BYTE_CAP, UNKNOWN_TIER_DIAGNOSTIC_ENTRY_CAP, UnknownTierStats, clone_cache_value, hash_path,
|
||||
prefix_usage_in_cache,
|
||||
AllTierStats, BucketTargetUsageInfo, BucketUsageInfo, DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME, DATA_USAGE_OBJECT_NAME,
|
||||
DATA_USAGE_OBSERVED_OBJECT_NAME, DataUsageEntry, DataUsageHash, DataUsageHashMap, DataUsageInfo,
|
||||
DataUsageSegmentInvalidationProof, DataUsageSnapshotSetState, LEGACY_DATA_USAGE_OBJECT_NAME, PrefixUsageEntry,
|
||||
PrefixUsageQuery, PrefixUsageSummary, ReplTargetSizeSummary, SizeReconciliationEntry, SizeReconciliationScope, SizeSummary,
|
||||
TierAccountingProof, TierStats, UNKNOWN_TIER, UNKNOWN_TIER_DIAGNOSTIC_BYTE_CAP, UNKNOWN_TIER_DIAGNOSTIC_ENTRY_CAP,
|
||||
UnknownTierStats, clone_cache_value, hash_path, prefix_usage_in_cache,
|
||||
};
|
||||
use rustfs_heal_contracts::heal_channel::HealScanMode;
|
||||
use rustfs_utils::path::{SLASH_SEPARATOR, path_join_buf};
|
||||
@@ -261,6 +261,9 @@ pub static DATA_USAGE_RECOVERY_PATH: LazyLock<String> =
|
||||
pub static DATA_USAGE_OBSERVED_OBJ_NAME_PATH: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{DATA_USAGE_OBSERVED_OBJECT_NAME}"));
|
||||
|
||||
pub static DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{DATA_USAGE_CERTIFIED_BUCKETS_OBJECT_NAME}"));
|
||||
|
||||
pub static LEGACY_DATA_USAGE_OBJ_NAME_PATH: LazyLock<String> =
|
||||
LazyLock::new(|| format!("{BUCKET_META_PREFIX}{SLASH_SEPARATOR}{LEGACY_DATA_USAGE_OBJECT_NAME}"));
|
||||
|
||||
@@ -302,7 +305,11 @@ impl ScannerSizeSummaryExt for SizeSummary {
|
||||
self.versions = self.versions.saturating_add(1);
|
||||
}
|
||||
|
||||
let logical_size = size.max(0);
|
||||
let logical_size = if crate::storage_api::is_vector_pagination_session(&oi.bucket, &oi.name) {
|
||||
0
|
||||
} else {
|
||||
size.max(0)
|
||||
};
|
||||
let size = usize::try_from(logical_size).unwrap_or(usize::MAX);
|
||||
self.total_size = self.total_size.saturating_add(size);
|
||||
let logical_bytes = u64::try_from(logical_size).unwrap_or(u64::MAX);
|
||||
@@ -524,6 +531,22 @@ impl DataUsageScanIdentity {
|
||||
&& !self.bucket_incarnation.is_nil()
|
||||
&& matches!(self.scan_mode, HealScanMode::Normal | HealScanMode::Deep)
|
||||
}
|
||||
|
||||
/// Whether two identities fence the same bucket checkpoint scope.
|
||||
///
|
||||
/// `publication_epoch` is a process-local data-movement counter. It moves
|
||||
/// on leader handoff and cold restart without changing the namespace a
|
||||
/// checkpoint traverses, so it must not decide whether a durable cursor is
|
||||
/// adoptable. The bucket incarnation, set layout, tier generation and scan
|
||||
/// mode all describe the namespace or the way it is walked and still fence
|
||||
/// a checkpoint exactly.
|
||||
pub(crate) fn same_checkpoint_scope(&self, other: &Self) -> bool {
|
||||
self.version == other.version
|
||||
&& self.bucket_incarnation == other.bucket_incarnation
|
||||
&& self.set_layout == other.set_layout
|
||||
&& self.tier_registry_generation == other.tier_registry_generation
|
||||
&& self.scan_mode == other.scan_mode
|
||||
}
|
||||
}
|
||||
|
||||
/// A forward coverage sweep may span budgets, but not authorize mixed mutation generations.
|
||||
@@ -672,7 +695,13 @@ impl DataUsageDurableProgress {
|
||||
|| self.source.is_none()
|
||||
|| self.source != previous.source
|
||||
|| !self.identity.is_some_and(|identity| identity.is_valid())
|
||||
|| self.identity != previous.identity
|
||||
// A leader handoff or cold restart changes only the process-local
|
||||
// publication epoch. Cursor movement remains durable progress under
|
||||
// the same bucket scope, so compare the stable checkpoint fields.
|
||||
|| !self
|
||||
.identity
|
||||
.zip(previous.identity)
|
||||
.is_some_and(|(current, previous)| current.same_checkpoint_scope(&previous))
|
||||
|| self.started_plan.is_none()
|
||||
|| self.started_plan != previous.started_plan
|
||||
{
|
||||
@@ -1485,35 +1514,31 @@ impl DataUsageCache {
|
||||
.into_iter()
|
||||
.filter(|(bucket, observation)| bucket == name && observation.matches(source, identity))
|
||||
.collect();
|
||||
// A checkpoint is a durable traversal frontier, not a publication
|
||||
// result. A newer leader may adopt it only when the frontier is
|
||||
// independently fenced by the bucket identity and has a validated
|
||||
// cursor/coverage receipt. Caches without that proof still take the
|
||||
// normal rebuild path; this keeps an old, incomplete writer from
|
||||
// authorizing a new leader to skip namespace coverage.
|
||||
// Cycle deadlines advance both counters, so a validated frontier from
|
||||
// an earlier cycle must remain eligible for adoption.
|
||||
let checking_handoff = self.info.leader_epoch < leader_epoch && self.info.scan_identity == Some(identity);
|
||||
let handoff_digest = if checking_handoff {
|
||||
self.validated_scan_frontier_receipt().map(|(_, digest)| digest)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let cross_epoch_checkpoint = checking_handoff
|
||||
&& (handoff_digest.is_some()
|
||||
|| self.validated_raw_enumeration_cursor().is_some()
|
||||
|| self.validated_raw_enumeration_page_index().is_some()
|
||||
|| self.info.scan_directory_work.iter().any(|d| d.is_bound_to(&self.info)));
|
||||
// The durable cursor is scoped to the bucket and its layout. The
|
||||
// local publication epoch still fences writes, but can change on restart.
|
||||
let saved_identity = self.info.scan_identity;
|
||||
let checkpoint_identity_matches =
|
||||
saved_identity.is_some_and(|saved| saved.is_valid() && saved.same_checkpoint_scope(&identity));
|
||||
let frontier_receipt = checkpoint_identity_matches
|
||||
.then(|| self.validated_scan_frontier_receipt())
|
||||
.flatten()
|
||||
.map(|(path, digest)| (clone_cache_value(path), digest));
|
||||
let bare_cursor = self.validated_bare_scan_cursor().is_some();
|
||||
let valid_cursor = frontier_receipt.is_some() || bare_cursor;
|
||||
let cross_epoch_checkpoint = self.info.leader_epoch < leader_epoch
|
||||
&& checkpoint_identity_matches
|
||||
&& (valid_cursor || self.has_validated_directory_position());
|
||||
let reusable = identity.is_valid()
|
||||
&& name != DATA_USAGE_ROOT
|
||||
&& self.info.name == name
|
||||
&& self.info.source == Some(source)
|
||||
&& (self.info.leader_epoch == leader_epoch || cross_epoch_checkpoint)
|
||||
&& self.info.cache_key_format == DATA_USAGE_CACHE_KEY_FORMAT
|
||||
&& self.info.scan_identity == Some(identity)
|
||||
&& checkpoint_identity_matches
|
||||
&& self.info.tier_registry_generation == Some(identity.tier_registry_generation)
|
||||
&& (self.cache.is_empty() || self.checked_flatten_complete_scope(name).is_some());
|
||||
if reusable
|
||||
&& saved_identity == Some(identity)
|
||||
&& self.info.snapshot_complete
|
||||
&& self.info.scan_progress.is_none()
|
||||
&& !self.has_scan_position()
|
||||
@@ -1521,6 +1546,22 @@ impl DataUsageCache {
|
||||
{
|
||||
return self.prepare_for_scan(name, next_cycle, leader_epoch, source, scan_plan_digest, true);
|
||||
}
|
||||
if reusable && (valid_cursor || self.has_validated_directory_position()) {
|
||||
let reason = if self
|
||||
.info
|
||||
.scan_progress
|
||||
.is_some_and(|progress| progress.started_plan != checkpoint_plan_digest)
|
||||
{
|
||||
"plan_changed"
|
||||
} else if bare_cursor {
|
||||
"cursor_without_receipt"
|
||||
} else if cross_epoch_checkpoint || saved_identity != Some(identity) {
|
||||
"cross_epoch"
|
||||
} else {
|
||||
"same_epoch"
|
||||
};
|
||||
counter!("rustfs_scanner_checkpoint_decisions_total", "decision" => "adopted", "reason" => reason).increment(1);
|
||||
}
|
||||
if !reusable {
|
||||
if self.has_scan_position() {
|
||||
let reason = if name == DATA_USAGE_ROOT {
|
||||
@@ -1533,15 +1574,23 @@ impl DataUsageCache {
|
||||
"source_mismatch"
|
||||
} else if self.info.cache_key_format != DATA_USAGE_CACHE_KEY_FORMAT {
|
||||
"key_format_mismatch"
|
||||
} else if self.info.scan_identity != Some(identity)
|
||||
|| self.info.tier_registry_generation != Some(identity.tier_registry_generation)
|
||||
{
|
||||
} else if self.info.tier_registry_generation != Some(identity.tier_registry_generation) {
|
||||
"tier_generation_mismatch"
|
||||
} else if !checkpoint_identity_matches {
|
||||
"identity_mismatch"
|
||||
} else if self.info.leader_epoch != leader_epoch && !cross_epoch_checkpoint {
|
||||
"unvalidated_handoff"
|
||||
} else if !valid_cursor && !self.has_validated_directory_position() {
|
||||
"invalid_cursor"
|
||||
} else {
|
||||
"incomplete_cache_scope"
|
||||
};
|
||||
counter!(
|
||||
"rustfs_scanner_checkpoint_decisions_total",
|
||||
"decision" => "reset",
|
||||
"reason" => reason
|
||||
)
|
||||
.increment(1);
|
||||
warn!(
|
||||
target: "rustfs::scanner::data_usage",
|
||||
event = EVENT_SCANNER_CACHE_LOAD_STATE,
|
||||
@@ -1591,11 +1640,7 @@ impl DataUsageCache {
|
||||
|| !self.info.scan_directory_work.is_empty()
|
||||
|| self.info.scan_raw_enumeration_cursor.is_some()
|
||||
|| self.info.scan_raw_enumeration_page_index.is_some()
|
||||
|| if checking_handoff {
|
||||
handoff_digest.is_some()
|
||||
} else {
|
||||
self.validated_scan_frontier().is_some()
|
||||
};
|
||||
|| (reusable && valid_cursor);
|
||||
if !cursor_is_valid {
|
||||
self.info.scan_progress = None;
|
||||
}
|
||||
@@ -1607,13 +1652,14 @@ impl DataUsageCache {
|
||||
self.info.tier_registry_generation = Some(identity.tier_registry_generation);
|
||||
self.info.scan_identity = Some(identity);
|
||||
self.info.snapshot_complete = false;
|
||||
if reusable
|
||||
&& let Some(digest) = handoff_digest
|
||||
&& let Some(receipt) = self.info.scan_coverage_receipt.as_mut()
|
||||
{
|
||||
// Reuse the digest computed during handoff validation. Only the
|
||||
// leader epoch and fields outside the digest have changed here.
|
||||
receipt.digest = digest;
|
||||
if reusable && let Some((frontier, digest)) = frontier_receipt {
|
||||
if saved_identity != Some(identity) {
|
||||
if self.seal_scan_frontier(Some(&frontier)).is_err() {
|
||||
self.info.scan_progress = None;
|
||||
}
|
||||
} else if cross_epoch_checkpoint && let Some(receipt) = self.info.scan_coverage_receipt.as_mut() {
|
||||
receipt.digest = digest;
|
||||
}
|
||||
}
|
||||
// A sweep without a durable position restarts from the first entry,
|
||||
// so it observes nothing under the plan that finished the previous
|
||||
@@ -1781,6 +1827,36 @@ impl DataUsageCache {
|
||||
.then_some((through, current.unwrap_or(receipt.digest)))
|
||||
}
|
||||
|
||||
/// A legacy cursor can preserve a scheduling position. Only a validated
|
||||
/// coverage receipt can authorize skipping a prefix.
|
||||
pub(crate) fn validated_bare_scan_cursor(&self) -> Option<&str> {
|
||||
let cursor = self.info.scan_resume_after.as_deref()?;
|
||||
(self.info.scan_coverage_receipt.is_none()
|
||||
&& self.info.scan_progress.is_some()
|
||||
&& self.info.scan_identity.is_some_and(|identity| identity.is_valid())
|
||||
&& self.info.source.is_some()
|
||||
&& self.info.name != DATA_USAGE_ROOT
|
||||
&& cursor.len() <= DATA_USAGE_SCAN_CURSOR_MAX_BYTES
|
||||
&& !cursor.is_empty()
|
||||
&& path_is_in_bucket_scope(&self.info.name, cursor)
|
||||
&& self.find(cursor).is_some()
|
||||
&& self.info.scan_checkpoint.as_ref().is_none_or(|checkpoint| {
|
||||
checkpoint.version == DATA_USAGE_SCAN_CHECKPOINT_VERSION && checkpoint.resume_after == cursor
|
||||
}))
|
||||
.then_some(cursor)
|
||||
}
|
||||
|
||||
pub(crate) fn has_validated_directory_position(&self) -> bool {
|
||||
self.validated_bare_scan_cursor().is_some()
|
||||
|| self.validated_raw_enumeration_cursor().is_some()
|
||||
|| self.validated_raw_enumeration_page_index().is_some()
|
||||
|| self
|
||||
.info
|
||||
.scan_directory_work
|
||||
.iter()
|
||||
.any(|receipt| receipt.is_bound_to(&self.info))
|
||||
}
|
||||
|
||||
pub(crate) fn validated_raw_enumeration_cursor(&self) -> Option<&DataUsageRawEnumerationCursor> {
|
||||
let cursor = self.info.scan_raw_enumeration_cursor.as_ref()?;
|
||||
(self.info.scan_progress.is_some()
|
||||
|
||||
@@ -229,6 +229,18 @@ impl DataUsageCache {
|
||||
},
|
||||
objects: accepted.map(|(objects, _, _)| u64::try_from(objects)).transpose().ok()?,
|
||||
size: accepted.map(|(_, size, _)| u64::try_from(size)).transpose().ok()?,
|
||||
blocker: (completed.is_none()).then(|| {
|
||||
self.info
|
||||
.scan_checkpoint
|
||||
.as_ref()
|
||||
.map_or("unknown", |checkpoint| match checkpoint.reason {
|
||||
super::DataUsageScanCheckpointReason::Runtime => "runtime_budget",
|
||||
super::DataUsageScanCheckpointReason::Objects => "object_budget",
|
||||
super::DataUsageScanCheckpointReason::Directories => "directory_budget",
|
||||
super::DataUsageScanCheckpointReason::Unknown => "unknown",
|
||||
})
|
||||
.to_owned()
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -273,6 +285,7 @@ impl DataUsageCache {
|
||||
// previous accepted sample and its original time until it has another
|
||||
// measured range. This is a whole observation, never an added delta.
|
||||
let sample = previous
|
||||
.as_ref()
|
||||
.filter(|previous| {
|
||||
sample.objects.is_none()
|
||||
&& previous.objects.is_some()
|
||||
@@ -286,7 +299,29 @@ impl DataUsageCache {
|
||||
&& previous.set_layout == sample.set_layout
|
||||
&& (previous.scanner_epoch, previous.scanner_cycle) <= (sample.scanner_epoch, sample.scanner_cycle)
|
||||
})
|
||||
.cloned()
|
||||
.unwrap_or(sample);
|
||||
// Idempotent per durable position: repeated checkpoints at the same
|
||||
// cycle, epoch and accepted values must not churn the shared object.
|
||||
// A later turn in the same cycle still replaces it when the sample
|
||||
// grew, and completion always publishes the final authoritative value.
|
||||
if let Some(previous) = &previous
|
||||
&& previous.matches(
|
||||
&sample.bucket,
|
||||
&sample.bucket_incarnation,
|
||||
(sample.pool_index, sample.set_index),
|
||||
movement_generation,
|
||||
)
|
||||
&& previous.set_layout == sample.set_layout
|
||||
&& previous.scanner_epoch == sample.scanner_epoch
|
||||
&& previous.scanner_cycle == sample.scanner_cycle
|
||||
&& previous.stage == sample.stage
|
||||
&& previous.objects == sample.objects
|
||||
&& previous.size == sample.size
|
||||
&& previous.blocker == sample.blocker
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((path, serde_json::to_vec(&sample).ok()?, revision))
|
||||
}
|
||||
|
||||
@@ -300,11 +335,12 @@ impl DataUsageCache {
|
||||
};
|
||||
// A diagnostic write failure must not invalidate a durable checkpoint.
|
||||
// The next admitted checkpoint retries, with no request-path S3 listing.
|
||||
let _ = timeout(
|
||||
let result = timeout(
|
||||
Duration::from_secs(2),
|
||||
crate::save_config_with_publication_admission_for_epoch(store, &path, data, revision.preconditions(), epoch),
|
||||
)
|
||||
.await;
|
||||
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_progress_write(matches!(result, Ok(Ok(_))));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -808,7 +808,7 @@ impl DataUsageCache {
|
||||
_ => (inline.clone(), [None, None]),
|
||||
};
|
||||
let path = path_join_buf(&[BUCKET_META_PREFIX, name]);
|
||||
let display_progress = timeout(Duration::from_secs(2), async {
|
||||
let display_progress = match timeout(Duration::from_secs(2), async {
|
||||
let input = if expected_epoch.is_some() && self.info.scan_identity.is_some() && self.info.name != DATA_USAGE_ROOT {
|
||||
match &encoded {
|
||||
Some(encoded) => encoded.progress_input().await,
|
||||
@@ -820,8 +820,13 @@ impl DataUsageCache {
|
||||
self.prepare_display_progress(store.clone(), expected_epoch, input).await
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
{
|
||||
Ok(prepared) => prepared,
|
||||
Err(_) => {
|
||||
rustfs_scanner_metrics::metrics::global_metrics().record_scanner_progress_prepare_timeout();
|
||||
None
|
||||
}
|
||||
};
|
||||
let primary_save_started = Instant::now();
|
||||
let main = Self::save_path_with_retry(
|
||||
store.clone(),
|
||||
|
||||
@@ -50,13 +50,19 @@ impl Serialize for OrderedEntries<'_> {
|
||||
}
|
||||
|
||||
impl SourceTree {
|
||||
fn matches(&self, bucket: &str, identity: DataUsageScanIdentity, started_plan: DataUsageScanPlanDigest) -> bool {
|
||||
self.bucket == bucket
|
||||
&& self.identity.is_valid()
|
||||
&& identity.is_valid()
|
||||
&& self.identity.same_checkpoint_scope(&identity)
|
||||
&& self.started_plan == started_plan
|
||||
}
|
||||
|
||||
/// An inactive receipt may preserve an existing source position. Only an
|
||||
/// active, verified traversal can contribute new progress.
|
||||
pub(super) fn frontier(&self, info: &DataUsageCacheInfo) -> Option<&str> {
|
||||
if self.bucket != info.name
|
||||
|| Some(self.identity) != info.scan_identity
|
||||
|| Some(self.started_plan) != info.scan_progress.map(|p| p.started_plan)
|
||||
{
|
||||
let (identity, progress) = (info.scan_identity?, info.scan_progress?);
|
||||
if !self.matches(&info.name, identity, progress.started_plan) {
|
||||
return None;
|
||||
}
|
||||
self.coverage.as_ref().map(|receipt| receipt.through.as_str())
|
||||
@@ -89,9 +95,7 @@ impl DataUsageCache {
|
||||
&& directory_source_location(work.endpoint()) != current_location
|
||||
});
|
||||
self.info.scan_source_trees.retain(|key, tree| {
|
||||
tree.bucket == self.info.name
|
||||
&& tree.identity == identity
|
||||
&& tree.started_plan == progress.started_plan
|
||||
tree.matches(&self.info.name, identity, progress.started_plan)
|
||||
&& (key == &source
|
||||
|| endpoints.contains(directory_source_location(key)) && directory_source_location(key) != current_location)
|
||||
});
|
||||
@@ -140,9 +144,21 @@ impl DataUsageCache {
|
||||
self.info.scan_raw_enumeration_page_index = tree.index;
|
||||
self.info.scan_raw_enumeration_path_page_indexes = tree.ancestors;
|
||||
// A dormant tree must provide the same coverage/graph guarantees
|
||||
// required of an active checkpoint before its child links are used.
|
||||
if self.checked_flatten_complete_scope(&self.info.name).is_none()
|
||||
|| self.info.scan_coverage_receipt.is_some() && self.validated_scan_frontier().is_none()
|
||||
// required of an active checkpoint. Validate its receipt under the
|
||||
// saved identity before re-signing it under the adopted epoch;
|
||||
// signing first would turn corrupt accounting into trusted work.
|
||||
self.info.scan_identity = Some(tree.identity);
|
||||
let graph_valid = self.checked_flatten_complete_scope(&self.info.name).is_some();
|
||||
let frontier = self.validated_scan_frontier().map(str::to_owned);
|
||||
let receipt_valid = self.info.scan_coverage_receipt.is_none() || frontier.is_some();
|
||||
self.info.scan_identity = Some(identity);
|
||||
if !graph_valid || !receipt_valid {
|
||||
self.clear_active_directory_traversal();
|
||||
return;
|
||||
}
|
||||
if tree.identity != identity
|
||||
&& let Some(frontier) = frontier
|
||||
&& self.seal_scan_frontier(Some(&frontier)).is_err()
|
||||
{
|
||||
self.clear_active_directory_traversal();
|
||||
}
|
||||
@@ -164,6 +180,9 @@ fn directory_source_location(source: &str) -> &str {
|
||||
source.split_once('|').map_or(source, |(_, endpoint)| endpoint)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod handoff_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// Copyright 2026 RustFS Team
|
||||
// Licensed under the Apache License, Version 2.0.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn two_source_checkpoint(v2_receipt: bool) -> (DataUsageCache, HashSet<String>) {
|
||||
let mut cache = DataUsageCache::default();
|
||||
let identity = DataUsageScanIdentity {
|
||||
version: 1,
|
||||
bucket_incarnation: uuid::Uuid::from_u128(1),
|
||||
set_layout: DataUsageScanPlanDigest([2; 32]),
|
||||
publication_epoch: 1,
|
||||
tier_registry_generation: 3,
|
||||
scan_mode: HealScanMode::Normal,
|
||||
};
|
||||
let plan = DataUsageScanPlanDigest([4; 32]);
|
||||
cache.prepare_bucket_checkpoint("bucket", 1, 1, DataUsageCacheSource::new(0, 0), plan, identity);
|
||||
let endpoints = HashSet::from(["a".into(), "b".into()]);
|
||||
for (source, size) in [("disk-a|a", 7), ("disk-b|b", 11)] {
|
||||
cache.activate_directory_source(source.into(), &endpoints);
|
||||
cache.replace("bucket", "", DataUsageEntry::default());
|
||||
cache.replace(
|
||||
"bucket/object",
|
||||
"bucket",
|
||||
DataUsageEntry {
|
||||
objects: 1,
|
||||
versions: 2,
|
||||
size,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
cache.info.scan_resume_after = Some("bucket/object".into());
|
||||
cache.info.scan_checkpoint = Some(DataUsageScanCheckpoint::new(
|
||||
"bucket/object".into(),
|
||||
DataUsageScanCheckpointReason::Objects,
|
||||
));
|
||||
cache
|
||||
.seal_scan_frontier(Some("bucket/object"))
|
||||
.expect("seal measured source coverage");
|
||||
if v2_receipt {
|
||||
let digest = cache
|
||||
.v2_coverage_prefix_digest("bucket/object")
|
||||
.expect("encode v2 source coverage");
|
||||
cache.info.scan_coverage_receipt.as_mut().expect("sealed receipt").digest = digest;
|
||||
}
|
||||
}
|
||||
let next_identity = DataUsageScanIdentity {
|
||||
publication_epoch: 9,
|
||||
..identity
|
||||
};
|
||||
assert_eq!(
|
||||
cache.prepare_bucket_checkpoint("bucket", 2, 2, DataUsageCacheSource::new(0, 0), plan, next_identity),
|
||||
DataUsageCachePrepareOutcome::Reused
|
||||
);
|
||||
(
|
||||
DataUsageCache::unmarshal(&cache.marshal_msg().expect("persist source trees")).expect("cold source tree reload"),
|
||||
endpoints,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dormant_source_restores_and_resigns_coverage_after_epoch_change() {
|
||||
for v2_receipt in [false, true] {
|
||||
let (mut cache, endpoints) = two_source_checkpoint(v2_receipt);
|
||||
cache.activate_directory_source("disk-a|a".into(), &endpoints);
|
||||
assert_eq!(cache.validated_scan_frontier(), Some("bucket/object"));
|
||||
let measured = cache.checked_flatten("bucket").expect("restored connected source tree");
|
||||
assert_eq!((measured.objects, measured.versions, measured.size), (1, 2, 7));
|
||||
assert_eq!(cache.info.scan_identity.expect("current identity").publication_epoch, 9);
|
||||
assert!(!cache.info.snapshot_complete, "a restored prefix is not a certified bucket");
|
||||
cache.activate_directory_source("disk-b|b".into(), &endpoints);
|
||||
assert_eq!(cache.validated_scan_frontier(), Some("bucket/object"));
|
||||
assert_eq!(cache.checked_flatten("bucket").expect("B's own coverage").size, 11);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dormant_source_rejects_corrupt_receipt_after_epoch_change() {
|
||||
for field in 0..3 {
|
||||
let (mut cache, endpoints) = two_source_checkpoint(false);
|
||||
let tree = Arc::make_mut(cache.info.scan_source_trees.get_mut("disk-a|a").expect("dormant source"));
|
||||
match field {
|
||||
0 => tree.coverage.as_mut().expect("source receipt").digest[0] ^= 1,
|
||||
1 => {
|
||||
tree.entries
|
||||
.get_mut(&hash_path("bucket/object").0)
|
||||
.expect("covered entry")
|
||||
.size += 1
|
||||
}
|
||||
2 => tree.checkpoint.as_mut().expect("source checkpoint").resume_after = "bucket/another".into(),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
cache.activate_directory_source("disk-a|a".into(), &endpoints);
|
||||
assert!(cache.cache.is_empty(), "corrupt source field {field} must be rejected before re-signing");
|
||||
assert!(!cache.has_validated_directory_position());
|
||||
assert!(!cache.info.snapshot_complete);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dormant_source_rejects_changed_bucket_scope() {
|
||||
for field in 0..5 {
|
||||
let (mut cache, endpoints) = two_source_checkpoint(false);
|
||||
let tree = Arc::make_mut(cache.info.scan_source_trees.get_mut("disk-a|a").expect("dormant source"));
|
||||
match field {
|
||||
0 => tree.identity.bucket_incarnation = uuid::Uuid::from_u128(99),
|
||||
1 => tree.identity.set_layout = DataUsageScanPlanDigest([99; 32]),
|
||||
2 => tree.identity.tier_registry_generation += 1,
|
||||
3 => tree.identity.scan_mode = HealScanMode::Deep,
|
||||
4 => tree.identity.version += 1,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
cache.activate_directory_source("disk-a|a".into(), &endpoints);
|
||||
assert!(
|
||||
cache.cache.is_empty(),
|
||||
"changed scope field {field} cannot import another source's accounting"
|
||||
);
|
||||
assert!(!cache.has_validated_directory_position());
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,20 @@ mod cache_cost;
|
||||
mod checkpoint_layouts;
|
||||
mod save_metrics;
|
||||
|
||||
#[test]
|
||||
fn quota_exempt_pagination_keeps_physical_bytes_in_scanner_accounting() {
|
||||
let mut summary = SizeSummary::default();
|
||||
let info = ObjectInfo {
|
||||
bucket: "rustfs-v-example".into(),
|
||||
name: format!(".rustfs-table/{}/query-results/{}.session", uuid::Uuid::new_v4(), "a".repeat(64)),
|
||||
size: 79,
|
||||
..Default::default()
|
||||
};
|
||||
summary.actions_accounting(&info, 64, 64);
|
||||
assert_eq!(summary.total_size, 0);
|
||||
assert_eq!(summary.tier_accounting_proof.physical_total, 79);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scoped_scan_coverage_metadata_preserves_map_compatibility() {
|
||||
#[derive(serde::Deserialize)]
|
||||
@@ -4193,7 +4207,13 @@ fn durable_progress_rejects_reset_regression_and_uncommitted_discovery() {
|
||||
assert!(!before.advanced_from(&committed), "a reset is not progress");
|
||||
let mut replaced = committed.clone();
|
||||
replaced.identity.as_mut().expect("identity").publication_epoch += 1;
|
||||
assert!(!replaced.advanced_from(&before));
|
||||
assert!(
|
||||
replaced.advanced_from(&before),
|
||||
"a process-local publication epoch change is not cursor regression"
|
||||
);
|
||||
let mut replaced = committed.clone();
|
||||
replaced.identity.as_mut().expect("identity").bucket_incarnation = uuid::Uuid::from_u128(8);
|
||||
assert!(!replaced.advanced_from(&before), "a changed bucket scope is not progress");
|
||||
replaced = committed;
|
||||
replaced.started_plan = Some(DataUsageScanPlanDigest([99; 32]));
|
||||
assert!(!replaced.advanced_from(&before), "plan changes alone cannot earn another turn");
|
||||
|
||||
@@ -1076,8 +1076,13 @@ pub struct ScannerDataUsagePublicationAdmission {
|
||||
impl ScannerDataUsagePublicationAdmission {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn unfenced() -> Self {
|
||||
Self::unfenced_at_epoch(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn unfenced_at_epoch(epoch: u64) -> Self {
|
||||
Self {
|
||||
epoch: 0,
|
||||
epoch,
|
||||
_read_guard: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -850,7 +850,7 @@ async fn check_signed_scan_request(supports_tier_registry_preflight: bool) {
|
||||
server_epoch: Uuid::new_v4(),
|
||||
session_id: Uuid::new_v4(),
|
||||
session_sequence: 0,
|
||||
plans: ScannerBucketPlanDigests::from_work_plans(reuse, coverage, None),
|
||||
plans: ScannerBucketPlanDigests::from_work_plans(reuse, coverage, None, false),
|
||||
tier_registry_generation: GENERATION,
|
||||
skip_healing: true,
|
||||
scan_mode: HealScanMode::Deep,
|
||||
|
||||
@@ -23,9 +23,9 @@ use self::heal_info::{
|
||||
resolve_background_heal_info_for_cycle, save_background_heal_info_for_epoch, scanner_bitrot_start_for_cycle,
|
||||
};
|
||||
use crate::data_usage_define::{
|
||||
BACKGROUND_HEAL_INFO_PATH, DATA_USAGE_BLOOM_NAME_PATH, DATA_USAGE_OBJ_NAME_PATH, DATA_USAGE_OBSERVED_OBJ_NAME_PATH,
|
||||
DATA_USAGE_RECOVERY_PATH, DataUsageCache, DataUsageCacheRevision, LEGACY_DATA_USAGE_OBJ_NAME_PATH, read_config_revision,
|
||||
read_config_with_revision,
|
||||
BACKGROUND_HEAL_INFO_PATH, DATA_USAGE_BLOOM_NAME_PATH, DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH, DATA_USAGE_OBJ_NAME_PATH,
|
||||
DATA_USAGE_OBSERVED_OBJ_NAME_PATH, DATA_USAGE_RECOVERY_PATH, DataUsageCache, DataUsageCacheRevision,
|
||||
LEGACY_DATA_USAGE_OBJ_NAME_PATH, read_config_revision, read_config_with_revision,
|
||||
};
|
||||
use crate::runtime_config::{
|
||||
ScannerRuntimeConfig, ScannerRuntimeConfigSource, refresh_scanner_runtime_config_from_global, scanner_bitrot_cycle,
|
||||
@@ -654,7 +654,20 @@ where
|
||||
}
|
||||
|
||||
fn data_usage_info_is_cold(info: &DataUsageInfo) -> bool {
|
||||
!info.is_complete_bucket_usage_snapshot()
|
||||
if !info.is_complete_bucket_usage_snapshot() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// A complete snapshot from before bucket incarnations were persisted is
|
||||
// readable, but it is not safe to reuse after a cold restart. The admin
|
||||
// projection intentionally drops those values when it cannot bind them
|
||||
// to the current storage identity, so force a scan to recertify them.
|
||||
info.buckets_usage.values().any(|usage| {
|
||||
usage
|
||||
.bucket_incarnation
|
||||
.as_deref()
|
||||
.is_none_or(|incarnation| Uuid::parse_str(incarnation).map_or(true, |id| id.is_nil()))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn data_usage_info_has_persisted_baseline_identity(info: &DataUsageInfo) -> bool {
|
||||
@@ -676,11 +689,20 @@ pub(super) fn data_usage_info_has_persisted_baseline_identity(info: &DataUsageIn
|
||||
}
|
||||
|
||||
pub(super) fn data_usage_info_is_bootstrap_pending(info: &DataUsageInfo) -> bool {
|
||||
let Some(last_update) = info.last_update else {
|
||||
if !matches!(info.usage_snapshot_initial_view_version, None | Some(1))
|
||||
|| (info.usage_snapshot_initial_bootstrap && info.usage_snapshot_initial_view_version != Some(1))
|
||||
|| info
|
||||
.usage_snapshot_rebuild_generation
|
||||
.as_deref()
|
||||
.is_some_and(|generation| Uuid::parse_str(generation).map_or(true, |id| id.is_nil()))
|
||||
|| info
|
||||
.usage_snapshot_noninitial_buckets
|
||||
.iter()
|
||||
.any(|(bucket, incarnation)| bucket.is_empty() || Uuid::parse_str(incarnation).map_or(true, |id| id.is_nil()))
|
||||
{
|
||||
return false;
|
||||
};
|
||||
|
||||
info == &scanner_usage_bootstrap_marker(last_update, info.scanner_epoch)
|
||||
}
|
||||
info.has_usage_bootstrap_marker_shape()
|
||||
}
|
||||
|
||||
pub(super) fn scanner_usage_bootstrap_marker(last_update: std::time::SystemTime, scanner_epoch: Option<u64>) -> DataUsageInfo {
|
||||
@@ -689,6 +711,7 @@ pub(super) fn scanner_usage_bootstrap_marker(last_update: std::time::SystemTime,
|
||||
scanner_epoch,
|
||||
usage_snapshot_converged: Some(false),
|
||||
usage_snapshot_bootstrap_pending: true,
|
||||
usage_snapshot_rebuild_generation: Some(uuid::Uuid::new_v4().to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -2108,6 +2131,15 @@ where
|
||||
let baseline_publication_epoch = baseline_publication_guard.epoch();
|
||||
let usage_persist_baseline_result = read_data_usage_persist_baseline(storeapi.clone()).await;
|
||||
let observed_usage_candidate_result = read_config(storeapi.clone(), DATA_USAGE_OBSERVED_OBJ_NAME_PATH.as_str()).await;
|
||||
let completed_bucket_baseline = match tokio::time::timeout(
|
||||
Duration::from_secs(2),
|
||||
read_config_with_revision(storeapi.clone(), DATA_USAGE_CERTIFIED_BUCKETS_OBJ_NAME_PATH.as_str()),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok((bytes, _revision))) => Ok(bytes.map(Bytes::from)),
|
||||
_ => Err(()),
|
||||
};
|
||||
drop(baseline_publication_guard);
|
||||
let usage_persist_baseline = match usage_persist_baseline_result {
|
||||
Ok(baseline) => baseline,
|
||||
@@ -2167,6 +2199,7 @@ where
|
||||
scan_mode,
|
||||
scan_scope: crate::scanner_io::ScannerBucketScanScope::default(),
|
||||
persisted_usage_baseline: usage_persist_baseline.data.clone(),
|
||||
completed_bucket_baseline,
|
||||
observed_usage_candidate,
|
||||
requires_full_scan: scheduling.requires_full_scan,
|
||||
service_cohort: scheduling.service_cohort,
|
||||
@@ -4180,10 +4213,14 @@ enum ScannerCyclePublicationPlan {
|
||||
ProgressOnly,
|
||||
Observational,
|
||||
Authoritative,
|
||||
CertifiedBuckets,
|
||||
}
|
||||
|
||||
impl ScannerCyclePublicationPlan {
|
||||
fn for_result(result: &ScannerCycleResult) -> Self {
|
||||
if result.has_certified_bucket_update() {
|
||||
return Self::CertifiedBuckets;
|
||||
}
|
||||
match (result.has_usage_update(), result.status) {
|
||||
(false, _) => Self::ProgressOnly,
|
||||
(
|
||||
@@ -4205,7 +4242,7 @@ impl ScannerCyclePublicationPlan {
|
||||
}
|
||||
|
||||
fn uses_observational_lease(self) -> bool {
|
||||
self != Self::Authoritative
|
||||
!matches!(self, Self::Authoritative | Self::CertifiedBuckets)
|
||||
}
|
||||
|
||||
async fn await_leases<T, E, F, Fut>(
|
||||
@@ -4235,6 +4272,7 @@ impl ScannerCyclePublicationPlan {
|
||||
Self::ProgressOnly => "progress_only",
|
||||
Self::Observational => "observational",
|
||||
Self::Authoritative => "authoritative",
|
||||
Self::CertifiedBuckets => "certified_buckets",
|
||||
},
|
||||
"Scanner is acquiring peer publication proof"
|
||||
);
|
||||
|
||||
@@ -2717,9 +2717,12 @@ pub(super) async fn publish_scanner_usage_bootstrap_primary(
|
||||
expected_revision: &DataUsageCacheRevision,
|
||||
expected_publication_epoch: u64,
|
||||
leader_epoch: Option<u64>,
|
||||
initial_bootstrap: bool,
|
||||
owns_publication: &(impl Fn() -> bool + Sync),
|
||||
) -> Result<(), ScannerUsageBootstrapPublishError> {
|
||||
let marker = scanner_usage_bootstrap_marker(std::time::SystemTime::now(), leader_epoch);
|
||||
let mut marker = scanner_usage_bootstrap_marker(std::time::SystemTime::now(), leader_epoch);
|
||||
marker.usage_snapshot_initial_bootstrap = initial_bootstrap;
|
||||
marker.usage_snapshot_initial_view_version = initial_bootstrap.then_some(1);
|
||||
let data = serde_json::to_vec(&marker).map_err(ScannerUsageBootstrapPublishError::Encode)?;
|
||||
let save_result = save_reset_config(
|
||||
storeapi.clone(),
|
||||
@@ -2751,9 +2754,16 @@ pub(super) async fn publish_scanner_usage_bootstrap_primary(
|
||||
})
|
||||
}
|
||||
|
||||
inner(storeapi, expected_revision, expected_publication_epoch, leader_epoch, &owns_publication)
|
||||
.await
|
||||
.map_err(|err| err.into_scanner_error(context))
|
||||
inner(
|
||||
storeapi,
|
||||
expected_revision,
|
||||
expected_publication_epoch,
|
||||
leader_epoch,
|
||||
matches!(&context, ScannerUsageBootstrapPublishContext::Initial),
|
||||
&owns_publication,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| err.into_scanner_error(context))
|
||||
}
|
||||
|
||||
pub(super) async fn reset_scanner_usage_state_slots_for_full_rebuild(
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user