Compare commits

..
Author SHA1 Message Date
Chris Lu b749950d99 seaweed-volume: size the .ecx extent with the encode's needle version
Mirrors the Go volume server: ecx_indexes_past sizes needles with the
version the encode's .vif records, as the mount reads it, instead of the
version of the .dat beside the shards. An unreadable .ecx already keeps
the shards here, since the whole file is read before any entry counts;
a torn tail still counts the whole entries before it. Both cases are
now covered by tests.
2026-12-06 01:09:25 -08:00
Chris Lu e75e330376 storage: keep EC shards when the .ecx cannot be read
The extent check ignored the scan's error, so a read failure after an
entry past the recorded size still disqualified the recorded size and
let the shards be reclaimed. Only a torn tail, which an interrupted
write leaves, keeps the entries before it; any other read error now
keeps the shards.
2026-12-06 01:08:27 -08:00
Chris Lu 71b438c90c storage: size the .ecx extent with the encode's needle version
The extent check took the needle version from the .dat beside the
shards, which is the very file that may not be their source. Under a
different version than the encode's, a healthy .ecx could appear to
index past the recorded size and its shards would be reclaimed. Use
the version the encode's .vif records, as the mount reads it.
2026-12-06 01:08:09 -08:00
Chris Lu 1b4d5b7df2 seaweed-volume: check only the .ecx the mount opens against the recorded source
Mirrors the Go volume server: ecx_indexes_past reads the .ecx the mount
selects (the data dir's when non-empty, else the idx dir's), so a stale
shared .ecx the mount never opens cannot disqualify a healthy encode.
2026-12-06 00:53:20 -08:00
Chris Lu 63d6686221 storage: check only the .ecx the mount opens against the recorded source
The extent check read both the data-dir and the idx-dir .ecx, so a stale
shared .ecx the mount would never open could disqualify a healthy encode
and let a foreign .dat beside it reclaim the shards. Check the .ecx the
mount selects: the data dir's when non-empty, else the idx dir's.
2026-12-06 00:52:28 -08:00
Chris Lu 54efc0bf7e seaweed-volume: require the .ecx to fit the recorded source before trusting it
Mirrors the Go volume server: validate_ec_volume trusts the source size
the .vif records only when no .ecx beside the shards indexes a needle
past it, so partial shards of a re-encode interrupted under an earlier
encode's .vif are reclaimed even when their length matches that earlier
encode. find_dat_file_size_with_dirs now shares the .ecx extent scan.
2026-12-06 00:46:28 -08:00
Chris Lu 9efd3951fe storage: require the .ecx to fit the recorded source before trusting it
A re-encode of a grown .dat interrupted under an earlier encode's .vif
can leave partial shards that happen to be exactly as long as that
earlier encode's full shards, and the length check alone then trusted
the stale .vif and kept them. The re-encode writes the .ecx of the
grown .dat before any shard, so it indexes needles past the recorded
size, which no .ecx of a completed encode does. Trust the recorded size
only when no .ecx beside the shards indexes past it; an unreadable .ecx
or .dat keeps the shards.

FindDatFileSize now shares the .ecx extent scan.
2026-12-06 00:45:15 -08:00
Chris Lu 05d1c3a743 seaweed-volume: read the recorded EC source size from the encode's own .vif
Mirrors the Go volume server: validate_ec_volume resolves one .vif for
the encode, including the sibling data disk the mount takes it from
under a shared -dir.idx, and takes both the shard count and the
recorded source size from it.
2026-12-06 00:43:34 -08:00
Chris Lu 744caf3c9d storage: read the recorded EC source size from the encode's own .vif
The source size was looked up in the data and idx dirs only. Under a
shared -dir.idx the encode's .vif can sit on a sibling data disk, where
the shard count and the mount already take it from, so the source size
was missed and shards beside a foreign .dat fell back to the .dat size
check. Resolve one .vif for the encode and take both the shard count and
the source size from it.
2026-12-06 00:42:28 -08:00
Chris Lu ce338a724d seaweed-volume: keep EC shards when the .dat beside them is not their encode source
Mirrors the Go volume server: validate_ec_volume keeps shards that are
exactly the full encode of the source size their .vif records when the
.dat beside them has a different size, and leaves that .dat unloaded and
untouched. Without a recorded size, or with shards that are not that
encode's full size, the existing interrupted-encode reclaim applies.
2026-12-05 23:45:47 -08:00
Chris Lu faa7be7790 storage: keep EC shards when the .dat beside them is not their encode source
Startup validation compared the local shards with the full encode of
whatever .dat sat beside them and deleted the shards when they came out
smaller, taking that as an interrupted local encode. A .dat that is not
the encode source but grew past it (a regular replica that kept taking
writes) therefore made the server delete healthy shards and load the
.dat in their place.

The .vif records the size of the .dat the encode read. When the shards
are exactly the full encode of that size and the .dat beside them has a
different size, the .dat is not their source: keep the shards and leave
the .dat unloaded and untouched. Shards that are not the recorded
encode's full size, a .dat of the recorded size, and a .vif without a
recorded size keep the existing rule, so an interrupted encode is still
reclaimed, including a re-encode whose .vif is still the previous
encode's (the encode writes the .vif after the shards).
2026-12-05 23:45:47 -08:00
10 changed files with 1010 additions and 689 deletions

No files matched your search

