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
5 changed files with 955 additions and 96 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
+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
}