mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc1db38fab | ||
|
|
52f6347766 | ||
|
|
68b595d7ca | ||
|
|
3b07ea7145 | ||
|
|
13199aaf5f | ||
|
|
29ca7f3fe3 | ||
|
|
f81b0e3a49 | ||
|
|
2984d0622e | ||
|
|
9d069cfd08 |
No files matched your search
@@ -487,36 +487,32 @@ impl DiskLocation {
|
||||
let base = volume_file_name(&self.directory, collection, vid);
|
||||
let dat_path = format!("{}.dat", base);
|
||||
|
||||
// Custom ratio and source size come from the encode's own .vif; the
|
||||
// server holds no cluster EC config in memory.
|
||||
let Ok(encode_info) = ec_encode_vif(
|
||||
// Custom ratio comes from the volume's own .vif; the server holds no
|
||||
// cluster EC config in memory.
|
||||
let data_shards = ec_data_shards_from_vif(
|
||||
&self.directory,
|
||||
&self.idx_directory,
|
||||
&self.store_dirs,
|
||||
collection,
|
||||
vid,
|
||||
) else {
|
||||
);
|
||||
if data_shards == 0 {
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
"sibling .vif files disagree on the encode; keeping EC shards"
|
||||
);
|
||||
return true;
|
||||
};
|
||||
let data_shards = encode_info
|
||||
.as_ref()
|
||||
.and_then(|vi| vi.ec_shard_config.as_ref())
|
||||
.map(|c| c.data_shards as usize)
|
||||
.filter(|&ds| ds > 0)
|
||||
.unwrap_or(DATA_SHARDS_COUNT);
|
||||
}
|
||||
|
||||
// On-disk .dat: an empty <= superblock one is a stub; a transient stat
|
||||
// error keeps the shards rather than deleting.
|
||||
let mut dat_size: i64 = -1;
|
||||
let mut expected_shard_size: Option<i64> = None;
|
||||
let dat_exists = match fs::metadata(&dat_path) {
|
||||
Ok(meta) if meta.len() > SUPER_BLOCK_SIZE as u64 => {
|
||||
dat_size = meta.len() as i64;
|
||||
expected_shard_size = Some(calculate_expected_shard_size(dat_size, data_shards));
|
||||
expected_shard_size = Some(calculate_expected_shard_size(
|
||||
meta.len() as i64,
|
||||
data_shards,
|
||||
));
|
||||
true
|
||||
}
|
||||
Ok(_) => false,
|
||||
@@ -573,33 +569,6 @@ impl DiskLocation {
|
||||
if shard_count == 0 {
|
||||
return false;
|
||||
}
|
||||
// Shards that are exactly the full encode of the source size the .vif
|
||||
// records, under an .ecx indexing nothing past that size, were made
|
||||
// from that source. A .dat of any other size is not it (e.g. a replica
|
||||
// that kept taking writes), so its size says nothing about these
|
||||
// shards: keep them, and leave the .dat unloaded so it cannot collide
|
||||
// with the EC volume. The .ecx check catches a re-encode interrupted
|
||||
// under an earlier encode's .vif: it writes the .ecx of the grown .dat
|
||||
// before the shards.
|
||||
let recorded = encode_info.as_ref().map_or(0, |vi| vi.dat_file_size);
|
||||
if recorded > 0
|
||||
&& dat_size != recorded
|
||||
&& actual_shard_size == Some(calculate_expected_shard_size(recorded, data_shards))
|
||||
&& !self.ecx_indexes_past(
|
||||
collection,
|
||||
vid,
|
||||
encode_needle_version(&encode_info),
|
||||
recorded,
|
||||
)
|
||||
{
|
||||
warn!(
|
||||
volume_id = vid.0,
|
||||
dat_size,
|
||||
recorded,
|
||||
".dat size differs from the encode source size the .vif records; keeping the EC shards and leaving the .dat in place untouched"
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if let (Some(actual), Some(expected)) = (actual_shard_size, expected_shard_size)
|
||||
&& actual < expected
|
||||
{
|
||||
@@ -614,36 +583,6 @@ impl DiskLocation {
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the .ecx the mount would open for (collection, vid) -- the data
|
||||
/// dir's when non-empty, else the idx dir's -- indexes a live needle
|
||||
/// ending past `size`. A missing or unreadable file reports false: a
|
||||
/// doubt keeps the shards. A torn tail is what an interrupted write
|
||||
/// leaves, so the whole entries before it still count. Mirrors Go's
|
||||
/// ecxIndexesPast.
|
||||
fn ecx_indexes_past(
|
||||
&self,
|
||||
collection: &str,
|
||||
vid: VolumeId,
|
||||
version: Version,
|
||||
size: i64,
|
||||
) -> bool {
|
||||
let mut ecx = format!("{}.ecx", volume_file_name(&self.directory, collection, vid));
|
||||
if self.idx_directory != self.directory
|
||||
&& !crate::storage::erasure_coding::ec_volume::is_usable_ecx_file(&ecx)
|
||||
{
|
||||
ecx = format!(
|
||||
"{}.ecx",
|
||||
volume_file_name(&self.idx_directory, collection, vid)
|
||||
);
|
||||
}
|
||||
crate::storage::erasure_coding::ec_decoder::ecx_needle_extent(
|
||||
&ecx,
|
||||
version,
|
||||
&HashSet::new(),
|
||||
)
|
||||
.is_ok_and(|extent| extent > size)
|
||||
}
|
||||
|
||||
/// Remove all EC-related files for a volume.
|
||||
/// `pub(crate)` so the Store-level cross-disk passes in
|
||||
/// `store_ec_reconcile.rs` can call it to scrub partial EC artefacts
|
||||
@@ -1525,6 +1464,9 @@ fn calculate_expected_shard_size(dat_file_size: i64, data_shards: usize) -> i64
|
||||
shard_size
|
||||
}
|
||||
|
||||
/// Resolve the EC data-shard count from the volume's own `.vif` (the volume
|
||||
/// server never holds the cluster EC config in memory), checking the data dir
|
||||
/// then the idx dir. Falls back to the default ratio when no EC `.vif` is found.
|
||||
/// Remove a file, treating a missing file as success but propagating real errors
|
||||
/// (permissions, disk full). Mirrors Go's removeFileIfExists so a teardown failure
|
||||
/// surfaces instead of silently leaving stale artifacts.
|
||||
@@ -1535,47 +1477,26 @@ fn rm_if_present(path: String) -> io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The needle version the encode's `.vif` records, as the mount reads it,
|
||||
/// defaulting to the current version when unset. Mirrors Go's
|
||||
/// encodeNeedleVersion.
|
||||
fn encode_needle_version(info: &Option<VifVolumeInfo>) -> Version {
|
||||
match info.as_ref().map_or(0, |vi| vi.version) {
|
||||
0 => Version::current(),
|
||||
v => Version(v as u8),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.vif` describing the encode of an EC volume: the first with an EC
|
||||
/// shard config in the data dir, the idx dir, then the sibling data dir the
|
||||
/// mount takes it from under a shared idx dir. Without one it falls back to
|
||||
/// the first `.vif` found in the data or idx dir. Err when sibling `.vif`
|
||||
/// files disagree on the run. Mirrors Go's ecEncodeVolumeInfo.
|
||||
fn ec_encode_vif(
|
||||
fn ec_data_shards_from_vif(
|
||||
directory: &str,
|
||||
idx_directory: &str,
|
||||
store_dirs: &[String],
|
||||
collection: &str,
|
||||
vid: VolumeId,
|
||||
) -> Result<Option<VifVolumeInfo>, ()> {
|
||||
let has_ec_config = |vi: &VifVolumeInfo| {
|
||||
vi.ec_shard_config
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.data_shards > 0)
|
||||
};
|
||||
let mut fallback: Option<VifVolumeInfo> = None;
|
||||
) -> usize {
|
||||
for dir in [directory, idx_directory] {
|
||||
let vif = format!("{}.vif", volume_file_name(dir, collection, vid));
|
||||
if let Some(vi) = fs::read_to_string(&vif)
|
||||
if let Some(ds) = fs::read_to_string(&vif)
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<VifVolumeInfo>(&s).ok())
|
||||
.and_then(|vi| vi.ec_shard_config)
|
||||
.map(|c| c.data_shards as usize)
|
||||
&& ds > 0
|
||||
{
|
||||
if has_ec_config(&vi) {
|
||||
return Ok(Some(vi));
|
||||
}
|
||||
fallback.get_or_insert(vi);
|
||||
return ds;
|
||||
}
|
||||
if directory == idx_directory {
|
||||
return Ok(fallback);
|
||||
break;
|
||||
}
|
||||
}
|
||||
match crate::storage::erasure_coding::ec_volume::sibling_ec_config_vif(
|
||||
@@ -1584,10 +1505,18 @@ fn ec_encode_vif(
|
||||
store_dirs,
|
||||
collection,
|
||||
vid,
|
||||
)? {
|
||||
Some(vi) if has_ec_config(&vi) => Ok(Some(vi)),
|
||||
_ => Ok(fallback),
|
||||
) {
|
||||
Err(()) => return 0,
|
||||
Ok(Some(vi)) => {
|
||||
if let Some(ds) = vi.ec_shard_config.map(|c| c.data_shards as usize)
|
||||
&& ds > 0
|
||||
{
|
||||
return ds;
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
}
|
||||
DATA_SHARDS_COUNT
|
||||
}
|
||||
|
||||
/// Parse a volume filename like "collection_42.dat" or "42.dat" into (collection, VolumeId).
|
||||
@@ -1949,412 +1878,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn write_ec_vif(base: &str, dat_file_size: i64) {
|
||||
let vif = VifVolumeInfo {
|
||||
version: 3,
|
||||
dat_file_size,
|
||||
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
fs::write(
|
||||
format!("{}.vif", base),
|
||||
serde_json::to_string(&vif).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn write_sized(path: &str, size: i64) {
|
||||
fs::File::create(path)
|
||||
.unwrap()
|
||||
.set_len(size as u64)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
// An .ecx with one live needle ending at `end` in a current-version .dat.
|
||||
fn write_ecx_ending_at(base: &str, end: i64) {
|
||||
write_ecx_ending_at_version(base, end, Version::current());
|
||||
}
|
||||
|
||||
fn write_ecx_ending_at_version(base: &str, end: i64, version: Version) {
|
||||
let size = Size(1000);
|
||||
let offset = end - crate::storage::needle::needle::get_actual_size(size, version);
|
||||
let mut entry = [0u8; NEEDLE_MAP_ENTRY_SIZE];
|
||||
idx_entry_to_bytes(
|
||||
&mut entry,
|
||||
NeedleId(1),
|
||||
Offset::from_actual_offset(offset),
|
||||
size,
|
||||
);
|
||||
fs::write(format!("{}.ecx", base), entry).unwrap();
|
||||
}
|
||||
|
||||
// A .dat of `size` whose superblock names the current needle version.
|
||||
fn write_sized_dat(path: &str, size: i64) {
|
||||
use std::io::Write;
|
||||
let mut f = fs::File::create(path).unwrap();
|
||||
f.write_all(&[Version::current().0]).unwrap();
|
||||
f.set_len(size as u64).unwrap();
|
||||
}
|
||||
|
||||
fn test_location(dir: &str) -> DiskLocation {
|
||||
DiskLocation::new(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
// A .dat larger than the source the .vif records sits beside a full-size
|
||||
// shard of that encode: it is not the shards' source, so the shards stay,
|
||||
// the .dat is not loaded, and nothing on disk is touched.
|
||||
#[test]
|
||||
fn test_load_existing_foreign_dat_beside_ec_shards_keeps_both() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let vid = VolumeId(74);
|
||||
{
|
||||
let mut loc = test_location(dir);
|
||||
loc.create_volume(vid, NeedleMapKind::InMemory, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
loc.close();
|
||||
}
|
||||
let base = volume_file_name(dir, "", vid);
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
let source_size = 30 * 1024 * 1024i64;
|
||||
write_ec_vif(&base, source_size);
|
||||
let shard_size = calculate_expected_shard_size(source_size, ds);
|
||||
write_sized(&format!("{}.ec09", base), shard_size);
|
||||
// The .ecx indexes a needle ending exactly at the source size.
|
||||
write_ecx_ending_at(&base, source_size);
|
||||
write_sized(&format!("{}.ecj", base), 0);
|
||||
// Grown past the source by later writes: its full encode would be
|
||||
// larger than the shard, which used to read as an interrupted encode.
|
||||
let foreign_size = source_size + 10 * 1024 * 1024;
|
||||
assert!(calculate_expected_shard_size(foreign_size, ds) > shard_size);
|
||||
fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(format!("{}.dat", base))
|
||||
.unwrap()
|
||||
.set_len(foreign_size as u64)
|
||||
.unwrap();
|
||||
|
||||
let exts = [".dat", ".idx", ".vif", ".ecx", ".ecj", ".ec09"];
|
||||
let sizes: Vec<u64> = exts
|
||||
.iter()
|
||||
.map(|e| fs::metadata(format!("{}{}", base, e)).unwrap().len())
|
||||
.collect();
|
||||
let vif_before = fs::read(format!("{}.vif", base)).unwrap();
|
||||
|
||||
let mut loc = test_location(dir);
|
||||
assert!(
|
||||
loc.validate_ec_volume("", vid),
|
||||
"shards whose .vif names a different source size than the .dat must be kept",
|
||||
);
|
||||
loc.load_existing_volumes(NeedleMapKind::InMemory).unwrap();
|
||||
assert!(
|
||||
loc.find_volume(vid).is_none(),
|
||||
"a .dat that is not the encode source was loaded beside its EC shards",
|
||||
);
|
||||
for (e, size) in exts.iter().zip(sizes) {
|
||||
let meta = fs::metadata(format!("{}{}", base, e))
|
||||
.unwrap_or_else(|err| panic!("{} is gone: {}", e, err));
|
||||
assert_eq!(meta.len(), size, "{} size changed", e);
|
||||
}
|
||||
assert_eq!(fs::read(format!("{}.vif", base)).unwrap(), vif_before);
|
||||
}
|
||||
|
||||
// The .dat matches the recorded source size and the shards are short of its
|
||||
// full encode: an interrupted local encode, still reclaimed.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_interrupted_encode_with_recorded_size_reclaims() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = test_location(dir);
|
||||
let base = volume_file_name(dir, "", VolumeId(75));
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
|
||||
let dat_size = 30 * 1024 * 1024i64;
|
||||
write_sized(&format!("{}.dat", base), dat_size);
|
||||
write_ec_vif(&base, dat_size);
|
||||
let partial = calculate_expected_shard_size(dat_size, ds) / 3;
|
||||
for i in 0..total {
|
||||
write_sized(&format!("{}.ec{:02}", base, i), partial);
|
||||
}
|
||||
assert!(
|
||||
!loc.validate_ec_volume("", VolumeId(75)),
|
||||
"partial shards beside the recorded source .dat should be reclaimable",
|
||||
);
|
||||
}
|
||||
|
||||
// The .vif is written after the shards, so an interrupted re-encode of a
|
||||
// volume that was once EC-decoded still has the old encode's .vif. Shards
|
||||
// that are not that encode's full size are not described by it: reclaim.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_interrupted_re_encode_with_stale_vif_reclaims() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = test_location(dir);
|
||||
let base = volume_file_name(dir, "", VolumeId(76));
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
|
||||
let old_source_size = 20 * 1024 * 1024i64;
|
||||
let dat_size = 60 * 1024 * 1024i64;
|
||||
write_sized(&format!("{}.dat", base), dat_size);
|
||||
write_ec_vif(&base, old_source_size);
|
||||
let partial = calculate_expected_shard_size(dat_size, ds) / 2;
|
||||
assert_ne!(partial, calculate_expected_shard_size(old_source_size, ds));
|
||||
for i in 0..total {
|
||||
write_sized(&format!("{}.ec{:02}", base, i), partial);
|
||||
}
|
||||
assert!(
|
||||
!loc.validate_ec_volume("", VolumeId(76)),
|
||||
"partial shards of an interrupted re-encode must not be kept for a stale .vif",
|
||||
);
|
||||
}
|
||||
|
||||
// Under a shared -dir.idx the encode's .vif can sit on a sibling data
|
||||
// disk, where the mount also takes it from. The recorded source size must
|
||||
// be read from there too, or the shards fall back to the .dat size check.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_foreign_dat_keeps_shards_with_sibling_vif() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let root = tmp.path().to_str().unwrap();
|
||||
let (data_a, data_b, idx) = (
|
||||
format!("{root}/a"),
|
||||
format!("{root}/b"),
|
||||
format!("{root}/idx"),
|
||||
);
|
||||
for d in [&data_a, &data_b, &idx] {
|
||||
fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let mut loc = DiskLocation::new(
|
||||
&data_a,
|
||||
&idx,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
loc.store_dirs = vec![data_a.clone(), data_b.clone()];
|
||||
let vid = VolumeId(78);
|
||||
let base_a = volume_file_name(&data_a, "", vid);
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
|
||||
let source_size = 30 * 1024 * 1024i64;
|
||||
write_ec_vif(&volume_file_name(&data_b, "", vid), source_size);
|
||||
write_sized(&format!("{}.ecx", volume_file_name(&idx, "", vid)), 0);
|
||||
write_sized(
|
||||
&format!("{}.ec09", base_a),
|
||||
calculate_expected_shard_size(source_size, ds),
|
||||
);
|
||||
write_sized(&format!("{}.dat", base_a), source_size + 10 * 1024 * 1024);
|
||||
|
||||
assert!(
|
||||
loc.validate_ec_volume("", vid),
|
||||
"the sibling .vif's source size was ignored and the shards would be deleted",
|
||||
);
|
||||
}
|
||||
|
||||
// A re-encode of a grown .dat interrupted under an earlier encode's .vif,
|
||||
// with every partial shard exactly as long as that earlier encode's full
|
||||
// shards. The re-encode wrote the .ecx of the grown .dat first, so it
|
||||
// indexes needles past the recorded size: the shards are not that
|
||||
// encode's, and the complete .dat is reclaimed.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_interrupted_re_encode_matching_stale_length_reclaims() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = test_location(dir);
|
||||
let vid = VolumeId(79);
|
||||
let base = volume_file_name(dir, "", vid);
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
|
||||
let old_source_size = 20 * 1024 * 1024i64;
|
||||
let dat_size = 60 * 1024 * 1024i64;
|
||||
write_sized_dat(&format!("{}.dat", base), dat_size);
|
||||
write_ec_vif(&base, old_source_size);
|
||||
write_ecx_ending_at(&base, dat_size);
|
||||
for i in 0..total {
|
||||
write_sized(
|
||||
&format!("{}.ec{:02}", base, i),
|
||||
calculate_expected_shard_size(old_source_size, ds),
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!loc.validate_ec_volume("", vid),
|
||||
"a stale .vif was trusted for partial shards under an .ecx of the grown .dat",
|
||||
);
|
||||
|
||||
// The same shards under an .ecx that stays within the recorded size
|
||||
// are that encode's: keep them.
|
||||
write_ecx_ending_at(&base, old_source_size);
|
||||
assert!(
|
||||
loc.validate_ec_volume("", vid),
|
||||
"shards whose .ecx and length match the recorded source must be kept",
|
||||
);
|
||||
}
|
||||
|
||||
// Only the .ecx the mount opens speaks for the shards: a non-empty
|
||||
// data-dir .ecx within the recorded size wins over an older shared-idx
|
||||
// .ecx pointing past it, and the shards stay.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_checks_the_ecx_the_mount_opens() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let root = tmp.path().to_str().unwrap();
|
||||
let (data, idx) = (format!("{root}/data"), format!("{root}/idx"));
|
||||
for d in [&data, &idx] {
|
||||
fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let loc = DiskLocation::new(
|
||||
&data,
|
||||
&idx,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let vid = VolumeId(80);
|
||||
let base = volume_file_name(&data, "", vid);
|
||||
let idx_base = volume_file_name(&idx, "", vid);
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
|
||||
let source_size = 30 * 1024 * 1024i64;
|
||||
write_ec_vif(&base, source_size);
|
||||
write_ecx_ending_at(&base, source_size);
|
||||
write_ecx_ending_at(&idx_base, source_size + 20 * 1024 * 1024);
|
||||
write_sized(
|
||||
&format!("{}.ec09", base),
|
||||
calculate_expected_shard_size(source_size, ds),
|
||||
);
|
||||
write_sized_dat(&format!("{}.dat", base), source_size + 10 * 1024 * 1024);
|
||||
|
||||
assert!(
|
||||
loc.validate_ec_volume("", vid),
|
||||
"an .ecx the mount ignores decided against the shards",
|
||||
);
|
||||
|
||||
// With no data-dir .ecx the mount opens the shared one, which indexes
|
||||
// past the recorded size: the old rule applies and reclaims.
|
||||
fs::remove_file(format!("{}.ecx", base)).unwrap();
|
||||
assert!(
|
||||
!loc.validate_ec_volume("", vid),
|
||||
"the shared .ecx the mount opens was not checked",
|
||||
);
|
||||
}
|
||||
|
||||
// The .ecx extent is sized with the needle version the encode's .vif
|
||||
// records, as the mount reads it, not the version of the foreign .dat.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_sizes_the_ecx_with_the_encode_version() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = test_location(dir);
|
||||
let vid = VolumeId(81);
|
||||
let base = volume_file_name(dir, "", vid);
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
let source_size = 30 * 1024 * 1024i64;
|
||||
let vif = VifVolumeInfo {
|
||||
version: 2,
|
||||
dat_file_size: source_size,
|
||||
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
|
||||
data_shards: 10,
|
||||
parity_shards: 4,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
fs::write(
|
||||
format!("{}.vif", base),
|
||||
serde_json::to_string(&vif).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
// Ends exactly at the source under version 2; version 3 would put it
|
||||
// 8 bytes past.
|
||||
write_ecx_ending_at_version(&base, source_size, Version(2));
|
||||
write_sized(
|
||||
&format!("{}.ec09", base),
|
||||
calculate_expected_shard_size(source_size, ds),
|
||||
);
|
||||
write_sized_dat(&format!("{}.dat", base), source_size + 10 * 1024 * 1024);
|
||||
|
||||
assert!(
|
||||
loc.validate_ec_volume("", vid),
|
||||
"the .ecx was sized with the foreign .dat's needle version, not the encode's",
|
||||
);
|
||||
}
|
||||
|
||||
// An interrupted write leaves a torn .ecx tail; the whole entries before
|
||||
// it still show the re-encode's .ecx indexing past the stale recorded size.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_torn_ecx_tail_still_reclaims_re_encode() {
|
||||
use std::io::Write;
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = test_location(dir);
|
||||
let vid = VolumeId(82);
|
||||
let base = volume_file_name(dir, "", vid);
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
|
||||
let old_source_size = 20 * 1024 * 1024i64;
|
||||
let dat_size = 60 * 1024 * 1024i64;
|
||||
write_sized_dat(&format!("{}.dat", base), dat_size);
|
||||
write_ec_vif(&base, old_source_size);
|
||||
write_ecx_ending_at(&base, dat_size);
|
||||
fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(format!("{}.ecx", base))
|
||||
.unwrap()
|
||||
.write_all(&[1, 2, 3])
|
||||
.unwrap();
|
||||
for i in 0..total {
|
||||
write_sized(
|
||||
&format!("{}.ec{:02}", base, i),
|
||||
calculate_expected_shard_size(old_source_size, ds),
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!loc.validate_ec_volume("", vid),
|
||||
"a torn .ecx tail hid the entries past the stale recorded size",
|
||||
);
|
||||
}
|
||||
|
||||
// A .vif without a recorded source size keeps the old size check against
|
||||
// the .dat, in both directions.
|
||||
#[test]
|
||||
fn test_validate_ec_volume_no_recorded_size_keeps_old_rule() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let loc = test_location(dir);
|
||||
let base = volume_file_name(dir, "", VolumeId(77));
|
||||
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
|
||||
write_ec_vif(&base, 0);
|
||||
write_sized(
|
||||
&format!("{}.ec00", base),
|
||||
calculate_expected_shard_size(30 * 1024 * 1024, ds),
|
||||
);
|
||||
|
||||
write_sized(&format!("{}.dat", base), 40 * 1024 * 1024);
|
||||
assert!(
|
||||
!loc.validate_ec_volume("", VolumeId(77)),
|
||||
"without a recorded size, shards smaller than the .dat's full encode should be reclaimable",
|
||||
);
|
||||
write_sized(&format!("{}.dat", base), 30 * 1024 * 1024);
|
||||
assert!(
|
||||
loc.validate_ec_volume("", VolumeId(77)),
|
||||
"without a recorded size, shards matching the .dat's full encode must be kept",
|
||||
);
|
||||
}
|
||||
|
||||
// The per-disk generation reader behind the fenced EC teardown: a present .vif
|
||||
// yields its generation (or 0 with no EC config), a missing .vif is unreadable
|
||||
// (preserved, fail-safe), and the idx dir is a fallback for the split-disk layout.
|
||||
|
||||
@@ -48,30 +48,28 @@ pub fn find_dat_file_size_with_dirs(
|
||||
ec00.read_exact(&mut sb_buf)?;
|
||||
let version = Version(sb_buf[0]);
|
||||
|
||||
// At least the superblock size
|
||||
let extent = ecx_needle_extent(&format!("{}.ecx", ecx_base), version, deleted)?;
|
||||
Ok(extent.max(SUPER_BLOCK_SIZE as i64))
|
||||
}
|
||||
// Start with at least the superblock size
|
||||
let mut dat_size: i64 = SUPER_BLOCK_SIZE as i64;
|
||||
|
||||
/// Where the furthest live needle indexed by the `.ecx` at `ecx_path` ends in
|
||||
/// the source `.dat`, or 0 when it indexes none. Needles in `deleted` count as
|
||||
/// deleted. Mirrors Go's EcxNeedleExtent.
|
||||
pub fn ecx_needle_extent(
|
||||
ecx_path: &str,
|
||||
version: Version,
|
||||
deleted: &HashSet<NeedleId>,
|
||||
) -> io::Result<i64> {
|
||||
let ecx_data = std::fs::read(ecx_path)?;
|
||||
let (entries, _) = ecx_data.as_chunks::<NEEDLE_MAP_ENTRY_SIZE>();
|
||||
let mut extent = 0i64;
|
||||
for entry in entries {
|
||||
let (key, offset, size) = idx_entry_from_bytes(entry);
|
||||
// Scan .ecx entries
|
||||
let ecx_path = format!("{}.ecx", ecx_base);
|
||||
let ecx_data = std::fs::read(&ecx_path)?;
|
||||
let entry_count = ecx_data.len() / NEEDLE_MAP_ENTRY_SIZE;
|
||||
|
||||
for i in 0..entry_count {
|
||||
let start = i * NEEDLE_MAP_ENTRY_SIZE;
|
||||
let (key, offset, size) =
|
||||
idx_entry_from_bytes(&ecx_data[start..start + NEEDLE_MAP_ENTRY_SIZE]);
|
||||
if size.is_deleted() || deleted.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
extent = extent.max(offset.to_actual_offset() + get_actual_size(size, version));
|
||||
let entry_stop = offset.to_actual_offset() + get_actual_size(size, version);
|
||||
if entry_stop > dat_size {
|
||||
dat_size = entry_stop;
|
||||
}
|
||||
}
|
||||
Ok(extent)
|
||||
|
||||
Ok(dat_size)
|
||||
}
|
||||
|
||||
/// Whether the `.ecx` in `ecx_dir` indexes a needle deleted neither there nor
|
||||
|
||||
+74
-12
@@ -1463,10 +1463,63 @@ func (ecb *ecBalancer) applyShardMoveRPC(src, dst *EcNode, collection string, vi
|
||||
// separates generations living on different disks; same-disk mixing is prevented
|
||||
// upstream by the pre-encode artifact wipe and the cross-run read guard.
|
||||
func CountExistingEcShardsForVolume(topologyInfo *master_pb.TopologyInfo, volumeID uint32, collection string) int {
|
||||
if topologyInfo == nil {
|
||||
return 0
|
||||
key := EcVolumeKey{VolumeId: volumeID, Collection: collection}
|
||||
return CountExistingEcShardsForVolumes(topologyInfo, map[EcVolumeKey]struct{}{key: {}})[key]
|
||||
}
|
||||
|
||||
// EcVolumeKey names an EC volume by id and collection.
|
||||
type EcVolumeKey struct {
|
||||
VolumeId uint32
|
||||
Collection string
|
||||
}
|
||||
|
||||
// CountExistingEcShardsForVolumes is CountExistingEcShardsForVolume for many
|
||||
// volumes in one topology walk.
|
||||
func CountExistingEcShardsForVolumes(topologyInfo *master_pb.TopologyInfo, volumes map[EcVolumeKey]struct{}) map[EcVolumeKey]int {
|
||||
counts := make(map[EcVolumeKey]int, len(volumes))
|
||||
for key, generations := range ecShardGenerations(topologyInfo, volumes) {
|
||||
for _, gen := range generations {
|
||||
if c := gen.bits.Count(); c > counts[key] {
|
||||
counts[key] = c
|
||||
}
|
||||
}
|
||||
}
|
||||
perGeneration := make(map[int64]erasure_coding.ShardBits)
|
||||
return counts
|
||||
}
|
||||
|
||||
// LargestEcGenerationHolders returns the addresses of the nodes holding shards
|
||||
// of the generation CountExistingEcShardsForVolume counts, or nil when no
|
||||
// generation is strictly largest and so none can be named the EC volume.
|
||||
func LargestEcGenerationHolders(topologyInfo *master_pb.TopologyInfo, volumeID uint32, collection string) []pb.ServerAddress {
|
||||
key := EcVolumeKey{VolumeId: volumeID, Collection: collection}
|
||||
var largest *ecShardGeneration
|
||||
tied := false
|
||||
for _, gen := range ecShardGenerations(topologyInfo, map[EcVolumeKey]struct{}{key: {}})[key] {
|
||||
switch {
|
||||
case largest == nil || gen.bits.Count() > largest.bits.Count():
|
||||
largest, tied = gen, false
|
||||
case gen.bits.Count() == largest.bits.Count():
|
||||
tied = true
|
||||
}
|
||||
}
|
||||
if largest == nil || tied {
|
||||
return nil
|
||||
}
|
||||
return largest.holders
|
||||
}
|
||||
|
||||
type ecShardGeneration struct {
|
||||
bits erasure_coding.ShardBits
|
||||
holders []pb.ServerAddress
|
||||
}
|
||||
|
||||
// ecShardGenerations groups the shards of the given volumes in the topology
|
||||
// by encode generation, recording each generation's shard bits and holders.
|
||||
func ecShardGenerations(topologyInfo *master_pb.TopologyInfo, volumes map[EcVolumeKey]struct{}) map[EcVolumeKey]map[int64]*ecShardGeneration {
|
||||
if topologyInfo == nil || len(volumes) == 0 {
|
||||
return nil
|
||||
}
|
||||
found := make(map[EcVolumeKey]map[int64]*ecShardGeneration)
|
||||
for _, dc := range topologyInfo.DataCenterInfos {
|
||||
for _, rack := range dc.RackInfos {
|
||||
for _, node := range rack.DataNodeInfos {
|
||||
@@ -1478,22 +1531,31 @@ func CountExistingEcShardsForVolume(topologyInfo *master_pb.TopologyInfo, volume
|
||||
if ecShardInfo == nil {
|
||||
continue
|
||||
}
|
||||
if ecShardInfo.Id != volumeID || ecShardInfo.Collection != collection {
|
||||
key := EcVolumeKey{VolumeId: ecShardInfo.Id, Collection: ecShardInfo.Collection}
|
||||
if _, want := volumes[key]; !want {
|
||||
continue
|
||||
}
|
||||
perGeneration[ecShardInfo.EncodeTsNs] |= erasure_coding.ShardBits(ecShardInfo.EcIndexBits)
|
||||
perGeneration := found[key]
|
||||
if perGeneration == nil {
|
||||
perGeneration = make(map[int64]*ecShardGeneration)
|
||||
found[key] = perGeneration
|
||||
}
|
||||
gen := perGeneration[ecShardInfo.EncodeTsNs]
|
||||
if gen == nil {
|
||||
gen = &ecShardGeneration{}
|
||||
perGeneration[ecShardInfo.EncodeTsNs] = gen
|
||||
}
|
||||
bits := erasure_coding.ShardBits(ecShardInfo.EcIndexBits)
|
||||
gen.bits |= bits
|
||||
if holder := pb.NewServerAddressFromDataNode(node); bits.Count() > 0 && !slices.Contains(gen.holders, holder) {
|
||||
gen.holders = append(gen.holders, holder)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
best := 0
|
||||
for _, bits := range perGeneration {
|
||||
if c := bits.Count(); c > best {
|
||||
best = c
|
||||
}
|
||||
}
|
||||
return best
|
||||
return found
|
||||
}
|
||||
|
||||
// ParseVolumeIdsFlag parses a comma-separated -volumeIds flag value, dropping
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"regexp"
|
||||
@@ -14,7 +12,6 @@ import (
|
||||
"slices"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
@@ -660,27 +657,22 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
|
||||
baseFileName := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
|
||||
datFileName := baseFileName + ".dat"
|
||||
|
||||
// Custom ratio and source size come from the encode's own .vif; the
|
||||
// server holds no cluster EC config in memory.
|
||||
encodeInfo, ambiguous := l.ecEncodeVolumeInfo(collection, vid)
|
||||
if ambiguous {
|
||||
// Custom ratio comes from the volume's own .vif; the server holds no
|
||||
// cluster EC config in memory.
|
||||
dataShards := l.ecDataShardsFromVif(collection, vid)
|
||||
if dataShards == 0 {
|
||||
glog.Warningf("EC volume %d: sibling .vif files disagree on the encode; keeping EC shards", vid)
|
||||
return true
|
||||
}
|
||||
dataShards := erasure_coding.DataShardsCount
|
||||
if ds := encodeInfo.GetEcShardConfig().GetDataShards(); ds > 0 {
|
||||
dataShards = int(ds)
|
||||
}
|
||||
|
||||
// On-disk .dat size, or -1 when absent (an empty <= superblock .dat is a
|
||||
// stub). A transient stat error keeps the shards rather than deleting.
|
||||
var datSize, expectedShardSize int64 = -1, -1
|
||||
var expectedShardSize int64 = -1
|
||||
datExists := false
|
||||
if datFileInfo, err := os.Stat(datFileName); err == nil {
|
||||
if datFileInfo.Size() > int64(super_block.SuperBlockSize) {
|
||||
datExists = true
|
||||
datSize = datFileInfo.Size()
|
||||
expectedShardSize = calculateExpectedShardSize(datSize, dataShards)
|
||||
expectedShardSize = calculateExpectedShardSize(datFileInfo.Size(), dataShards)
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
glog.Warningf("EC volume %d: cannot stat .dat %s (%v); keeping EC shards", vid, datFileName, err)
|
||||
@@ -720,20 +712,6 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
|
||||
if shardCount == 0 {
|
||||
return false
|
||||
}
|
||||
// Shards that are exactly the full encode of the source size the .vif
|
||||
// records, under an .ecx indexing nothing past that size, were made from
|
||||
// that source. A .dat of any other size is not it (e.g. a replica that
|
||||
// kept taking writes), so its size says nothing about these shards: keep
|
||||
// them, and leave the .dat unloaded so it cannot collide with the EC
|
||||
// volume. The .ecx check catches a re-encode interrupted under an earlier
|
||||
// encode's .vif: it writes the .ecx of the grown .dat before the shards.
|
||||
if recorded := encodeInfo.GetDatFileSize(); recorded > 0 && datSize != recorded &&
|
||||
actualShardSize == calculateExpectedShardSize(recorded, dataShards) &&
|
||||
!l.ecxIndexesPast(collection, vid, encodeNeedleVersion(encodeInfo), recorded) {
|
||||
glog.Warningf("EC volume %d: .dat is %d bytes but the .vif records an encode source of %d bytes; keeping the EC shards and leaving the .dat in place untouched",
|
||||
vid, datSize, recorded)
|
||||
return true
|
||||
}
|
||||
if expectedShardSize > 0 && actualShardSize > 0 && actualShardSize < expectedShardSize {
|
||||
glog.Warningf("EC volume %d: %d shards of %d bytes are smaller than the .dat's full encode (%d bytes); reclaiming the complete .dat",
|
||||
vid, shardCount, actualShardSize, expectedShardSize)
|
||||
@@ -742,72 +720,52 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
|
||||
return true
|
||||
}
|
||||
|
||||
// ecxIndexesPast reports whether the .ecx the mount would open for
|
||||
// (collection, vid) -- the data dir's when non-empty, else the idx dir's --
|
||||
// indexes a live needle ending past size. A missing or unreadable file
|
||||
// reports false: a doubt keeps the shards. A torn tail is what an
|
||||
// interrupted write leaves, so the whole entries before it still count.
|
||||
func (l *DiskLocation) ecxIndexesPast(collection string, vid needle.VolumeId, version needle.Version, size int64) bool {
|
||||
ecxBase := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
|
||||
if fi, err := os.Stat(ecxBase + ".ecx"); (err != nil || fi.Size() == 0) && l.IdxDirectory != l.Directory {
|
||||
ecxBase = erasure_coding.EcShardFileName(collection, l.IdxDirectory, int(vid))
|
||||
}
|
||||
extent, err := erasure_coding.EcxNeedleExtent(ecxBase, version)
|
||||
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return false
|
||||
}
|
||||
return extent > size
|
||||
}
|
||||
|
||||
// encodeNeedleVersion is the needle version the encode's .vif records, as the
|
||||
// mount reads it, defaulting to the current version when unset.
|
||||
func encodeNeedleVersion(info *volume_server_pb.VolumeInfo) needle.Version {
|
||||
if v := info.GetVersion(); v > 0 {
|
||||
return needle.Version(v)
|
||||
}
|
||||
return needle.GetCurrentVersion()
|
||||
}
|
||||
|
||||
// ecEncodeVolumeInfo returns the .vif describing the encode of an EC volume:
|
||||
// the first with an EC shard config in the data dir, the idx dir, then the
|
||||
// sibling data dir the mount takes it from under a shared idx dir. Without
|
||||
// one it falls back to the first .vif found in the data or idx dir, which
|
||||
// may be nil. ambiguous is set when sibling .vif files disagree on the run.
|
||||
func (l *DiskLocation) ecEncodeVolumeInfo(collection string, vid needle.VolumeId) (info *volume_server_pb.VolumeInfo, ambiguous bool) {
|
||||
var fallback *volume_server_pb.VolumeInfo
|
||||
load := func(vifName string) *volume_server_pb.VolumeInfo {
|
||||
vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vifName)
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
if fallback == nil {
|
||||
fallback = vi
|
||||
}
|
||||
if vi.GetEcShardConfig().GetDataShards() > 0 {
|
||||
return vi
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// ecDataShardsFromVif resolves the data-shard count for an EC volume from
|
||||
// its own .vif (EcShardConfig), checking the data dir, the idx dir, then the
|
||||
// sibling data dir the mount takes the .vif from under a shared idx dir. The
|
||||
// .vif is the source of truth for custom ratios on the volume server, which
|
||||
// never holds the cluster EC config in memory. Falls back to the default
|
||||
// ratio when the .vif carries no EC shard config.
|
||||
func (l *DiskLocation) ecDataShardsFromVif(collection string, vid needle.VolumeId) int {
|
||||
// At most two dirs to check; avoid slice/map allocations on this
|
||||
// per-volume startup path.
|
||||
if l.Directory != "" {
|
||||
if vi := load(erasure_coding.EcShardFileName(collection, l.Directory, int(vid)) + ".vif"); vi != nil {
|
||||
return vi, false
|
||||
if ds := ecDataShardsFromVifDir(collection, l.Directory, vid); ds > 0 {
|
||||
return ds
|
||||
}
|
||||
}
|
||||
if l.IdxDirectory != "" && l.IdxDirectory != l.Directory {
|
||||
if vi := load(erasure_coding.EcShardFileName(collection, l.IdxDirectory, int(vid)) + ".vif"); vi != nil {
|
||||
return vi, false
|
||||
if ds := ecDataShardsFromVifDir(collection, l.IdxDirectory, vid); ds > 0 {
|
||||
return ds
|
||||
}
|
||||
vif, ambiguous := erasure_coding.SiblingEcConfigVif(collection, vid, l.Directory, l.IdxDirectory, l.storeDirs)
|
||||
if ambiguous {
|
||||
return nil, true
|
||||
return 0
|
||||
}
|
||||
if vif != "" {
|
||||
if vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vif); found && vi.GetEcShardConfig().GetDataShards() > 0 {
|
||||
return vi, false
|
||||
if ds := ecDataShardsFromVifPath(vif); ds > 0 {
|
||||
return ds
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback, false
|
||||
return erasure_coding.DataShardsCount
|
||||
}
|
||||
|
||||
// ecDataShardsFromVifDir returns the .vif EcShardConfig data-shard count for
|
||||
// (collection, vid) under dir, or 0 when absent / not custom.
|
||||
func ecDataShardsFromVifDir(collection, dir string, vid needle.VolumeId) int {
|
||||
return ecDataShardsFromVifPath(erasure_coding.EcShardFileName(collection, dir, int(vid)) + ".vif")
|
||||
}
|
||||
|
||||
// ecDataShardsFromVifPath returns the EcShardConfig data-shard count recorded
|
||||
// in one .vif, or 0 when absent / not custom.
|
||||
func ecDataShardsFromVifPath(vifName string) int {
|
||||
if vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vifName); found && vi.EcShardConfig != nil {
|
||||
if ds := int(vi.EcShardConfig.DataShards); ds > 0 {
|
||||
return ds
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// removeEcVolumeFiles removes all EC-related files for a volume
|
||||
|
||||
@@ -5,13 +5,8 @@ import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
|
||||
)
|
||||
|
||||
func writeSizedFile(t *testing.T, path string, size int64) {
|
||||
@@ -106,331 +101,3 @@ func TestValidateEcVolume_TransientStatErrorKeeps(t *testing.T) {
|
||||
t.Fatal("validateEcVolume returned delete on a transient stat error; must keep on ambiguity")
|
||||
}
|
||||
}
|
||||
|
||||
func writeEcVif(t *testing.T, base string, datFileSize int64) {
|
||||
t.Helper()
|
||||
vi := &volume_server_pb.VolumeInfo{
|
||||
Version: uint32(needle.GetCurrentVersion()),
|
||||
DatFileSize: datFileSize,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: uint32(erasure_coding.DataShardsCount),
|
||||
ParityShards: uint32(erasure_coding.ParityShardsCount),
|
||||
},
|
||||
}
|
||||
if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil {
|
||||
t.Fatalf("save .vif: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A .dat larger than the source the .vif records sits beside a full-size
|
||||
// shard of that encode: it is not the shards' source, so the shards stay, the
|
||||
// .dat is not loaded, and nothing on disk is touched.
|
||||
func TestLoadExistingVolume_ForeignDatBesideEcShardsKeepsBoth(t *testing.T) {
|
||||
store := newTestStore(t, 1)
|
||||
l := store.Locations[0]
|
||||
const vid = needle.VolumeId(74)
|
||||
mountTestVolume(t, l, vid, "")
|
||||
l.UnloadVolume(vid)
|
||||
base := erasure_coding.EcShardFileName("", l.Directory, int(vid))
|
||||
|
||||
sourceSize := int64(30 * 1024 * 1024)
|
||||
writeEcVif(t, base, sourceSize)
|
||||
shardSize := calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount)
|
||||
writeSizedFile(t, base+erasure_coding.ToExt(9), shardSize)
|
||||
// The .ecx indexes a needle ending exactly at the source size.
|
||||
writeEcxEndingAt(t, base, sourceSize)
|
||||
writeSizedFile(t, base+".ecj", 0)
|
||||
// Grown past the source by later writes: its full encode would be larger
|
||||
// than the shard, which used to read as an interrupted local encode.
|
||||
foreignSize := sourceSize + 10*1024*1024
|
||||
if calculateExpectedShardSize(foreignSize, erasure_coding.DataShardsCount) <= shardSize {
|
||||
t.Fatal("test setup: the foreign .dat must encode to larger shards")
|
||||
}
|
||||
if err := os.Truncate(base+".dat", foreignSize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
want := map[string]int64{}
|
||||
for _, ext := range []string{".dat", ".idx", ".vif", ".ecx", ".ecj", erasure_coding.ToExt(9)} {
|
||||
fi, err := os.Stat(base + ext)
|
||||
if err != nil {
|
||||
t.Fatalf("stat %s: %v", ext, err)
|
||||
}
|
||||
want[ext] = fi.Size()
|
||||
}
|
||||
vifBefore, err := os.ReadFile(base + ".vif")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !l.validateEcVolume("", vid) {
|
||||
t.Fatal("validateEcVolume would delete shards whose .vif names a different source size than the .dat beside them")
|
||||
}
|
||||
l.loadExistingVolume(filepath.Base(base)+".idx", NeedleMapInMemory, true, 0, 0, false)
|
||||
if _, found := l.FindVolume(vid); found {
|
||||
t.Fatal("a .dat that is not the encode source was loaded beside its EC shards")
|
||||
}
|
||||
for ext, size := range want {
|
||||
fi, err := os.Stat(base + ext)
|
||||
if err != nil {
|
||||
t.Fatalf("%s is gone: %v", ext, err)
|
||||
}
|
||||
if fi.Size() != size {
|
||||
t.Fatalf("%s size changed: %d -> %d", ext, size, fi.Size())
|
||||
}
|
||||
}
|
||||
if vifAfter, _ := os.ReadFile(base + ".vif"); string(vifAfter) != string(vifBefore) {
|
||||
t.Fatal(".vif was rewritten")
|
||||
}
|
||||
}
|
||||
|
||||
// The .dat matches the recorded source size and the shards are short of its
|
||||
// full encode: an interrupted local encode, still reclaimed.
|
||||
func TestValidateEcVolume_InterruptedEncodeWithRecordedSizeReclaims(t *testing.T) {
|
||||
l := newTestDiskLocation(t.TempDir())
|
||||
base := erasure_coding.EcShardFileName("", l.Directory, 75)
|
||||
|
||||
datSize := int64(30 * 1024 * 1024)
|
||||
writeSizedFile(t, base+".dat", datSize)
|
||||
writeEcVif(t, base, datSize)
|
||||
partialShardSize := calculateExpectedShardSize(datSize, erasure_coding.DataShardsCount) / 3
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
writeSizedFile(t, base+erasure_coding.ToExt(i), partialShardSize)
|
||||
}
|
||||
|
||||
if l.validateEcVolume("", 75) {
|
||||
t.Fatal("validateEcVolume kept partial shards beside the recorded source .dat")
|
||||
}
|
||||
}
|
||||
|
||||
// The .vif is written after the shards, so an interrupted re-encode of a
|
||||
// volume that was once EC-decoded still has the old encode's .vif. Shards that
|
||||
// are not that encode's full size are not described by it: reclaim as before.
|
||||
func TestValidateEcVolume_InterruptedReEncodeWithStaleVifReclaims(t *testing.T) {
|
||||
l := newTestDiskLocation(t.TempDir())
|
||||
base := erasure_coding.EcShardFileName("", l.Directory, 76)
|
||||
|
||||
oldSourceSize := int64(20 * 1024 * 1024)
|
||||
datSize := int64(60 * 1024 * 1024)
|
||||
writeSizedFile(t, base+".dat", datSize)
|
||||
writeEcVif(t, base, oldSourceSize)
|
||||
partialShardSize := calculateExpectedShardSize(datSize, erasure_coding.DataShardsCount) / 2
|
||||
if partialShardSize == calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount) {
|
||||
t.Fatal("test setup: partial shards must not match the stale encode's size")
|
||||
}
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
writeSizedFile(t, base+erasure_coding.ToExt(i), partialShardSize)
|
||||
}
|
||||
|
||||
if l.validateEcVolume("", 76) {
|
||||
t.Fatal("validateEcVolume kept partial shards of an interrupted re-encode because of a stale .vif")
|
||||
}
|
||||
}
|
||||
|
||||
// A .vif without a recorded source size keeps the old size check against the
|
||||
// .dat, in both directions.
|
||||
func TestValidateEcVolume_NoRecordedSizeKeepsOldRule(t *testing.T) {
|
||||
l := newTestDiskLocation(t.TempDir())
|
||||
base := erasure_coding.EcShardFileName("", l.Directory, 77)
|
||||
|
||||
shardSize := calculateExpectedShardSize(30*1024*1024, erasure_coding.DataShardsCount)
|
||||
writeEcVif(t, base, 0)
|
||||
writeSizedFile(t, base+erasure_coding.ToExt(0), shardSize)
|
||||
|
||||
writeSizedFile(t, base+".dat", 40*1024*1024)
|
||||
if l.validateEcVolume("", 77) {
|
||||
t.Fatal("without a recorded size, shards smaller than the .dat's full encode should be reclaimable")
|
||||
}
|
||||
writeSizedFile(t, base+".dat", 30*1024*1024)
|
||||
if !l.validateEcVolume("", 77) {
|
||||
t.Fatal("without a recorded size, shards matching the .dat's full encode must be kept")
|
||||
}
|
||||
}
|
||||
|
||||
// Under a shared -dir.idx the encode's .vif can sit on a sibling data disk,
|
||||
// where the mount also takes it from. The recorded source size must be read
|
||||
// from there too, or the shards fall back to the .dat size check and go.
|
||||
func TestValidateEcVolume_ForeignDatKeepsShardsWithSiblingVif(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
dataA, dataB, idx := filepath.Join(root, "a"), filepath.Join(root, "b"), filepath.Join(root, "idx")
|
||||
for _, d := range []string{dataA, dataB, idx} {
|
||||
if err := os.Mkdir(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
l := newTestDiskLocation(dataA)
|
||||
l.IdxDirectory = idx
|
||||
l.storeDirs = []string{dataA, dataB}
|
||||
const vid = 78
|
||||
baseA := erasure_coding.EcShardFileName("", dataA, vid)
|
||||
|
||||
sourceSize := int64(30 * 1024 * 1024)
|
||||
writeEcVif(t, erasure_coding.EcShardFileName("", dataB, vid), sourceSize)
|
||||
writeSizedFile(t, erasure_coding.EcShardFileName("", idx, vid)+".ecx", 0)
|
||||
writeSizedFile(t, baseA+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
|
||||
writeSizedFile(t, baseA+".dat", sourceSize+10*1024*1024)
|
||||
|
||||
if !l.validateEcVolume("", vid) {
|
||||
t.Fatal("validateEcVolume ignored the sibling .vif's source size and would delete the shards")
|
||||
}
|
||||
}
|
||||
|
||||
// writeEcxEndingAt writes an .ecx with one live needle ending at end in a
|
||||
// current-version .dat.
|
||||
func writeEcxEndingAt(t *testing.T, base string, end int64) {
|
||||
t.Helper()
|
||||
writeEcxEndingAtVersion(t, base, end, needle.GetCurrentVersion())
|
||||
}
|
||||
|
||||
func writeEcxEndingAtVersion(t *testing.T, base string, end int64, version needle.Version) {
|
||||
t.Helper()
|
||||
size := types.Size(1000)
|
||||
offset := end - needle.GetActualSize(size, version)
|
||||
entry := needle_map.ToBytes(1, types.ToOffset(offset), size)
|
||||
if err := os.WriteFile(base+".ecx", entry, 0o644); err != nil {
|
||||
t.Fatalf("write .ecx: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// writeSizedDat writes a .dat of size whose superblock names the current
|
||||
// needle version.
|
||||
func writeSizedDat(t *testing.T, path string, size int64) {
|
||||
t.Helper()
|
||||
writeSizedFile(t, path, size)
|
||||
f, err := os.OpenFile(path, os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := f.WriteAt([]byte{byte(needle.GetCurrentVersion())}, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A re-encode of a grown .dat interrupted under an earlier encode's .vif,
|
||||
// with every partial shard exactly as long as that earlier encode's full
|
||||
// shards. The re-encode wrote the .ecx of the grown .dat first, so it indexes
|
||||
// needles past the recorded size: the shards are not that encode's, and the
|
||||
// complete .dat is reclaimed.
|
||||
func TestValidateEcVolume_InterruptedReEncodeMatchingStaleLengthReclaims(t *testing.T) {
|
||||
l := newTestDiskLocation(t.TempDir())
|
||||
const vid = 79
|
||||
base := erasure_coding.EcShardFileName("", l.Directory, vid)
|
||||
|
||||
oldSourceSize := int64(20 * 1024 * 1024)
|
||||
datSize := int64(60 * 1024 * 1024)
|
||||
writeSizedDat(t, base+".dat", datSize)
|
||||
writeEcVif(t, base, oldSourceSize)
|
||||
writeEcxEndingAt(t, base, datSize)
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
writeSizedFile(t, base+erasure_coding.ToExt(i), calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount))
|
||||
}
|
||||
|
||||
if l.validateEcVolume("", vid) {
|
||||
t.Fatal("validateEcVolume trusted a stale .vif for partial shards under an .ecx of the grown .dat")
|
||||
}
|
||||
|
||||
// The same shards under an .ecx that stays within the recorded size are
|
||||
// that encode's: keep them.
|
||||
writeEcxEndingAt(t, base, oldSourceSize)
|
||||
if !l.validateEcVolume("", vid) {
|
||||
t.Fatal("validateEcVolume dropped shards whose .ecx and length match the recorded source")
|
||||
}
|
||||
}
|
||||
|
||||
// Only the .ecx the mount opens speaks for the shards: a non-empty data-dir
|
||||
// .ecx within the recorded size wins over an older shared-idx .ecx pointing
|
||||
// past it, and the shards stay.
|
||||
func TestValidateEcVolume_ChecksTheEcxTheMountOpens(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
data, idx := filepath.Join(root, "data"), filepath.Join(root, "idx")
|
||||
for _, d := range []string{data, idx} {
|
||||
if err := os.Mkdir(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
l := newTestDiskLocation(data)
|
||||
l.IdxDirectory = idx
|
||||
const vid = 80
|
||||
base := erasure_coding.EcShardFileName("", data, vid)
|
||||
idxBase := erasure_coding.EcShardFileName("", idx, vid)
|
||||
|
||||
sourceSize := int64(30 * 1024 * 1024)
|
||||
writeEcVif(t, base, sourceSize)
|
||||
writeEcxEndingAt(t, base, sourceSize)
|
||||
writeEcxEndingAt(t, idxBase, sourceSize+20*1024*1024)
|
||||
writeSizedFile(t, base+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
|
||||
writeSizedDat(t, base+".dat", sourceSize+10*1024*1024)
|
||||
|
||||
if !l.validateEcVolume("", vid) {
|
||||
t.Fatal("an .ecx the mount ignores decided against the shards")
|
||||
}
|
||||
|
||||
// With no data-dir .ecx the mount opens the shared one, which indexes
|
||||
// past the recorded size: the old rule applies and reclaims.
|
||||
if err := os.Remove(base + ".ecx"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if l.validateEcVolume("", vid) {
|
||||
t.Fatal("the shared .ecx the mount opens was not checked")
|
||||
}
|
||||
}
|
||||
|
||||
// The .ecx extent is sized with the needle version the encode's .vif records,
|
||||
// as the mount reads it, not the version of the foreign .dat beside it.
|
||||
func TestValidateEcVolume_SizesTheEcxWithTheEncodeVersion(t *testing.T) {
|
||||
l := newTestDiskLocation(t.TempDir())
|
||||
const vid = 81
|
||||
base := erasure_coding.EcShardFileName("", l.Directory, vid)
|
||||
|
||||
sourceSize := int64(30 * 1024 * 1024)
|
||||
vi := &volume_server_pb.VolumeInfo{
|
||||
Version: uint32(needle.Version2),
|
||||
DatFileSize: sourceSize,
|
||||
EcShardConfig: &volume_server_pb.EcShardConfig{
|
||||
DataShards: uint32(erasure_coding.DataShardsCount),
|
||||
ParityShards: uint32(erasure_coding.ParityShardsCount),
|
||||
},
|
||||
}
|
||||
if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Ends exactly at the source under version 2; version 3 would put it
|
||||
// 8 bytes past.
|
||||
writeEcxEndingAtVersion(t, base, sourceSize, needle.Version2)
|
||||
writeSizedFile(t, base+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
|
||||
writeSizedDat(t, base+".dat", sourceSize+10*1024*1024)
|
||||
|
||||
if !l.validateEcVolume("", vid) {
|
||||
t.Fatal("the .ecx was sized with the foreign .dat's needle version, not the encode's")
|
||||
}
|
||||
}
|
||||
|
||||
// An interrupted write leaves a torn .ecx tail; the whole entries before it
|
||||
// still show the re-encode's .ecx indexing past the stale recorded size.
|
||||
func TestValidateEcVolume_TornEcxTailStillReclaimsReEncode(t *testing.T) {
|
||||
l := newTestDiskLocation(t.TempDir())
|
||||
const vid = 82
|
||||
base := erasure_coding.EcShardFileName("", l.Directory, vid)
|
||||
|
||||
oldSourceSize := int64(20 * 1024 * 1024)
|
||||
datSize := int64(60 * 1024 * 1024)
|
||||
writeSizedDat(t, base+".dat", datSize)
|
||||
writeEcVif(t, base, oldSourceSize)
|
||||
writeEcxEndingAt(t, base, datSize)
|
||||
f, err := os.OpenFile(base+".ecx", os.O_APPEND|os.O_WRONLY, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.Write([]byte{1, 2, 3}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
|
||||
writeSizedFile(t, base+erasure_coding.ToExt(i), calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount))
|
||||
}
|
||||
|
||||
if l.validateEcVolume("", vid) {
|
||||
t.Fatal("a torn .ecx tail hid the entries past the stale recorded size")
|
||||
}
|
||||
}
|
||||
@@ -109,25 +109,20 @@ func FindDatFileSize(shard0FileName, indexBaseFileName string) (datSize int64, e
|
||||
// when all needles are deleted (see issue #7748).
|
||||
datSize = int64(super_block.SuperBlockSize)
|
||||
|
||||
extent, err := EcxNeedleExtent(indexBaseFileName, version)
|
||||
if extent > datSize {
|
||||
datSize = extent
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// EcxNeedleExtent returns where the furthest live needle indexed by
|
||||
// indexBaseFileName.ecx ends in the source .dat, or 0 when it indexes none.
|
||||
func EcxNeedleExtent(indexBaseFileName string, version needle.Version) (extent int64, err error) {
|
||||
err = iterateEcxFile(indexBaseFileName, func(key types.NeedleId, offset types.Offset, size types.Size) error {
|
||||
|
||||
if size.IsDeleted() {
|
||||
return nil
|
||||
}
|
||||
if end := offset.ToActualOffset() + needle.GetActualSize(size, version); end > extent {
|
||||
extent = end
|
||||
|
||||
entryStopOffset := offset.ToActualOffset() + needle.GetActualSize(size, version)
|
||||
if datSize < entryStopOffset {
|
||||
datSize = entryStopOffset
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
|
||||
@@ -16,18 +22,29 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/ecbalancer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
||||
storagetypes "github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/base"
|
||||
workerutil "github.com/seaweedfs/seaweedfs/weed/worker/tasks/util"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/types"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
minProposalsBeforeEarlyStop = 10
|
||||
maxConsecutivePlanningFailures = 10
|
||||
// A volume being decoded briefly holds a regular copy beside its complete
|
||||
// shard set; only a replica that stays there this long is an orphan.
|
||||
minOrphanSourceCoexistence = 30 * time.Minute
|
||||
)
|
||||
|
||||
// orphanSourceIndexReadTimeout bounds each .idx/.ecx read of the orphan
|
||||
// cleanup, so a stalled server cannot hold up detection.
|
||||
var orphanSourceIndexReadTimeout = 5 * time.Minute
|
||||
|
||||
// Detection implements the detection logic for erasure coding tasks.
|
||||
// It respects ctx cancellation and can stop early once maxResults is reached.
|
||||
func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, clusterInfo *types.ClusterInfo, config base.TaskConfig, maxResults int) ([]*types.TaskDetectionResult, bool, error) {
|
||||
@@ -57,6 +74,10 @@ func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, cluste
|
||||
skippedTooFewNodes := 0
|
||||
consecutivePlanningFailures := 0
|
||||
|
||||
if clusterInfo != nil && clusterInfo.ActiveTopology != nil {
|
||||
pruneOrphanSourceSightings(clusterInfo.ActiveTopology)
|
||||
}
|
||||
|
||||
// EC shard replica placement: explicit config wins, else the master default.
|
||||
var replicaPlacement *super_block.ReplicaPlacement
|
||||
if clusterInfo != nil {
|
||||
@@ -703,6 +724,10 @@ func findExistingECShards(activeTopology *topology.ActiveTopology, volumeID uint
|
||||
// targeted server, never EC shards (those live in a separate store path).
|
||||
// The cluster-wide `volume.delete` shell command is what would have nuked
|
||||
// the EC shards too; the targeted RPC used here is safe by construction.
|
||||
// A replica is deleted only once it has sat beside the shards for
|
||||
// minOrphanSourceCoexistence, only while read-only, and only when every live
|
||||
// needle in its .idx is accounted for by the EC volume's .ecx (see
|
||||
// needlesMissingFromEc); one that took writes after the encode is kept.
|
||||
// Returns the count of replicas successfully deleted plus any error.
|
||||
func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.ClusterInfo, metric *types.VolumeHealthMetrics, expectedShards int) (int, error) {
|
||||
if clusterInfo == nil || clusterInfo.ActiveTopology == nil {
|
||||
@@ -728,11 +753,26 @@ func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.Cluster
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
ecx := &ecxReader{
|
||||
holders: ec.LargestEcGenerationHolders(clusterInfo.ActiveTopology.GetTopologyInfo(), metric.VolumeID, metric.Collection),
|
||||
volumeID: metric.VolumeID,
|
||||
collection: metric.Collection,
|
||||
dialOption: clusterInfo.GrpcDialOption,
|
||||
}
|
||||
|
||||
deleted := 0
|
||||
var deleteErrors []string
|
||||
now := time.Now()
|
||||
for _, replica := range replicas {
|
||||
serverAddress := replica.ServerID
|
||||
sighting := orphanSourceKey{volumeID: metric.VolumeID, collection: metric.Collection, server: serverAddress}
|
||||
if sat := now.Sub(sightOrphanSource(sighting, expectedShards, now)); sat < minOrphanSourceCoexistence {
|
||||
glog.V(1).Infof("EC Detection: source replica for volume %d on %s has sat beside the EC shards for %v; waiting %v before treating it as orphaned",
|
||||
metric.VolumeID, serverAddress, sat.Truncate(time.Second), minOrphanSourceCoexistence)
|
||||
continue
|
||||
}
|
||||
var isReadOnly bool
|
||||
var missing int
|
||||
err := operation.WithVolumeServerClient(false, pb.ServerAddress(serverAddress), clusterInfo.GrpcDialOption,
|
||||
func(client volume_server_pb.VolumeServerClient) error {
|
||||
// Re-probe before deleting: only a still-readonly source replica is
|
||||
@@ -746,6 +786,12 @@ func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.Cluster
|
||||
if !isReadOnly {
|
||||
return nil
|
||||
}
|
||||
// Read-only does not prove the replica took no writes after
|
||||
// the encode: it may have been writable in between.
|
||||
var checkErr error
|
||||
if missing, checkErr = needlesMissingFromEc(ctx, client, metric.VolumeID, metric.Collection, ecx); checkErr != nil || missing > 0 {
|
||||
return checkErr
|
||||
}
|
||||
_, deleteErr := client.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{
|
||||
VolumeId: metric.VolumeID,
|
||||
OnlyEmpty: false,
|
||||
@@ -760,7 +806,12 @@ func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.Cluster
|
||||
glog.Warningf("EC Detection: source replica for volume %d on %s is writable; not deleting (may hold writes the EC shards lack)", metric.VolumeID, serverAddress)
|
||||
continue
|
||||
}
|
||||
if missing > 0 {
|
||||
glog.Warningf("EC Detection: source replica for volume %d on %s holds %d needles the EC volume lacks or holds differently; keeping it", metric.VolumeID, serverAddress, missing)
|
||||
continue
|
||||
}
|
||||
deleted++
|
||||
forgetOrphanSource(sighting)
|
||||
glog.V(1).Infof("EC Detection: deleted orphan regular replica for volume %d on %s", metric.VolumeID, serverAddress)
|
||||
}
|
||||
|
||||
@@ -770,6 +821,181 @@ func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.Cluster
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
type orphanSourceKey struct {
|
||||
volumeID uint32
|
||||
collection string
|
||||
server string
|
||||
}
|
||||
|
||||
// orphanSourceSighting is when detection first saw a regular replica beside a
|
||||
// complete EC shard set, and the shard count that made the set complete.
|
||||
type orphanSourceSighting struct {
|
||||
at time.Time
|
||||
expectedShards int
|
||||
}
|
||||
|
||||
// orphanSourceSightings is in memory only: a restart just delays cleanup.
|
||||
var orphanSourceSightings = struct {
|
||||
sync.Mutex
|
||||
firstSeen map[orphanSourceKey]orphanSourceSighting
|
||||
}{firstSeen: make(map[orphanSourceKey]orphanSourceSighting)}
|
||||
|
||||
// sightOrphanSource records a sighting and returns the first one.
|
||||
func sightOrphanSource(key orphanSourceKey, expectedShards int, now time.Time) time.Time {
|
||||
orphanSourceSightings.Lock()
|
||||
defer orphanSourceSightings.Unlock()
|
||||
sighting, found := orphanSourceSightings.firstSeen[key]
|
||||
if !found {
|
||||
sighting.at = now
|
||||
}
|
||||
sighting.expectedShards = expectedShards
|
||||
orphanSourceSightings.firstSeen[key] = sighting
|
||||
return sighting.at
|
||||
}
|
||||
|
||||
func forgetOrphanSource(key orphanSourceKey) {
|
||||
orphanSourceSightings.Lock()
|
||||
defer orphanSourceSightings.Unlock()
|
||||
delete(orphanSourceSightings.firstSeen, key)
|
||||
}
|
||||
|
||||
// pruneOrphanSourceSightings forgets every sighting whose replica no longer
|
||||
// sits beside a complete EC shard set, so a coexistence that ends and later
|
||||
// recurs starts its wait over.
|
||||
func pruneOrphanSourceSightings(activeTopology *topology.ActiveTopology) {
|
||||
orphanSourceSightings.Lock()
|
||||
sightings := maps.Clone(orphanSourceSightings.firstSeen)
|
||||
orphanSourceSightings.Unlock()
|
||||
if len(sightings) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
volumes := make(map[ec.EcVolumeKey]struct{}, len(sightings))
|
||||
for key := range sightings {
|
||||
volumes[ec.EcVolumeKey{VolumeId: key.volumeID, Collection: key.collection}] = struct{}{}
|
||||
}
|
||||
shardCounts := ec.CountExistingEcShardsForVolumes(activeTopology.GetTopologyInfo(), volumes)
|
||||
var ended []orphanSourceKey
|
||||
for key, sighting := range sightings {
|
||||
if shardCounts[ec.EcVolumeKey{VolumeId: key.volumeID, Collection: key.collection}] < sighting.expectedShards ||
|
||||
!slices.ContainsFunc(findVolumeReplicaLocations(activeTopology, key.volumeID, key.collection), func(replica topology.VolumeReplica) bool {
|
||||
return replica.ServerID == key.server
|
||||
}) {
|
||||
ended = append(ended, key)
|
||||
}
|
||||
}
|
||||
|
||||
orphanSourceSightings.Lock()
|
||||
defer orphanSourceSightings.Unlock()
|
||||
for _, key := range ended {
|
||||
delete(orphanSourceSightings.firstSeen, key)
|
||||
}
|
||||
}
|
||||
|
||||
// needlesMissingFromEc counts the live needles in the replica's .idx that the
|
||||
// EC volume's .ecx does not account for. The .ecx lists the needles live at
|
||||
// encode time with their sizes; a later delete marks its entry in place and
|
||||
// keeps the offset. A live replica needle is accounted for when the .ecx holds
|
||||
// it at the same size, or deleted at the same offset (the encoded record,
|
||||
// deleted since). Anything else may be data the EC volume never had.
|
||||
func needlesMissingFromEc(ctx context.Context, client volume_server_pb.VolumeServerClient, volumeID uint32, collection string, ecx *ecxReader) (int, error) {
|
||||
idxBytes, err := readVolumeFile(ctx, client, volumeID, collection, ".idx", false)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("read source replica .idx: %w", err)
|
||||
}
|
||||
live := make(map[storagetypes.NeedleId]needle_map.NeedleValue)
|
||||
err = idx.WalkIndexFile(bytes.NewReader(idxBytes), 0, func(key storagetypes.NeedleId, offset storagetypes.Offset, size storagetypes.Size) error {
|
||||
if offset.IsZero() || !size.IsValid() {
|
||||
delete(live, key)
|
||||
} else {
|
||||
live[key] = needle_map.NeedleValue{Key: key, Offset: offset, Size: size}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("walk source replica .idx: %w", err)
|
||||
}
|
||||
if len(live) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
ecxBytes, err := ecx.read(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
err = idx.WalkIndexFile(bytes.NewReader(ecxBytes), 0, func(key storagetypes.NeedleId, offset storagetypes.Offset, size storagetypes.Size) error {
|
||||
if replica, found := live[key]; found && (size == replica.Size || size.IsDeleted() && offset == replica.Offset) {
|
||||
delete(live, key)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("walk .ecx: %w", err)
|
||||
}
|
||||
return len(live), nil
|
||||
}
|
||||
|
||||
// ecxReader fetches the EC volume's .ecx from one of its shard holders, once.
|
||||
type ecxReader struct {
|
||||
holders []pb.ServerAddress
|
||||
volumeID uint32
|
||||
collection string
|
||||
dialOption grpc.DialOption
|
||||
content []byte
|
||||
loaded bool
|
||||
}
|
||||
|
||||
func (r *ecxReader) read(ctx context.Context) ([]byte, error) {
|
||||
if r.loaded {
|
||||
return r.content, nil
|
||||
}
|
||||
if len(r.holders) == 0 {
|
||||
return nil, fmt.Errorf("no EC shard holder of volume %d to read .ecx from", r.volumeID)
|
||||
}
|
||||
var errs []string
|
||||
for _, holder := range r.holders {
|
||||
err := operation.WithVolumeServerClient(false, holder, r.dialOption,
|
||||
func(client volume_server_pb.VolumeServerClient) error {
|
||||
content, readErr := readVolumeFile(ctx, client, r.volumeID, r.collection, ".ecx", true)
|
||||
r.content = content
|
||||
return readErr
|
||||
})
|
||||
if err == nil {
|
||||
r.loaded = true
|
||||
return r.content, nil
|
||||
}
|
||||
errs = append(errs, fmt.Sprintf("%s: %v", holder, err))
|
||||
}
|
||||
return nil, fmt.Errorf("read .ecx of volume %d: %s", r.volumeID, strings.Join(errs, "; "))
|
||||
}
|
||||
|
||||
// readVolumeFile reads a whole volume file over the CopyFile RPC.
|
||||
func readVolumeFile(ctx context.Context, client volume_server_pb.VolumeServerClient, volumeID uint32, collection, ext string, isEcVolume bool) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, orphanSourceIndexReadTimeout)
|
||||
defer cancel()
|
||||
stream, err := client.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
|
||||
VolumeId: volumeID,
|
||||
Collection: collection,
|
||||
Ext: ext,
|
||||
CompactionRevision: math.MaxUint32,
|
||||
StopOffset: math.MaxInt64,
|
||||
IsEcVolume: isEcVolume,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
for {
|
||||
resp, recvErr := stream.Recv()
|
||||
if recvErr == io.EOF {
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
if recvErr != nil {
|
||||
return nil, recvErr
|
||||
}
|
||||
buf.Write(resp.GetFileContent())
|
||||
}
|
||||
}
|
||||
|
||||
// countExistingEcShardsForVolume counts (volumeID, collection) EC shards in the
|
||||
// topology, counting only the single largest encode generation; see
|
||||
// ec.CountExistingEcShardsForVolume for the generation semantics.
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
|
||||
"github.com/seaweedfs/seaweedfs/weed/ec"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -90,3 +92,50 @@ func TestCountExistingEcShards_PreUpgradeZeroGeneration(t *testing.T) {
|
||||
})
|
||||
require.Equal(t, 14, countExistingEcShardsForVolume(at, vid, ""))
|
||||
}
|
||||
|
||||
// The .ecx used to vet a source replica must come from a holder of the
|
||||
// generation that is counted as the EC volume, never from a stale run, and no
|
||||
// holder is named when two generations tie.
|
||||
func TestLargestEcGenerationHolders(t *testing.T) {
|
||||
const vid = uint32(45)
|
||||
at := buildEcTopology(t, vid, "", []ecShardSet{
|
||||
{bits: ecBits(0, 1, 2), encodeTsNs: 1},
|
||||
{bits: ecBits(0, 1, 2, 3, 4, 5, 6), encodeTsNs: 2},
|
||||
{bits: ecBits(7, 8, 9, 10, 11, 12, 13), encodeTsNs: 2},
|
||||
})
|
||||
require.Equal(t, []pb.ServerAddress{"10.0.0.2:8080", "10.0.0.3:8080"}, ec.LargestEcGenerationHolders(at.GetTopologyInfo(), vid, ""))
|
||||
|
||||
tied := buildEcTopology(t, vid, "", []ecShardSet{
|
||||
{bits: ecBits(0, 1, 2), encodeTsNs: 1},
|
||||
{bits: ecBits(3, 4, 5), encodeTsNs: 2},
|
||||
})
|
||||
require.Nil(t, ec.LargestEcGenerationHolders(tied.GetTopologyInfo(), vid, ""))
|
||||
require.Nil(t, ec.LargestEcGenerationHolders(nil, vid, ""))
|
||||
}
|
||||
|
||||
// One walk counts each requested volume as CountExistingEcShardsForVolume does,
|
||||
// keeping generations and collections apart and skipping unrequested volumes.
|
||||
func TestCountExistingEcShardsForVolumes(t *testing.T) {
|
||||
shards := func(vid uint32, collection string, bits uint32, encodeTsNs int64) *master_pb.VolumeEcShardInformationMessage {
|
||||
return &master_pb.VolumeEcShardInformationMessage{Id: vid, Collection: collection, EcIndexBits: bits, EncodeTsNs: encodeTsNs}
|
||||
}
|
||||
node := func(id string, infos ...*master_pb.VolumeEcShardInformationMessage) *master_pb.DataNodeInfo {
|
||||
return &master_pb.DataNodeInfo{Id: id, DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {EcShardInfos: infos}}}
|
||||
}
|
||||
topologyInfo := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
node("10.0.0.1:8080", shards(1, "", ecBits(0, 1, 2, 3, 4, 5, 6), 7), shards(2, "", ecBits(0, 1, 2), 1)),
|
||||
node("10.0.0.2:8080", shards(1, "", ecBits(7, 8, 9, 10, 11, 12, 13), 7), shards(2, "", ecBits(3, 4), 2), shards(2, "other", ecBits(5, 6, 7, 8), 1)),
|
||||
node("10.0.0.3:8080", shards(3, "", ecBits(0, 1), 1)),
|
||||
}}},
|
||||
}}}
|
||||
counts := ec.CountExistingEcShardsForVolumes(topologyInfo, map[ec.EcVolumeKey]struct{}{
|
||||
{VolumeId: 1}: {},
|
||||
{VolumeId: 2}: {},
|
||||
{VolumeId: 4}: {},
|
||||
})
|
||||
require.Equal(t, map[ec.EcVolumeKey]int{{VolumeId: 1}: 14, {VolumeId: 2}: 3}, counts)
|
||||
require.Equal(t, 14, ec.CountExistingEcShardsForVolume(topologyInfo, 1, ""))
|
||||
require.Equal(t, 4, ec.CountExistingEcShardsForVolume(topologyInfo, 2, "other"))
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
package erasure_coding
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -10,6 +16,9 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
|
||||
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
|
||||
storagetypes "github.com/seaweedfs/seaweedfs/weed/storage/types"
|
||||
"github.com/seaweedfs/seaweedfs/weed/worker/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
@@ -36,6 +45,7 @@ func TestCleanupOrphanSkipsWritableSourceReplica(t *testing.T) {
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
metric := &types.VolumeHealthMetrics{VolumeID: volumeID, Collection: ""}
|
||||
backdateOrphanSource(t, volumeID, "", clusterHarness.VolumeServerAddress())
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
@@ -92,3 +102,357 @@ func buildSingleNodeTopology(t *testing.T, serverAddr string, volumeID uint32) *
|
||||
require.NoError(t, at.UpdateTopology(topologyInfo))
|
||||
return at
|
||||
}
|
||||
|
||||
// fakeOrphanServer is a stub VolumeServer serving a read-only source replica's
|
||||
// .idx or an EC shard holder's .ecx, and recording a VolumeDelete.
|
||||
type fakeOrphanServer struct {
|
||||
volume_server_pb.UnimplementedVolumeServerServer
|
||||
|
||||
mu sync.Mutex
|
||||
files map[string][]byte
|
||||
copyErr error
|
||||
stall bool
|
||||
deleted bool
|
||||
}
|
||||
|
||||
func (f *fakeOrphanServer) VolumeStatus(context.Context, *volume_server_pb.VolumeStatusRequest) (*volume_server_pb.VolumeStatusResponse, error) {
|
||||
return &volume_server_pb.VolumeStatusResponse{IsReadOnly: true}, nil
|
||||
}
|
||||
|
||||
func (f *fakeOrphanServer) VolumeDelete(context.Context, *volume_server_pb.VolumeDeleteRequest) (*volume_server_pb.VolumeDeleteResponse, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.deleted = true
|
||||
return &volume_server_pb.VolumeDeleteResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *fakeOrphanServer) CopyFile(req *volume_server_pb.CopyFileRequest, stream grpc.ServerStreamingServer[volume_server_pb.CopyFileResponse]) error {
|
||||
if f.copyErr != nil {
|
||||
return f.copyErr
|
||||
}
|
||||
if f.stall {
|
||||
<-stream.Context().Done()
|
||||
return stream.Context().Err()
|
||||
}
|
||||
f.mu.Lock()
|
||||
content, found := f.files[req.GetExt()]
|
||||
f.mu.Unlock()
|
||||
if !found || req.GetIsEcVolume() != (req.GetExt() == ".ecx") {
|
||||
return fmt.Errorf("volume %d%s not found", req.GetVolumeId(), req.GetExt())
|
||||
}
|
||||
return stream.Send(&volume_server_pb.CopyFileResponse{FileContent: content})
|
||||
}
|
||||
|
||||
func (f *fakeOrphanServer) setFile(ext string, content []byte) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.files[ext] = content
|
||||
}
|
||||
|
||||
func (f *fakeOrphanServer) wasDeleted() bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.deleted
|
||||
}
|
||||
|
||||
func startFakeOrphanServer(t *testing.T, server *fakeOrphanServer) string {
|
||||
t.Helper()
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
grpcServer := grpc.NewServer()
|
||||
volume_server_pb.RegisterVolumeServerServer(grpcServer, server)
|
||||
go grpcServer.Serve(lis)
|
||||
t.Cleanup(grpcServer.Stop)
|
||||
_, port, err := net.SplitHostPort(lis.Addr().String())
|
||||
require.NoError(t, err)
|
||||
return "127.0.0.1:0." + port
|
||||
}
|
||||
|
||||
// indexEntry is one index record; an unset offset is derived from the key.
|
||||
type indexEntry struct {
|
||||
key uint64
|
||||
size storagetypes.Size
|
||||
offset int64
|
||||
}
|
||||
|
||||
func indexBytes(entries ...indexEntry) []byte {
|
||||
var buf bytes.Buffer
|
||||
for _, e := range entries {
|
||||
offset := e.offset
|
||||
if offset == 0 {
|
||||
offset = int64(e.key) * 8
|
||||
}
|
||||
buf.Write(needle_map.ToBytes(storagetypes.NeedleId(e.key), storagetypes.ToOffset(offset), e.size))
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// buildOrphanTopology places the regular replica on replicaAddr and the full
|
||||
// EC shard set on holderAddr. The holder reports its gRPC port in GrpcPort
|
||||
// rather than in its id, so it is reachable only through that port.
|
||||
func buildOrphanTopology(t *testing.T, replicaAddr, holderAddr string, volumeID uint32) *topology.ActiveTopology {
|
||||
t.Helper()
|
||||
grpcPort, err := strconv.Atoi(holderAddr[strings.LastIndex(holderAddr, ".")+1:])
|
||||
require.NoError(t, err)
|
||||
at := topology.NewActiveTopology(10)
|
||||
require.NoError(t, at.UpdateTopology(&master_pb.TopologyInfo{
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{Id: replicaAddr, DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{{Id: volumeID}},
|
||||
}}},
|
||||
{Id: "ec-holder", Address: "127.0.0.1:1", GrpcPort: uint32(grpcPort), DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{
|
||||
Id: volumeID,
|
||||
EcIndexBits: uint32(1)<<erasure_coding.TotalShardsCount - 1,
|
||||
EncodeTsNs: 1,
|
||||
}},
|
||||
}}},
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}))
|
||||
return at
|
||||
}
|
||||
|
||||
// A read-only source replica is deleted only when the EC volume's .ecx accounts
|
||||
// for every live needle in its .idx: held at the same size, or deleted at the
|
||||
// same offset.
|
||||
func TestCleanupOrphanChecksSourceNeedlesAgainstEcx(t *testing.T) {
|
||||
const volumeID = uint32(956)
|
||||
ecx := indexBytes(
|
||||
indexEntry{key: 1, size: 100},
|
||||
indexEntry{key: 2, size: storagetypes.TombstoneFileSize},
|
||||
indexEntry{key: 3, size: 100},
|
||||
)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
idx []byte
|
||||
ecxCopyErr error
|
||||
wantDeleted bool
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "live needles held in ecx or deleted there in place",
|
||||
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 2, size: 100}, indexEntry{key: 3, size: 100}),
|
||||
wantDeleted: true,
|
||||
},
|
||||
{
|
||||
name: "live needles in ecx at other offsets",
|
||||
idx: indexBytes(indexEntry{key: 1, size: 100, offset: 800}, indexEntry{key: 3, size: 100, offset: 808}),
|
||||
wantDeleted: true,
|
||||
},
|
||||
{
|
||||
name: "needle rewritten at another size",
|
||||
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 3, size: 100}, indexEntry{key: 3, size: 150, offset: 800}),
|
||||
},
|
||||
{
|
||||
name: "needle deleted in ecx but rewritten in the replica",
|
||||
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 2, size: 100, offset: 800}),
|
||||
},
|
||||
{
|
||||
name: "live needle absent from ecx",
|
||||
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 4, size: 100}, indexEntry{key: 5, size: 100}),
|
||||
},
|
||||
{
|
||||
name: "needle absent from ecx is deleted in the replica",
|
||||
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 4, size: 100}, indexEntry{key: 4, size: storagetypes.TombstoneFileSize}),
|
||||
wantDeleted: true,
|
||||
},
|
||||
{
|
||||
name: "ecx copy fails",
|
||||
idx: indexBytes(indexEntry{key: 1, size: 100}),
|
||||
ecxCopyErr: fmt.Errorf("holder unreachable"),
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
replica := &fakeOrphanServer{files: map[string][]byte{".idx": tt.idx}}
|
||||
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": ecx}, copyErr: tt.ecxCopyErr}
|
||||
replicaAddr := startFakeOrphanServer(t, replica)
|
||||
clusterInfo := &types.ClusterInfo{
|
||||
ActiveTopology: buildOrphanTopology(t, replicaAddr, startFakeOrphanServer(t, holder), volumeID),
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
backdateOrphanSource(t, volumeID, "", replicaAddr)
|
||||
metric := &types.VolumeHealthMetrics{VolumeID: volumeID}
|
||||
|
||||
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
|
||||
if tt.wantErr {
|
||||
require.Error(t, err)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
}
|
||||
require.Equal(t, tt.wantDeleted, replica.wasDeleted())
|
||||
if tt.wantDeleted {
|
||||
require.Equal(t, 1, deleted)
|
||||
} else {
|
||||
require.Equal(t, 0, deleted)
|
||||
}
|
||||
require.False(t, holder.wasDeleted())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// backdateOrphanSource records a sighting old enough for cleanup to act on.
|
||||
func backdateOrphanSource(t *testing.T, volumeID uint32, collection, server string) {
|
||||
t.Helper()
|
||||
key := orphanSourceKey{volumeID: volumeID, collection: collection, server: server}
|
||||
orphanSourceSightings.Lock()
|
||||
orphanSourceSightings.firstSeen[key] = orphanSourceSighting{
|
||||
at: time.Now().Add(-minOrphanSourceCoexistence - time.Minute),
|
||||
expectedShards: erasure_coding.TotalShardsCount,
|
||||
}
|
||||
orphanSourceSightings.Unlock()
|
||||
t.Cleanup(func() { forgetOrphanSource(key) })
|
||||
}
|
||||
|
||||
// A replica first seen beside the shards is left alone; once it has sat there
|
||||
// for minOrphanSourceCoexistence it is deleted, still subject to the needle check.
|
||||
func TestCleanupOrphanWaitsForSustainedCoexistence(t *testing.T) {
|
||||
const volumeID = uint32(957)
|
||||
ecx := indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 2, size: 100})
|
||||
replica := &fakeOrphanServer{files: map[string][]byte{".idx": indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 3, size: 100})}}
|
||||
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": ecx}}
|
||||
replicaAddr := startFakeOrphanServer(t, replica)
|
||||
clusterInfo := &types.ClusterInfo{
|
||||
ActiveTopology: buildOrphanTopology(t, replicaAddr, startFakeOrphanServer(t, holder), volumeID),
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
metric := &types.VolumeHealthMetrics{VolumeID: volumeID}
|
||||
t.Cleanup(func() { forgetOrphanSource(orphanSourceKey{volumeID: volumeID, server: replicaAddr}) })
|
||||
|
||||
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, deleted)
|
||||
require.False(t, replica.wasDeleted(), "a replica first seen beside the shards must not be deleted")
|
||||
|
||||
backdateOrphanSource(t, volumeID, "", replicaAddr)
|
||||
deleted, err = cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, deleted)
|
||||
require.False(t, replica.wasDeleted(), "an aged replica holding needles the EC volume lacks must be kept")
|
||||
|
||||
replica.setFile(".idx", indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 2, size: 100}))
|
||||
deleted, err = cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, deleted)
|
||||
require.True(t, replica.wasDeleted())
|
||||
}
|
||||
|
||||
// A sighting is forgotten once the replica no longer sits beside a complete
|
||||
// shard set, so a later coexistence (such as a decode) waits from scratch.
|
||||
func TestOrphanSourceSightingResetsWhenCoexistenceEnds(t *testing.T) {
|
||||
const volumeID = uint32(958)
|
||||
ecx := indexBytes(indexEntry{key: 1, size: 100})
|
||||
replica := &fakeOrphanServer{files: map[string][]byte{".idx": indexBytes(indexEntry{key: 1, size: 100})}}
|
||||
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": ecx}}
|
||||
replicaAddr := startFakeOrphanServer(t, replica)
|
||||
fullTopology := buildOrphanTopology(t, replicaAddr, startFakeOrphanServer(t, holder), volumeID)
|
||||
clusterInfo := &types.ClusterInfo{
|
||||
ActiveTopology: fullTopology,
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
metric := &types.VolumeHealthMetrics{VolumeID: volumeID}
|
||||
key := orphanSourceKey{volumeID: volumeID, server: replicaAddr}
|
||||
backdateOrphanSource(t, volumeID, "", replicaAddr)
|
||||
goneKey := orphanSourceKey{volumeID: volumeID, server: "127.0.0.1:0.1"}
|
||||
backdateOrphanSource(t, volumeID, "", goneKey.server)
|
||||
|
||||
pruneOrphanSourceSightings(fullTopology)
|
||||
orphanSourceSightings.Lock()
|
||||
_, kept := orphanSourceSightings.firstSeen[key]
|
||||
_, goneKept := orphanSourceSightings.firstSeen[goneKey]
|
||||
orphanSourceSightings.Unlock()
|
||||
require.True(t, kept, "a sighting must survive while the coexistence lasts")
|
||||
require.False(t, goneKept, "a sighting of a server no longer holding the replica must be forgotten")
|
||||
|
||||
pruneOrphanSourceSightings(buildSingleNodeTopology(t, replicaAddr, volumeID))
|
||||
orphanSourceSightings.Lock()
|
||||
_, kept = orphanSourceSightings.firstSeen[key]
|
||||
orphanSourceSightings.Unlock()
|
||||
require.False(t, kept, "a sighting must be forgotten once the shards are gone")
|
||||
|
||||
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, deleted)
|
||||
require.False(t, replica.wasDeleted(), "a renewed coexistence must wait again")
|
||||
}
|
||||
|
||||
// A collection encoded with fewer shards than the default ratio is complete at
|
||||
// its own count, so its sighting must age instead of being pruned every cycle.
|
||||
func TestOrphanSourceSightingKeepsCustomRatioShardSet(t *testing.T) {
|
||||
const volumeID = uint32(960)
|
||||
const customShards = 9
|
||||
replica := &fakeOrphanServer{files: map[string][]byte{".idx": indexBytes(indexEntry{key: 1, size: 100})}}
|
||||
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": indexBytes(indexEntry{key: 1, size: 100})}}
|
||||
replicaAddr := startFakeOrphanServer(t, replica)
|
||||
at := buildOrphanTopology(t, replicaAddr, startFakeOrphanServer(t, holder), volumeID)
|
||||
topologyInfo := at.GetTopologyInfo()
|
||||
topologyInfo.DataCenterInfos[0].RackInfos[0].DataNodeInfos[1].DiskInfos["hdd"].EcShardInfos[0].EcIndexBits = uint32(1)<<customShards - 1
|
||||
require.NoError(t, at.UpdateTopology(topologyInfo))
|
||||
clusterInfo := &types.ClusterInfo{
|
||||
ActiveTopology: at,
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
key := orphanSourceKey{volumeID: volumeID, server: replicaAddr}
|
||||
t.Cleanup(func() { forgetOrphanSource(key) })
|
||||
sightOrphanSource(key, customShards, time.Now().Add(-minOrphanSourceCoexistence-time.Minute))
|
||||
|
||||
pruneOrphanSourceSightings(at)
|
||||
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, &types.VolumeHealthMetrics{VolumeID: volumeID}, customShards)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, deleted)
|
||||
require.True(t, replica.wasDeleted(), "a sighting of a complete custom-ratio shard set must survive the prune")
|
||||
}
|
||||
|
||||
// A holder that stalls mid-read is given up on after orphanSourceIndexReadTimeout
|
||||
// and the .ecx is read from the next holder instead.
|
||||
func TestCleanupOrphanReadsEcxPastStalledHolder(t *testing.T) {
|
||||
const volumeID = uint32(959)
|
||||
saved := orphanSourceIndexReadTimeout
|
||||
orphanSourceIndexReadTimeout = 200 * time.Millisecond
|
||||
t.Cleanup(func() { orphanSourceIndexReadTimeout = saved })
|
||||
|
||||
ecx := indexBytes(indexEntry{key: 1, size: 100})
|
||||
replica := &fakeOrphanServer{files: map[string][]byte{".idx": ecx}}
|
||||
stalled := &fakeOrphanServer{stall: true}
|
||||
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": ecx}}
|
||||
replicaAddr := startFakeOrphanServer(t, replica)
|
||||
half := func(addr string, bits uint32) *master_pb.DataNodeInfo {
|
||||
return &master_pb.DataNodeInfo{Id: addr, DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {
|
||||
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{Id: volumeID, EcIndexBits: bits, EncodeTsNs: 1}},
|
||||
}}}
|
||||
}
|
||||
at := topology.NewActiveTopology(10)
|
||||
require.NoError(t, at.UpdateTopology(&master_pb.TopologyInfo{
|
||||
DataCenterInfos: []*master_pb.DataCenterInfo{{
|
||||
Id: "dc1",
|
||||
RackInfos: []*master_pb.RackInfo{{
|
||||
Id: "rack1",
|
||||
DataNodeInfos: []*master_pb.DataNodeInfo{
|
||||
{Id: replicaAddr, DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {
|
||||
VolumeInfos: []*master_pb.VolumeInformationMessage{{Id: volumeID}},
|
||||
}}},
|
||||
half(startFakeOrphanServer(t, stalled), uint32(1)<<erasure_coding.DataShardsCount-1),
|
||||
half(startFakeOrphanServer(t, holder), (uint32(1)<<erasure_coding.TotalShardsCount-1)&^(uint32(1)<<erasure_coding.DataShardsCount-1)),
|
||||
},
|
||||
}},
|
||||
}},
|
||||
}))
|
||||
clusterInfo := &types.ClusterInfo{
|
||||
ActiveTopology: at,
|
||||
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
}
|
||||
backdateOrphanSource(t, volumeID, "", replicaAddr)
|
||||
|
||||
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, &types.VolumeHealthMetrics{VolumeID: volumeID}, erasure_coding.TotalShardsCount)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, deleted)
|
||||
require.True(t, replica.wasDeleted())
|
||||
}
|
||||
Reference in new issue
Block a user