+509 -32
View File
@@ -487,32 +487,36 @@ impl DiskLocation {
let base = volume_file_name(&self.directory, collection, vid);
let dat_path = format!("{}.dat", base);
// 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(
// 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(
&self.directory,
&self.idx_directory,
&self.store_dirs,
collection,
vid,
);
if data_shards == 0 {
) else {
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 => {
expected_shard_size = Some(calculate_expected_shard_size(
meta.len() as i64,
data_shards,
));
dat_size = meta.len() as i64;
expected_shard_size = Some(calculate_expected_shard_size(dat_size, data_shards));
true
}
Ok(_) => false,
@@ -569,6 +573,33 @@ 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
{
@@ -583,6 +614,36 @@ 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
@@ -1464,9 +1525,6 @@ 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.
@@ -1477,26 +1535,47 @@ fn rm_if_present(path: String) -> io::Result<()> {
}
}
fn ec_data_shards_from_vif(
/// 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(
directory: &str,
idx_directory: &str,
store_dirs: &[String],
collection: &str,
vid: VolumeId,
) -> usize {
) -> 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;
for dir in [directory, idx_directory] {
let vif = format!("{}.vif", volume_file_name(dir, collection, vid));
if let Some(ds) = fs::read_to_string(&vif)
if let Some(vi) = 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
{
return ds;
if has_ec_config(&vi) {
return Ok(Some(vi));
}
fallback.get_or_insert(vi);
}
if directory == idx_directory {
break;
return Ok(fallback);
}
}
match crate::storage::erasure_coding::ec_volume::sibling_ec_config_vif(
@@ -1505,18 +1584,10 @@ fn ec_data_shards_from_vif(
store_dirs,
collection,
vid,
) {
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) => {}
)? {
Some(vi) if has_ec_config(&vi) => Ok(Some(vi)),
_ => Ok(fallback),
}
DATA_SHARDS_COUNT
}
/// Parse a volume filename like "collection_42.dat" or "42.dat" into (collection, VolumeId).
@@ -1878,6 +1949,412 @@ 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,28 +48,30 @@ pub fn find_dat_file_size_with_dirs(
ec00.read_exact(&mut sb_buf)?;
let version = Version(sb_buf[0]);
// Start with at least the superblock size
let mut dat_size: i64 = SUPER_BLOCK_SIZE as i64;
// At least the superblock size
let extent = ecx_needle_extent(&format!("{}.ecx", ecx_base), version, deleted)?;
Ok(extent.max(SUPER_BLOCK_SIZE as i64))
}
// 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]);
/// 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);
if size.is_deleted() || deleted.contains(&key) {
continue;
}
let entry_stop = offset.to_actual_offset() + get_actual_size(size, version);
if entry_stop > dat_size {
dat_size = entry_stop;
}
extent = extent.max(offset.to_actual_offset() + get_actual_size(size, version));
}
Ok(dat_size)
Ok(extent)
}
/// Whether the `.ecx` in `ecx_dir` indexes a needle deleted neither there nor
+1 -1
View File
@@ -532,7 +532,7 @@ func (ms *MasterServer) VolumeMarkReadonly(ctx context.Context, req *master_pb.V
glog.V(0).Infof("volume %d marked readonly with %d pending bytes", vid, pending)
}
} else {
ms.Topo.SetVolumeWritable(vl, dn, vid)
vl.SetVolumeWritable(dn, vid)
}
}
}
+82 -40
View File
@@ -1,7 +1,9 @@
package storage
import (
"errors"
"fmt"
"io"
"os"
"path"
"regexp"
@@ -12,6 +14,7 @@ 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"
@@ -657,22 +660,27 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
baseFileName := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
datFileName := baseFileName + ".dat"
// 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 {
// 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 {
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 expectedShardSize int64 = -1
var datSize, expectedShardSize int64 = -1, -1
datExists := false
if datFileInfo, err := os.Stat(datFileName); err == nil {
if datFileInfo.Size() > int64(super_block.SuperBlockSize) {
datExists = true
expectedShardSize = calculateExpectedShardSize(datFileInfo.Size(), dataShards)
datSize = datFileInfo.Size()
expectedShardSize = calculateExpectedShardSize(datSize, dataShards)
}
} else if !os.IsNotExist(err) {
glog.Warningf("EC volume %d: cannot stat .dat %s (%v); keeping EC shards", vid, datFileName, err)
@@ -712,6 +720,20 @@ 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)
@@ -720,52 +742,72 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
return true
}
// 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.
// 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
}
if l.Directory != "" {
if ds := ecDataShardsFromVifDir(collection, l.Directory, vid); ds > 0 {
return ds
if vi := load(erasure_coding.EcShardFileName(collection, l.Directory, int(vid)) + ".vif"); vi != nil {
return vi, false
}
}
if l.IdxDirectory != "" && l.IdxDirectory != l.Directory {
if ds := ecDataShardsFromVifDir(collection, l.IdxDirectory, vid); ds > 0 {
return ds
if vi := load(erasure_coding.EcShardFileName(collection, l.IdxDirectory, int(vid)) + ".vif"); vi != nil {
return vi, false
}
vif, ambiguous := erasure_coding.SiblingEcConfigVif(collection, vid, l.Directory, l.IdxDirectory, l.storeDirs)
if ambiguous {
return 0
return nil, true
}
if vif != "" {
if ds := ecDataShardsFromVifPath(vif); ds > 0 {
return ds
if vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vif); found && vi.GetEcShardConfig().GetDataShards() > 0 {
return vi, 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
return fallback, false
}
// removeEcVolumeFiles removes all EC-related files for a volume
@@ -5,8 +5,13 @@ 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) {
@@ -101,3 +106,331 @@ 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")
}
}
+12 -7
View File
@@ -109,20 +109,25 @@ func FindDatFileSize(shard0FileName, indexBaseFileName string) (datSize int64, e
// when all needles are deleted (see issue #7748).
datSize = int64(super_block.SuperBlockSize)
err = iterateEcxFile(indexBaseFileName, func(key types.NeedleId, offset types.Offset, size types.Size) error {
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
}
entryStopOffset := offset.ToActualOffset() + needle.GetActualSize(size, version)
if datSize < entryStopOffset {
datSize = entryStopOffset
if end := offset.ToActualOffset() + needle.GetActualSize(size, version); end > extent {
extent = end
}
return nil
})
return
}
-423
View File
@@ -2,7 +2,6 @@ package topology
import (
"errors"
"sync"
"sync/atomic"
"testing"
"time"
@@ -11,7 +10,6 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
@@ -427,424 +425,3 @@ func TestFailedWritablePushRetriedOnNextReport(t *testing.T) {
return !topo.isQuarantined(dn1, v1.Id) && isWritable(t, topo, v1) && writablePushes.Load() >= 2
}, 5*time.Second, time.Millisecond, "the next volume report must retry the release and its writable push")
}
type quarantinePush struct {
dn NodeId
readOnly bool
}
type quarantinePushRecorder struct {
mu sync.Mutex
pushes []quarantinePush
}
func (r *quarantinePushRecorder) push(dn *DataNode, _ needle.VolumeId, readOnly bool) error {
r.mu.Lock()
defer r.mu.Unlock()
r.pushes = append(r.pushes, quarantinePush{dn.Id(), readOnly})
return nil
}
func (r *quarantinePushRecorder) to(dn *DataNode) []bool {
r.mu.Lock()
defer r.mu.Unlock()
var marks []bool
for _, p := range r.pushes {
if p.dn == dn.Id() {
marks = append(marks, p.readOnly)
}
}
return marks
}
func TestQuarantineLeavesReadOnlyCopyUnpushed(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
rp, _ := super_block.NewReplicaPlacementFromString("000")
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1 := NewDataNode("server1")
dn2 := NewDataNode("server2")
v1 := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, ReadOnly: true}
v2 := storage.VolumeInfo{Id: 7, Collection: "b", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
dn1.UpdateVolumes([]storage.VolumeInfo{v1})
dn2.UpdateVolumes([]storage.VolumeInfo{v2})
topo.GetVolumeLayout(v1.Collection, v1.ReplicaPlacement, v1.Ttl, types.ToDiskType(v1.DiskType)).RegisterVolume(&v1, dn1, nil)
topo.GetVolumeLayout(v2.Collection, v2.ReplicaPlacement, v2.Ttl, types.ToDiskType(v2.DiskType)).RegisterVolume(&v2, dn2, nil)
topo.flagDuplicateVolumeId(v2, dn2)
// the mark still takes deletes, so pushing it onto a copy its server
// already holds read-only could only relax that copy
require.Empty(t, recorder.to(dn1), "a copy already read-only must not be pushed")
require.Equal(t, []bool{true}, recorder.to(dn2))
topo.UnRegisterVolumeLayout(v2, dn2)
require.False(t, topo.isQuarantined(dn1, v1.Id))
require.Empty(t, recorder.to(dn1), "the release must not open a copy the master never marked")
require.False(t, isWritable(t, topo, v1), "the survivor keeps its own read-only state")
}
func TestQuarantineReleaseFollowsWritableReportAfterMark(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
rp, _ := super_block.NewReplicaPlacementFromString("000")
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1 := NewDataNode("server1")
dn2 := NewDataNode("server2")
v1 := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, ReadOnly: true, Version: needle.Version3}
v2 := storage.VolumeInfo{Id: 7, Collection: "b", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
dn1.UpdateVolumes([]storage.VolumeInfo{v1})
dn2.UpdateVolumes([]storage.VolumeInfo{v2})
topo.GetVolumeLayout(v1.Collection, v1.ReplicaPlacement, v1.Ttl, types.ToDiskType(v1.DiskType)).RegisterVolume(&v1, dn1, nil)
topo.GetVolumeLayout(v2.Collection, v2.ReplicaPlacement, v2.Ttl, types.ToDiskType(v2.DiskType)).RegisterVolume(&v2, dn2, nil)
topo.flagDuplicateVolumeId(v2, dn2)
// whoever froze the copy reopens it while the conflict stands: the
// master marks it again, and the reopening is what a release restores
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{{
Id: 7, Collection: "a", ReplicaPlacement: 0, Version: uint32(needle.Version3),
}}, dn1)
topo.duplicateFlagChecks.Wait()
require.Equal(t, []bool{true}, recorder.to(dn1))
require.False(t, isWritable(t, topo, v1), "the writable report must not lift the quarantine")
topo.UnRegisterVolumeLayout(v2, dn2)
require.False(t, topo.isQuarantined(dn1, v1.Id))
require.Equal(t, []bool{true, false}, recorder.to(dn1))
require.True(t, isWritable(t, topo, v1), "the release must restore the state the server last chose")
}
func TestQuarantineReleaseKeepsStricterMarkAfterMark(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
rp, _ := super_block.NewReplicaPlacementFromString("000")
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1 := NewDataNode("server1")
dn2 := NewDataNode("server2")
v1 := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
v2 := storage.VolumeInfo{Id: 7, Collection: "b", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}
dn1.UpdateVolumes([]storage.VolumeInfo{v1})
dn2.UpdateVolumes([]storage.VolumeInfo{v2})
topo.GetVolumeLayout(v1.Collection, v1.ReplicaPlacement, v1.Ttl, types.ToDiskType(v1.DiskType)).RegisterVolume(&v1, dn1, nil)
topo.GetVolumeLayout(v2.Collection, v2.ReplicaPlacement, v2.Ttl, types.ToDiskType(v2.DiskType)).RegisterVolume(&v2, dn2, nil)
topo.flagDuplicateVolumeId(v2, dn2)
require.Equal(t, []bool{true}, recorder.to(dn1))
// the mark lands, then something freezes the copy so it refuses deletes
// too; that is no longer the master's mark, and a release must keep it
for _, canDelete := range []bool{true, false} {
topo.ApplyVolumeChanges([]*master_pb.VolumeInformationMessage{{
Id: 7, Collection: "a", Version: uint32(needle.Version3), ReadOnly: true, ReadOnlyCanDelete: canDelete,
}}, dn1)
}
topo.duplicateFlagChecks.Wait()
topo.UnRegisterVolumeLayout(v2, dn2)
require.False(t, topo.isQuarantined(dn1, v1.Id))
require.Equal(t, []bool{true}, recorder.to(dn1), "the release must not reopen a copy frozen by someone else")
require.False(t, isWritable(t, topo, v1))
}
func mountEcShards(topo *Topology, dn *DataNode, vid uint32, shardIds ...erasure_coding.ShardId) {
msg := buildEcShardMessage(vid, "a", "", 0, shardIds)
topo.IncrementalSyncDataNodeEcShards([]*master_pb.VolumeEcShardInformationMessage{msg}, nil, dn)
}
func deleteEcShards(topo *Topology, dn *DataNode, vid uint32, shardIds ...erasure_coding.ShardId) {
msg := buildEcShardMessage(vid, "a", "", 0, shardIds)
topo.IncrementalSyncDataNodeEcShards(nil, []*master_pb.VolumeEcShardInformationMessage{msg}, dn)
}
// requireOnlyMarked checks that marks were pushed and none of them opened
// the copy; how many land depends on how many checks saw it.
func requireOnlyMarked(t *testing.T, marks []bool) {
t.Helper()
require.NotEmpty(t, marks)
require.NotContains(t, marks, false)
}
// requireReleasedLast checks the copy was marked and then opened once, last.
func requireReleasedLast(t *testing.T, marks []bool) {
t.Helper()
require.GreaterOrEqual(t, len(marks), 2)
requireOnlyMarked(t, marks[:len(marks)-1])
require.False(t, marks[len(marks)-1])
}
func reportVolume(topo *Topology, dn *DataNode, readOnly bool) {
topo.ApplyVolumeChanges([]*master_pb.VolumeInformationMessage{{
Id: 7, Collection: "a", Version: uint32(needle.Version3), ReadOnly: readOnly,
}}, dn)
}
func TestEcShardsQuarantineRegularCopy(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1, dn2, dn3 := NewDataNode("server1"), NewDataNode("server2"), NewDataNode("server3")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
reportVolume(topo, dn1, false)
topo.duplicateFlagChecks.Wait()
require.True(t, isWritable(t, topo, v))
mountEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6)
mountEcShards(topo, dn3, 7, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
require.False(t, isWritable(t, topo, v), "a regular copy must leave the writables once its id has EC shards")
require.True(t, topo.isQuarantined(dn1, v.Id))
requireOnlyMarked(t, recorder.to(dn1))
require.Empty(t, recorder.to(dn2), "shard holders are not regular volumes")
require.Empty(t, recorder.to(dn3), "shard holders are not regular volumes")
}
func TestEcShardsKeepLateRegularCopyOutOfWritables(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1, dn2 := NewDataNode("server1"), NewDataNode("server2")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
mountEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
// a stale copy of the source comes back with its server, writable
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{{
Id: 7, Collection: "a", Version: uint32(needle.Version3),
}}, dn1)
require.False(t, isWritable(t, topo, v), "the copy must be read-only from the moment it registers")
topo.duplicateFlagChecks.Wait()
require.False(t, isWritable(t, topo, v))
require.True(t, topo.isQuarantined(dn1, v.Id))
requireOnlyMarked(t, recorder.to(dn1))
}
func TestEcShardsQuarantineSurvivesVacuumReopen(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1, dn2 := NewDataNode("server1"), NewDataNode("server2")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
reportVolume(topo, dn1, false)
mountEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
marked := len(recorder.to(dn1))
requireOnlyMarked(t, recorder.to(dn1))
// the mark lands, then a compaction ends by marking the copy writable
reportVolume(topo, dn1, true)
reportVolume(topo, dn1, false)
topo.duplicateFlagChecks.Wait()
require.False(t, isWritable(t, topo, v), "a reopened copy must stay out of the writables while the shards exist")
require.Greater(t, len(recorder.to(dn1)), marked, "the reopened copy must be marked again")
requireOnlyMarked(t, recorder.to(dn1))
// a full heartbeat repeating the writable flag does not lift it either
topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{{
Id: 7, Collection: "a", Version: uint32(needle.Version3),
}}, dn1)
topo.duplicateFlagChecks.Wait()
require.False(t, isWritable(t, topo, v))
}
func TestEcShardsGoneReleasesDecodedVolume(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1, dn2 := NewDataNode("server1"), NewDataNode("server2")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
mountEcShards(topo, dn1, 7, 0, 1, 2, 3, 4, 5, 6)
mountEcShards(topo, dn2, 7, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
// the decode collects the data shards on dn1, generates the volume there
// and mounts it, then deletes every shard
reportVolume(topo, dn1, false)
topo.duplicateFlagChecks.Wait()
require.False(t, isWritable(t, topo, v), "the decoded volume stays read-only while shards remain")
deleteEcShards(topo, dn2, 7, 7, 8, 9, 10, 11, 12, 13)
require.False(t, isWritable(t, topo, v), "some shards still remain")
require.True(t, topo.isQuarantined(dn1, v.Id))
deleteEcShards(topo, dn1, 7, 0, 1, 2, 3, 4, 5, 6)
topo.duplicateFlagChecks.Wait()
require.False(t, topo.isQuarantined(dn1, v.Id))
require.True(t, isWritable(t, topo, v), "the decoded volume must end writable")
requireReleasedLast(t, recorder.to(dn1))
}
func TestEcEncodeSourceStaysReadOnlyUntilDeleted(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1, dn2, dn3 := NewDataNode("server1"), NewDataNode("server2"), NewDataNode("server3")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
reportVolume(topo, dn1, false)
topo.duplicateFlagChecks.Wait()
// the encode freezes the source, mounts the shards, then deletes the source
reportVolume(topo, dn1, true)
mountEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6)
mountEcShards(topo, dn3, 7, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
require.False(t, isWritable(t, topo, v))
require.Empty(t, recorder.to(dn1), "a frozen source needs no mark, which would let it take deletes")
topo.SyncDataNodeRegistration(nil, dn1)
topo.duplicateFlagChecks.Wait()
require.False(t, topo.isQuarantined(dn1, v.Id), "the record goes with the source")
require.Empty(t, recorder.to(dn1))
_, found := topo.FindCollection("a")
require.False(t, found, "no regular copy is left to write to")
require.NotEmpty(t, topo.Lookup("a", v.Id), "lookups resolve to the shard holders")
}
func TestEcEncodeRollbackRestoresWritableSource(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1, dn2 := NewDataNode("server1"), NewDataNode("server2")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
reportVolume(topo, dn1, false)
reportVolume(topo, dn1, true)
mountEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
// a failed encode tears the shards down and reopens the source; the
// reopening can reach the master first
reportVolume(topo, dn1, false)
require.False(t, isWritable(t, topo, v))
deleteEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
require.True(t, isWritable(t, topo, v), "a rolled back source must end writable")
requireReleasedLast(t, recorder.to(dn1))
}
func TestEcStaleShardsReleaseKeepsEncodeFreeze(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1, dn2 := NewDataNode("server1"), NewDataNode("server2")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
// shards left by an earlier failed encode mark the writable source
reportVolume(topo, dn1, false)
mountEcShards(topo, dn2, 7, 0, 1, 2)
topo.duplicateFlagChecks.Wait()
requireOnlyMarked(t, recorder.to(dn1))
// the next encode tears them down and freezes the source, and the master
// can learn of the freeze first
topo.ApplyVolumeChanges([]*master_pb.VolumeInformationMessage{{
Id: 7, Collection: "a", Version: uint32(needle.Version3), ReadOnly: true,
}}, dn1)
deleteEcShards(topo, dn2, 7, 0, 1, 2)
topo.duplicateFlagChecks.Wait()
require.False(t, topo.isQuarantined(dn1, v.Id))
require.False(t, isWritable(t, topo, v), "the release must not reopen a source an encode froze")
requireOnlyMarked(t, recorder.to(dn1))
}
func TestQuarantineSurvivesServerMarkingItWritable(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
dn1, dn2 := NewDataNode("server1"), NewDataNode("server2")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
reportVolume(topo, dn1, false)
mountEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
require.True(t, topo.isQuarantined(dn1, v.Id))
// a vacuum's commit ends with the server telling the master the copy is
// writable again, ahead of its next heartbeat
vl := topo.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, types.ToDiskType(v.DiskType))
topo.SetVolumeWritable(vl, dn1, v.Id)
require.False(t, isWritable(t, topo, v), "the server's word must not lift the quarantine")
// without a quarantine the same call reopens the copy
deleteEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
reportVolume(topo, dn1, true)
topo.SetVolumeWritable(vl, dn1, v.Id)
require.True(t, isWritable(t, topo, v))
}
func TestEcShardsQuarantineSurvivesReleaseBeforeRegistration(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
var released atomic.Bool
topo.QuarantineVolumeFn = func(dn *DataNode, vid needle.VolumeId, readOnly bool) error {
// a release pass for the id, finishing some other check, runs while
// the first mark is in flight
if readOnly && released.CompareAndSwap(false, true) {
topo.releaseResolvedQuarantine(vid)
}
return recorder.push(dn, vid, readOnly)
}
dn1, dn2 := NewDataNode("server1"), NewDataNode("server2")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
mountEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
reportVolume(topo, dn1, false)
topo.duplicateFlagChecks.Wait()
require.True(t, released.Load())
require.True(t, topo.isQuarantined(dn1, v.Id))
require.False(t, isWritable(t, topo, v), "the copy must stay quarantined")
requireOnlyMarked(t, recorder.to(dn1))
}
func TestEcShardsQuarantineSurvivesHolderDisconnect(t *testing.T) {
topo := NewTopology("topo", nil, 128, 3, false)
var recorder quarantinePushRecorder
topo.QuarantineVolumeFn = recorder.push
dn1, dn2 := NewDataNode("server1"), NewDataNode("server2")
rp, _ := super_block.NewReplicaPlacementFromString("000")
v := storage.VolumeInfo{Id: 7, Collection: "a", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL, Version: needle.Version3}
reportVolume(topo, dn1, false)
mountEcShards(topo, dn2, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
require.True(t, topo.isQuarantined(dn1, v.Id))
// the only shard holder drops out; its shards are still on its disks
topo.UnRegisterDataNode(dn2)
topo.duplicateFlagChecks.Wait()
require.True(t, topo.isQuarantined(dn1, v.Id), "a disconnect must not release the quarantine")
require.False(t, isWritable(t, topo, v))
requireOnlyMarked(t, recorder.to(dn1))
back := NewDataNode("server2")
mountEcShards(topo, back, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
require.False(t, isWritable(t, topo, v))
// only shards reported deleted end the conflict
deleteEcShards(topo, back, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
topo.duplicateFlagChecks.Wait()
require.False(t, topo.isQuarantined(dn1, v.Id))
require.True(t, isWritable(t, topo, v))
requireReleasedLast(t, recorder.to(dn1))
}
+46 -115
View File
@@ -139,9 +139,8 @@ type Topology struct {
growthFreezeApplyLock sync.Mutex
// quarantinedVolumeIds are (node, vid) pairs force-read-only because the
// vid collided across layouts or with EC shards of the same id. Kept
// separate from the reported flag so later heartbeats from the same
// server cannot quietly undo it.
// vid collided across layouts. Kept separate from the reported flag so
// later heartbeats from the same server cannot quietly undo it.
quarantinedVolumeIds sync.Map
// quarantineLock serializes each quarantine record update with the layout
// mark it justifies: a release pass and a heartbeat read-only flag update
@@ -317,25 +316,19 @@ func (t *Topology) enforceQuarantine(dn *DataNode, vi storage.VolumeInfo) storag
return vi
}
state := v.(quarantinedVolumeState)
// Once the mark lands a report that reads like it, read-only but taking
// deletes, may be the mark itself. Any other report is the server's own:
// writable after a restart, volume.mark or a vacuum reopening the copy,
// or frozen harder by a mark that refuses deletes too.
if !state.enforced || !vi.ReadOnly || !vi.ReadOnlyCanDelete {
if !state.enforced {
state.reported = vi.ReadOnly
}
// A copy its server already holds read-only takes no writes, and the
// mark, which still takes deletes, would relax a stricter one.
if t.QuarantineVolumeFn == nil || vi.ReadOnly {
if t.QuarantineVolumeFn == nil || (state.enforced && vi.ReadOnly) {
t.quarantinedVolumeIds.Store(q, state)
t.quarantineLock.Unlock()
return vi
}
t.quarantineLock.Unlock()
// The server holds the copy writable: the mark never landed, or the
// server lost it (restart, manual unquarantine); push it while the
// conflict stands. The call is remote, so it runs outside the lock.
// The mark never landed on the server, or the server lost it (restart,
// manual unquarantine); push it while the conflict stands. The call is
// remote, so it runs outside the lock.
pushed, err := t.pushQuarantine(dn, vi.Id, true)
if pushed && err == nil {
state.enforced = true
@@ -344,14 +337,16 @@ func (t *Topology) enforceQuarantine(dn *DataNode, vi storage.VolumeInfo) storag
cur, still := t.quarantinedVolumeIds.Load(q)
if still {
latest := cur.(quarantinedVolumeState)
latest.reported = false
if !latest.enforced {
latest.reported = state.reported
}
latest.enforced = latest.enforced || state.enforced
t.quarantinedVolumeIds.Store(q, latest)
t.quarantineLock.Unlock()
return vi
}
t.quarantineLock.Unlock()
if state.enforced {
if state.enforced && !state.reported {
// The conflict resolved while the push was in flight; leave the
// server consistent with the released layout.
t.releaseQuarantineWritable(dn, vi.Id)
@@ -359,20 +354,6 @@ func (t *Topology) enforceQuarantine(dn *DataNode, vi storage.VolumeInfo) storag
return vi
}
// SetVolumeWritable applies a volume server's own word that its copy of vid
// takes writes again, as a vacuum sends after its commit. A quarantined copy
// keeps its layout mark; the heartbeat that repeats the flag marks the server
// again.
func (t *Topology) SetVolumeWritable(vl *VolumeLayout, dn *DataNode, vid needle.VolumeId) {
t.quarantineLock.Lock()
defer t.quarantineLock.Unlock()
if t.isQuarantined(dn, vid) {
dn.SetVolumeReadOnly(vid, false)
return
}
vl.SetVolumeWritable(dn, vid)
}
func NewTopology(id string, seq sequence.Sequencer, volumeSizeLimit uint64, pulse int, replicationAsMin bool) *Topology {
t := &Topology{}
t.id = NodeId(id)
@@ -1073,7 +1054,15 @@ func (t *Topology) RegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
diskType := types.ToDiskType(v.DiskType)
for {
vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl, diskType)
if t.registerVolume(vl, &v, dn) {
// RegisterVolume reads the quarantine record and marks under
// accessLock; holding quarantineLock keeps that pair serialized with
// releaseResolvedQuarantine's clear-and-delete.
t.quarantineLock.Lock()
registered := vl.RegisterVolume(&v, dn, func(n *DataNode) bool {
return t.isQuarantined(n, v.Id)
})
t.quarantineLock.Unlock()
if registered {
// RegisterVolume rebuilds only the read-only flags, so a
// location list recreated flagless would pass the writable
// check before the next heartbeat re-measures the volume.
@@ -1090,32 +1079,6 @@ func (t *Topology) RegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
}
}
// registerVolume records dn's copy of v in vl with the quarantine marks folded
// in. A copy registering beside EC shards of its id is quarantined in the
// same step, so it never reaches the writable list and no release pass can
// see its record before the copy is in a layout.
func (t *Topology) registerVolume(vl *VolumeLayout, v *storage.VolumeInfo, dn *DataNode) bool {
ecCollection, conflict := "", false
// RegisterVolume reads the quarantine record and marks under accessLock;
// holding quarantineLock keeps that pair serialized with
// releaseResolvedQuarantine's clear-and-delete.
t.quarantineLock.Lock()
if !t.isQuarantined(dn, v.Id) {
if collection, held := t.ecShardsHeld(v.Id); held {
t.quarantinedVolumeIds.Store(quarantinedVolume{dn.Id(), v.Id}, quarantinedVolumeState{reported: v.ReadOnly})
ecCollection, conflict = collection, true
}
}
registered := vl.RegisterVolume(v, dn, func(n *DataNode) bool {
return t.isQuarantined(n, v.Id)
})
t.quarantineLock.Unlock()
if conflict {
logEcShardConflict(*v, dn, ecCollection)
}
return registered
}
func (t *Topology) flagDuplicateVolumeIdAsync(v storage.VolumeInfo, dn *DataNode) {
t.duplicateFlagChecks.Add(1)
go func() {
@@ -1124,26 +1087,12 @@ func (t *Topology) flagDuplicateVolumeIdAsync(v storage.VolumeInfo, dn *DataNode
}()
}
// flagRegularCopiesAsync runs the duplicate check for every regular copy of
// vid, for a conflicting holder that registers outside the volume layouts.
func (t *Topology) flagRegularCopiesAsync(vid needle.VolumeId) {
for _, item := range t.collectionMap.Items() {
for _, vl := range item.(*Collection).GetAllVolumeLayouts() {
for _, n := range vl.Lookup(vid) {
if vi, err := n.GetVolumesById(vid); err == nil {
t.flagDuplicateVolumeIdAsync(vi, n)
}
}
}
}
}
// flagDuplicateVolumeId reports and quarantines v.Id when another data node
// already serves it under a different layout key or as EC shards. It runs
// after registration so a legitimate same-node move (disk type or collection
// change) settles first and does not trip it. Every regular copy across the
// conflicting layouts is quarantined: either could be the impostor, and
// arrival order must not decide which copy stays writable.
// already serves it under a different layout key. It runs after registration
// so a legitimate same-node move (disk type or collection change) settles
// first and does not trip it. Every copy across the conflicting layouts is
// quarantined: either could be the impostor, and arrival order must not
// decide which copy stays writable.
func (t *Topology) flagDuplicateVolumeId(v storage.VolumeInfo, dn *DataNode) {
// Every pass ends with a release: a conflict could resolve between the
// scan below and the marks, and a check finding no hits is also the retry
@@ -1161,15 +1110,12 @@ func (t *Topology) flagDuplicateVolumeId(v storage.VolumeInfo, dn *DataNode) {
if own == nil || !own.HasDataNode(v.Id, dn) {
return
}
ecOnly := len(hits) == 1 && hits[0].vl == nil
if !ecOnly {
stats.MasterDuplicateVolumeIds.WithLabelValues(v.Collection, v.Id.String()).Inc()
var otherKeys []string
for _, h := range hits {
otherKeys = append(otherKeys, h.layoutKey())
}
glog.Errorf("duplicate volume id %d: %s reports it under %s but other data nodes also serve it under %s; marking all copies read-only", v.Id, dn.Id(), volumeLayoutKey(v.Collection, v.ReplicaPlacement, v.Ttl, types.ToDiskType(v.DiskType)), strings.Join(otherKeys, ", "))
stats.MasterDuplicateVolumeIds.WithLabelValues(v.Collection, v.Id.String()).Inc()
var otherKeys []string
for _, h := range hits {
otherKeys = append(otherKeys, h.layoutKey())
}
glog.Errorf("duplicate volume id %d: %s reports it under %s but other data nodes also serve it under %s; marking all copies read-only", v.Id, dn.Id(), volumeLayoutKey(v.Collection, v.ReplicaPlacement, v.Ttl, types.ToDiskType(v.DiskType)), strings.Join(otherKeys, ", "))
quarantine := func(n *DataNode, vl *VolumeLayout) {
q := quarantinedVolume{n.Id(), v.Id}
reported := false
@@ -1177,17 +1123,12 @@ func (t *Topology) flagDuplicateVolumeId(v storage.VolumeInfo, dn *DataNode) {
reported = vi.ReadOnly
}
t.quarantineLock.Lock()
_, loaded := t.quarantinedVolumeIds.LoadOrStore(q, quarantinedVolumeState{reported: reported})
t.quarantinedVolumeIds.LoadOrStore(q, quarantinedVolumeState{reported: reported})
if vl != nil {
vl.SetVolumeQuarantined(n, v.Id)
}
t.quarantineLock.Unlock()
// every shard registration rechecks; report the record's creation only
if ecOnly && !loaded {
logEcShardConflict(v, n, hits[0].collection)
}
if t.QuarantineVolumeFn == nil || reported {
// enforceQuarantine pushes once the server reports it writable
if t.QuarantineVolumeFn == nil {
return
}
pushed, err := t.pushQuarantine(n, v.Id, true)
@@ -1218,17 +1159,6 @@ func (t *Topology) flagDuplicateVolumeId(v storage.VolumeInfo, dn *DataNode) {
}
}
// logEcShardConflict reports a regular copy newly quarantined beside EC shards
// of its id. Only a writable copy could have taken writes the shards lack; a
// read-only one is what an encode holds until it deletes its source.
func logEcShardConflict(v storage.VolumeInfo, dn *DataNode, ecCollection string) {
if v.ReadOnly {
glog.V(1).Infof("volume id %d: %s holds a read-only regular copy in collection %q beside EC shards in collection %q; keeping it read-only", v.Id, dn.Id(), v.Collection, ecCollection)
return
}
glog.Warningf("volume id %d: %s reports a writable regular copy in collection %q beside EC shards in collection %q; marking it read-only", v.Id, dn.Id(), v.Collection, ecCollection)
}
// releaseResolvedQuarantine lifts read-only marks once the conflicting copy
// is gone, so a finished move does not leave the surviving copy quarantined.
// The writable push is a remote call, so the locked pass only applies the
@@ -1314,8 +1244,7 @@ func (t *Topology) findQuarantinedVolume(dnId NodeId, vid needle.VolumeId) (*Dat
}
// duplicateHit is one layout that holds v.Id on data nodes other than the
// reporter's, or, with no layout, the EC shards of v.Id. Shard holders are
// not regular volumes, so that hit names no nodes to mark.
// reporter's.
type duplicateHit struct {
collection string
vl *VolumeLayout
@@ -1323,9 +1252,6 @@ type duplicateHit struct {
}
func (h duplicateHit) layoutKey() string {
if h.vl == nil {
return fmt.Sprintf("ec shards collection=%q", h.collection)
}
return volumeLayoutKey(h.collection, h.vl.rp, h.vl.ttl, h.vl.diskType)
}
@@ -1339,9 +1265,7 @@ func ttlEqual(a, b *needle.TTL) bool {
// findDuplicateVolumeLayouts reports every layout that already holds v.Id on
// data nodes other than dn. Volume ids are global, so the same id held by two
// nodes under two layouts means the allocator reused an id. EC shards of v.Id
// conflict too: a read resolves to whichever holder the lookup prefers, and
// the shards never see what the regular copy took.
// nodes under two layouts means the allocator reused an id.
func (t *Topology) findDuplicateVolumeLayouts(v storage.VolumeInfo, dn *DataNode) []duplicateHit {
if v.ReplicaPlacement == nil {
return nil
@@ -1369,9 +1293,6 @@ func (t *Topology) findDuplicateVolumeLayouts(v storage.VolumeInfo, dn *DataNode
}
}
}
if collection, held := t.ecShardsHeld(v.Id); held {
hits = append(hits, duplicateHit{collection: collection})
}
return hits
}
@@ -1631,7 +1552,12 @@ func (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformati
// LookupVolume returns "volume id not found".
if !vl.HasDataNode(v.Id, dn) {
for {
if t.registerVolume(vl, &v, dn) {
t.quarantineLock.Lock()
registered := vl.RegisterVolume(&v, dn, func(n *DataNode) bool {
return t.isQuarantined(n, v.Id)
})
t.quarantineLock.Unlock()
if registered {
break
}
// Dropped with its collection; the next lookup creates a fresh
@@ -1740,7 +1666,12 @@ func (t *Topology) ApplyVolumeChanges(changed []*master_pb.VolumeInformationMess
// concerned: they were told it went when the node dropped out.
becameServable := !vl.HasDataNode(vi.Id, dn)
for becameServable {
if t.registerVolume(vl, &vi, dn) {
t.quarantineLock.Lock()
registered := vl.RegisterVolume(&vi, dn, func(n *DataNode) bool {
return t.isQuarantined(n, vi.Id)
})
t.quarantineLock.Unlock()
if registered {
break
}
// Dropped with its collection; the next lookup creates a fresh one.
+6 -51
View File
@@ -137,6 +137,8 @@ func (t *Topology) RegisterEcShards(ecvi *erasure_coding.EcVolumeInfo, dn *DataN
t.UpAdjustMaxVolumeId(ecvi.VolumeId)
t.ecShardMapLock.Lock()
defer t.ecShardMapLock.Unlock()
locations, found := t.ecShardMap[ecvi.VolumeId]
if !found {
locations = NewEcShardLocations(ecvi.Collection)
@@ -145,28 +147,15 @@ func (t *Topology) RegisterEcShards(ecvi *erasure_coding.EcVolumeInfo, dn *DataN
for _, shardId := range ecvi.ShardsInfo.Ids() {
locations.AddShard(shardId, dn)
}
t.ecShardMapLock.Unlock()
// a regular copy registered before the shards must not stay writable
// beside them
t.flagRegularCopiesAsync(ecvi.VolumeId)
}
// UnRegisterEcShards drops shards dn reported deleted.
func (t *Topology) UnRegisterEcShards(ecvi *erasure_coding.EcVolumeInfo, dn *DataNode) {
t.unregisterEcShards(ecvi, dn, true)
}
// unregisterEcShards drops dn's shards of ecvi from the lookup. Once a
// volume's last shards are reported deleted its entry goes, and with it the
// conflict that quarantines regular copies of the id. A node that only went
// away may come back with its shards, so its last shards leave the entry.
func (t *Topology) unregisterEcShards(ecvi *erasure_coding.EcVolumeInfo, dn *DataNode, reportedDeleted bool) {
glog.Infof("removing ec shard info:%+v", ecvi)
t.ecShardMapLock.Lock()
defer t.ecShardMapLock.Unlock()
locations, found := t.ecShardMap[ecvi.VolumeId]
if !found {
t.ecShardMapLock.Unlock()
return
}
for _, shardId := range ecvi.ShardsInfo.Ids() {
@@ -175,37 +164,6 @@ func (t *Topology) unregisterEcShards(ecvi *erasure_coding.EcVolumeInfo, dn *Dat
}
locations.DeleteShard(shardId, dn)
}
gone := reportedDeleted && !locations.hasShards()
if gone {
delete(t.ecShardMap, ecvi.VolumeId)
}
t.ecShardMapLock.Unlock()
if gone {
// the regular copy a decode left behind is no longer in conflict
t.releaseResolvedQuarantine(ecvi.VolumeId)
}
}
func (loc *EcShardLocations) hasShards() bool {
for _, nodes := range loc.Locations {
if len(nodes) > 0 {
return true
}
}
return false
}
// ecShardsHeld reports whether vid has EC shards, as far as the master knows,
// and under which collection: some node holds them, or their holders went
// away without reporting them deleted.
func (t *Topology) ecShardsHeld(vid needle.VolumeId) (collection string, held bool) {
t.ecShardMapLock.RLock()
defer t.ecShardMapLock.RUnlock()
if locations, found := t.ecShardMap[vid]; found {
return locations.Collection, true
}
return "", false
}
func (t *Topology) LookupEcShards(vid needle.VolumeId) (locations *EcShardLocations, found bool) {
@@ -311,6 +269,8 @@ func (t *Topology) ListEcServersByCollection(collection string) (dataNodes []pb.
func (t *Topology) DeleteEcCollection(collection string) {
t.ecShardMapLock.Lock()
defer t.ecShardMapLock.Unlock()
var vids []needle.VolumeId
for vid, ecVolumeLocation := range t.ecShardMap {
if ecVolumeLocation.Collection == collection {
@@ -321,9 +281,4 @@ func (t *Topology) DeleteEcCollection(collection string) {
for _, vid := range vids {
delete(t.ecShardMap, vid)
}
t.ecShardMapLock.Unlock()
for _, vid := range vids {
t.releaseResolvedQuarantine(vid)
}
}
+2 -3
View File
@@ -126,13 +126,12 @@ func (t *Topology) UnRegisterDataNode(dn *DataNode) {
// unregister ec shards when volume server disconnected. The node's own
// records clear first so the still-held check cannot skip the drop, and
// each unregister gets a copy — DeleteEcShard drains the shared
// ShardsInfo. The shards may come back with the node, so regular copies
// of their ids stay quarantined.
// ShardsInfo.
for _, s := range dn.GetEcShards() {
held := *s
held.ShardsInfo = s.ShardsInfo.Copy()
dn.DeleteEcShard(s)
t.unregisterEcShards(&held, dn, false)
t.UnRegisterEcShards(&held, dn)
}
negativeUsages := dn.GetDiskUsages().negative()