Compare commits

..
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 2647a88994 shell: fs.verify tests a missing replica beside a healthy one and chunk timestamps
The replica case registered the same healthy server twice, and the restored
chunk fixtures had no modification time to lose, with expected chunks built
by the helper under test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:37:59 -08:00
Chris LuandClaude Opus 5.5 6584bb4d54 shell: fs.verify -restoreFrom checks the chunks after one on an unknown volume
The scan of an entry stopped at the first chunk whose volume the cluster does
not know, so a later lost chunk the restore source holds was never restored.
Without -restoreFrom the scan still stops there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:37:13 -08:00
Chris LuandClaude Opus 5.5 af6b23f32d shell: fs.verify -restoreFrom skips an entry without a TTL under a TTL rule
The filer gives an entry and assigned needles without a TTL the path rule's,
so the restored entry kept its old creation time under a TTL it never had and
could expire on its next lookup, and the new needles went to TTL volumes. Such
an entry is now left as is and not pruned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:36:43 -08:00
Chris LuandClaude Opus 5.5 da19900464 shell: fs.verify -restoreFrom removes its uploads when the path turns read-only
A read-only refusal changes nothing, like a failed precondition, yet the new
needles were kept as if the update might have landed, and each later run
added more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:35:44 -08:00
Chris LuandClaude Opus 5.5 318d868ee8 shell: fs.verify -restoreFrom rewrites a manifest beside an unreadable nested one
A nested manifest that could not be read abandoned its parent's rewrite, so
the restored chunks the parent held directly were dropped. The unreadable
manifest now keeps its reference and the rest of the parent is rewritten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:35:15 -08:00
Chris LuandClaude Opus 5.5 3b9a7ceef8 shell: fs.verify -restoreFrom rewrites every manifest holding a restored needle
The manifests were only read when some restored needle was not a direct
chunk, so one referenced both directly and inside a manifest stayed lost
inside the manifest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:34:47 -08:00
Chris LuandClaude Opus 5.5 db13f03747 shell: fs.verify -restoreFrom holds one restored needle in memory at a time
Every checked needle of an entry was kept until the uploads, so a large file
with many lost chunks could exhaust memory. The check now drops the bytes and
each needle is read again just before its upload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:34:09 -08:00
Chris LuandClaude Opus 5.5 5e1671a4ad shell: fs.verify -restoreFrom reads its directory literally
The directory was used as a glob pattern, so a name with [, * or ? read
volume files from another directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:33:44 -08:00
Chris LuandClaude Opus 5.5 72ba251941 shell: fs.verify keeps an entry whose ETag it cannot check without MD5
Under fips140=only a 16-byte ETag may be an MD5 of intact content, so a
mismatch there no longer allows -pruneEntries to delete the entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:15:42 -08:00
Chris LuandClaude Opus 5.5 fd045baa4c shell: fs.verify treats a cut-short restore index as unreadable
A partial trailing record was skipped, so its key read as absent and
-pruneEntries could delete an entry the source still held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 01:15:28 -08:00
Chris LuandClaude Opus 5.5 4cc4180aa6 shell: fs.verify keeps an entry the restore source may still hold
With -restoreFrom and -pruneEntries, a missing needle the source could
not be read for (an unreadable .idx or a .dat read error), or held
intact but skipped (a cipher-key chunk, a volume-level manifest), let
the entry be pruned, deleting the file whose bytes were on hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 00:55:28 -08:00
Chris LuandClaude Opus 5.5 9d0c5ffe6a shell: fs.verify -restoreFrom loads a volume's index on its first lookup
Pointed at a data directory, the restore source read every .idx into
memory before verification began, though missing chunks usually name
few of those volumes, and one unreadable .idx stopped the whole run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 00:53:11 -08:00
Chris Lu cec02fbf0e shell: fs.verify finds a missing manifest under a readable one
A missing nested manifest failed the whole resolution, and the fallback then
checked only the entry's own chunks, so a healthy parent hid the lost child
from both pruning and -restoreFrom. The fallback now expands the manifests it
can read, cut to their spans, and verifies each unreadable one as a needle.
2026-12-06 00:41:05 -08:00
Chris Lu aa7d767827 shell: fs.verify -restoreFrom assigns restored needles with the entry's TTL
Without it the assignment took the path rule's TTL, so an entry with a longer
TTL of its own could outlive the restored needles.
2026-12-06 00:40:02 -08:00
Chris Lu 529ca9032e shell: fs.verify -restoreFrom recovers lost needles from leftover volume files
For a chunk whose needle is missing from every location, -restoreFrom reads
it from leftover regular volume files, checks it against the chunk (cookie,
CRC, size, MD5-sized ETag), uploads the stored bytes under a newly assigned
file id in their stored form, gzipped or not, and reads them back. The entry's
chunk is then repointed with offset, size, ETag and flags kept. All restorable
chunks of an entry go in one conditional replace that only lands while the
entry is unchanged since verification; a chunk held in a manifest is restored
by uploading a rewritten manifest. An entry with a restorable chunk is never
pruned.
2026-12-05 23:59:22 -08:00
Chris Lu 9da5893425 shell: read needles from leftover volume files for fs.verify restores
A restore source opens <collection>_<vid>.dat/.idx or <vid>.dat/.idx files
read-only and maps each key to its last live .idx record. A later tombstone
does not hide an earlier record, since a filer may still reference the
needle. Reads check the record's key, the file id's cookie and the CRC.
2026-12-05 23:59:12 -08:00
12 changed files with 1797 additions and 1044 deletions

No files matched your search

+32 -509
View File
@@ -487,36 +487,32 @@ impl DiskLocation {
let base = volume_file_name(&self.directory, collection, vid);
let dat_path = format!("{}.dat", base);
// Custom ratio and source size come from the encode's own .vif; the
// server holds no cluster EC config in memory.
let Ok(encode_info) = ec_encode_vif(
// Custom ratio comes from the volume's own .vif; the server holds no
// cluster EC config in memory.
let data_shards = ec_data_shards_from_vif(
&self.directory,
&self.idx_directory,
&self.store_dirs,
collection,
vid,
) else {
);
if data_shards == 0 {
warn!(
volume_id = vid.0,
"sibling .vif files disagree on the encode; keeping EC shards"
);
return true;
};
let data_shards = encode_info
.as_ref()
.and_then(|vi| vi.ec_shard_config.as_ref())
.map(|c| c.data_shards as usize)
.filter(|&ds| ds > 0)
.unwrap_or(DATA_SHARDS_COUNT);
}
// On-disk .dat: an empty <= superblock one is a stub; a transient stat
// error keeps the shards rather than deleting.
let mut dat_size: i64 = -1;
let mut expected_shard_size: Option<i64> = None;
let dat_exists = match fs::metadata(&dat_path) {
Ok(meta) if meta.len() > SUPER_BLOCK_SIZE as u64 => {
dat_size = meta.len() as i64;
expected_shard_size = Some(calculate_expected_shard_size(dat_size, data_shards));
expected_shard_size = Some(calculate_expected_shard_size(
meta.len() as i64,
data_shards,
));
true
}
Ok(_) => false,
@@ -573,33 +569,6 @@ impl DiskLocation {
if shard_count == 0 {
return false;
}
// Shards that are exactly the full encode of the source size the .vif
// records, under an .ecx indexing nothing past that size, were made
// from that source. A .dat of any other size is not it (e.g. a replica
// that kept taking writes), so its size says nothing about these
// shards: keep them, and leave the .dat unloaded so it cannot collide
// with the EC volume. The .ecx check catches a re-encode interrupted
// under an earlier encode's .vif: it writes the .ecx of the grown .dat
// before the shards.
let recorded = encode_info.as_ref().map_or(0, |vi| vi.dat_file_size);
if recorded > 0
&& dat_size != recorded
&& actual_shard_size == Some(calculate_expected_shard_size(recorded, data_shards))
&& !self.ecx_indexes_past(
collection,
vid,
encode_needle_version(&encode_info),
recorded,
)
{
warn!(
volume_id = vid.0,
dat_size,
recorded,
".dat size differs from the encode source size the .vif records; keeping the EC shards and leaving the .dat in place untouched"
);
return true;
}
if let (Some(actual), Some(expected)) = (actual_shard_size, expected_shard_size)
&& actual < expected
{
@@ -614,36 +583,6 @@ impl DiskLocation {
true
}
/// Whether the .ecx the mount would open for (collection, vid) -- the data
/// dir's when non-empty, else the idx dir's -- indexes a live needle
/// ending past `size`. A missing or unreadable file reports false: a
/// doubt keeps the shards. A torn tail is what an interrupted write
/// leaves, so the whole entries before it still count. Mirrors Go's
/// ecxIndexesPast.
fn ecx_indexes_past(
&self,
collection: &str,
vid: VolumeId,
version: Version,
size: i64,
) -> bool {
let mut ecx = format!("{}.ecx", volume_file_name(&self.directory, collection, vid));
if self.idx_directory != self.directory
&& !crate::storage::erasure_coding::ec_volume::is_usable_ecx_file(&ecx)
{
ecx = format!(
"{}.ecx",
volume_file_name(&self.idx_directory, collection, vid)
);
}
crate::storage::erasure_coding::ec_decoder::ecx_needle_extent(
&ecx,
version,
&HashSet::new(),
)
.is_ok_and(|extent| extent > size)
}
/// Remove all EC-related files for a volume.
/// `pub(crate)` so the Store-level cross-disk passes in
/// `store_ec_reconcile.rs` can call it to scrub partial EC artefacts
@@ -1525,6 +1464,9 @@ fn calculate_expected_shard_size(dat_file_size: i64, data_shards: usize) -> i64
shard_size
}
/// Resolve the EC data-shard count from the volume's own `.vif` (the volume
/// server never holds the cluster EC config in memory), checking the data dir
/// then the idx dir. Falls back to the default ratio when no EC `.vif` is found.
/// Remove a file, treating a missing file as success but propagating real errors
/// (permissions, disk full). Mirrors Go's removeFileIfExists so a teardown failure
/// surfaces instead of silently leaving stale artifacts.
@@ -1535,47 +1477,26 @@ fn rm_if_present(path: String) -> io::Result<()> {
}
}
/// The needle version the encode's `.vif` records, as the mount reads it,
/// defaulting to the current version when unset. Mirrors Go's
/// encodeNeedleVersion.
fn encode_needle_version(info: &Option<VifVolumeInfo>) -> Version {
match info.as_ref().map_or(0, |vi| vi.version) {
0 => Version::current(),
v => Version(v as u8),
}
}
/// The `.vif` describing the encode of an EC volume: the first with an EC
/// shard config in the data dir, the idx dir, then the sibling data dir the
/// mount takes it from under a shared idx dir. Without one it falls back to
/// the first `.vif` found in the data or idx dir. Err when sibling `.vif`
/// files disagree on the run. Mirrors Go's ecEncodeVolumeInfo.
fn ec_encode_vif(
fn ec_data_shards_from_vif(
directory: &str,
idx_directory: &str,
store_dirs: &[String],
collection: &str,
vid: VolumeId,
) -> Result<Option<VifVolumeInfo>, ()> {
let has_ec_config = |vi: &VifVolumeInfo| {
vi.ec_shard_config
.as_ref()
.is_some_and(|c| c.data_shards > 0)
};
let mut fallback: Option<VifVolumeInfo> = None;
) -> usize {
for dir in [directory, idx_directory] {
let vif = format!("{}.vif", volume_file_name(dir, collection, vid));
if let Some(vi) = fs::read_to_string(&vif)
if let Some(ds) = fs::read_to_string(&vif)
.ok()
.and_then(|s| serde_json::from_str::<VifVolumeInfo>(&s).ok())
.and_then(|vi| vi.ec_shard_config)
.map(|c| c.data_shards as usize)
&& ds > 0
{
if has_ec_config(&vi) {
return Ok(Some(vi));
}
fallback.get_or_insert(vi);
return ds;
}
if directory == idx_directory {
return Ok(fallback);
break;
}
}
match crate::storage::erasure_coding::ec_volume::sibling_ec_config_vif(
@@ -1584,10 +1505,18 @@ fn ec_encode_vif(
store_dirs,
collection,
vid,
)? {
Some(vi) if has_ec_config(&vi) => Ok(Some(vi)),
_ => Ok(fallback),
) {
Err(()) => return 0,
Ok(Some(vi)) => {
if let Some(ds) = vi.ec_shard_config.map(|c| c.data_shards as usize)
&& ds > 0
{
return ds;
}
}
Ok(None) => {}
}
DATA_SHARDS_COUNT
}
/// Parse a volume filename like "collection_42.dat" or "42.dat" into (collection, VolumeId).
@@ -1949,412 +1878,6 @@ mod tests {
);
}
fn write_ec_vif(base: &str, dat_file_size: i64) {
let vif = VifVolumeInfo {
version: 3,
dat_file_size,
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
data_shards: 10,
parity_shards: 4,
..Default::default()
}),
..Default::default()
};
fs::write(
format!("{}.vif", base),
serde_json::to_string(&vif).unwrap(),
)
.unwrap();
}
fn write_sized(path: &str, size: i64) {
fs::File::create(path)
.unwrap()
.set_len(size as u64)
.unwrap();
}
// An .ecx with one live needle ending at `end` in a current-version .dat.
fn write_ecx_ending_at(base: &str, end: i64) {
write_ecx_ending_at_version(base, end, Version::current());
}
fn write_ecx_ending_at_version(base: &str, end: i64, version: Version) {
let size = Size(1000);
let offset = end - crate::storage::needle::needle::get_actual_size(size, version);
let mut entry = [0u8; NEEDLE_MAP_ENTRY_SIZE];
idx_entry_to_bytes(
&mut entry,
NeedleId(1),
Offset::from_actual_offset(offset),
size,
);
fs::write(format!("{}.ecx", base), entry).unwrap();
}
// A .dat of `size` whose superblock names the current needle version.
fn write_sized_dat(path: &str, size: i64) {
use std::io::Write;
let mut f = fs::File::create(path).unwrap();
f.write_all(&[Version::current().0]).unwrap();
f.set_len(size as u64).unwrap();
}
fn test_location(dir: &str) -> DiskLocation {
DiskLocation::new(
dir,
dir,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap()
}
// A .dat larger than the source the .vif records sits beside a full-size
// shard of that encode: it is not the shards' source, so the shards stay,
// the .dat is not loaded, and nothing on disk is touched.
#[test]
fn test_load_existing_foreign_dat_beside_ec_shards_keeps_both() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let vid = VolumeId(74);
{
let mut loc = test_location(dir);
loc.create_volume(vid, NeedleMapKind::InMemory, &VolumeSpec::default())
.unwrap();
loc.close();
}
let base = volume_file_name(dir, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let source_size = 30 * 1024 * 1024i64;
write_ec_vif(&base, source_size);
let shard_size = calculate_expected_shard_size(source_size, ds);
write_sized(&format!("{}.ec09", base), shard_size);
// The .ecx indexes a needle ending exactly at the source size.
write_ecx_ending_at(&base, source_size);
write_sized(&format!("{}.ecj", base), 0);
// Grown past the source by later writes: its full encode would be
// larger than the shard, which used to read as an interrupted encode.
let foreign_size = source_size + 10 * 1024 * 1024;
assert!(calculate_expected_shard_size(foreign_size, ds) > shard_size);
fs::OpenOptions::new()
.write(true)
.open(format!("{}.dat", base))
.unwrap()
.set_len(foreign_size as u64)
.unwrap();
let exts = [".dat", ".idx", ".vif", ".ecx", ".ecj", ".ec09"];
let sizes: Vec<u64> = exts
.iter()
.map(|e| fs::metadata(format!("{}{}", base, e)).unwrap().len())
.collect();
let vif_before = fs::read(format!("{}.vif", base)).unwrap();
let mut loc = test_location(dir);
assert!(
loc.validate_ec_volume("", vid),
"shards whose .vif names a different source size than the .dat must be kept",
);
loc.load_existing_volumes(NeedleMapKind::InMemory).unwrap();
assert!(
loc.find_volume(vid).is_none(),
"a .dat that is not the encode source was loaded beside its EC shards",
);
for (e, size) in exts.iter().zip(sizes) {
let meta = fs::metadata(format!("{}{}", base, e))
.unwrap_or_else(|err| panic!("{} is gone: {}", e, err));
assert_eq!(meta.len(), size, "{} size changed", e);
}
assert_eq!(fs::read(format!("{}.vif", base)).unwrap(), vif_before);
}
// The .dat matches the recorded source size and the shards are short of its
// full encode: an interrupted local encode, still reclaimed.
#[test]
fn test_validate_ec_volume_interrupted_encode_with_recorded_size_reclaims() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let base = volume_file_name(dir, "", VolumeId(75));
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
let dat_size = 30 * 1024 * 1024i64;
write_sized(&format!("{}.dat", base), dat_size);
write_ec_vif(&base, dat_size);
let partial = calculate_expected_shard_size(dat_size, ds) / 3;
for i in 0..total {
write_sized(&format!("{}.ec{:02}", base, i), partial);
}
assert!(
!loc.validate_ec_volume("", VolumeId(75)),
"partial shards beside the recorded source .dat should be reclaimable",
);
}
// The .vif is written after the shards, so an interrupted re-encode of a
// volume that was once EC-decoded still has the old encode's .vif. Shards
// that are not that encode's full size are not described by it: reclaim.
#[test]
fn test_validate_ec_volume_interrupted_re_encode_with_stale_vif_reclaims() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let base = volume_file_name(dir, "", VolumeId(76));
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
let old_source_size = 20 * 1024 * 1024i64;
let dat_size = 60 * 1024 * 1024i64;
write_sized(&format!("{}.dat", base), dat_size);
write_ec_vif(&base, old_source_size);
let partial = calculate_expected_shard_size(dat_size, ds) / 2;
assert_ne!(partial, calculate_expected_shard_size(old_source_size, ds));
for i in 0..total {
write_sized(&format!("{}.ec{:02}", base, i), partial);
}
assert!(
!loc.validate_ec_volume("", VolumeId(76)),
"partial shards of an interrupted re-encode must not be kept for a stale .vif",
);
}
// Under a shared -dir.idx the encode's .vif can sit on a sibling data
// disk, where the mount also takes it from. The recorded source size must
// be read from there too, or the shards fall back to the .dat size check.
#[test]
fn test_validate_ec_volume_foreign_dat_keeps_shards_with_sibling_vif() {
let tmp = TempDir::new().unwrap();
let root = tmp.path().to_str().unwrap();
let (data_a, data_b, idx) = (
format!("{root}/a"),
format!("{root}/b"),
format!("{root}/idx"),
);
for d in [&data_a, &data_b, &idx] {
fs::create_dir_all(d).unwrap();
}
let mut loc = DiskLocation::new(
&data_a,
&idx,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
loc.store_dirs = vec![data_a.clone(), data_b.clone()];
let vid = VolumeId(78);
let base_a = volume_file_name(&data_a, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let source_size = 30 * 1024 * 1024i64;
write_ec_vif(&volume_file_name(&data_b, "", vid), source_size);
write_sized(&format!("{}.ecx", volume_file_name(&idx, "", vid)), 0);
write_sized(
&format!("{}.ec09", base_a),
calculate_expected_shard_size(source_size, ds),
);
write_sized(&format!("{}.dat", base_a), source_size + 10 * 1024 * 1024);
assert!(
loc.validate_ec_volume("", vid),
"the sibling .vif's source size was ignored and the shards would be deleted",
);
}
// A re-encode of a grown .dat interrupted under an earlier encode's .vif,
// with every partial shard exactly as long as that earlier encode's full
// shards. The re-encode wrote the .ecx of the grown .dat first, so it
// indexes needles past the recorded size: the shards are not that
// encode's, and the complete .dat is reclaimed.
#[test]
fn test_validate_ec_volume_interrupted_re_encode_matching_stale_length_reclaims() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let vid = VolumeId(79);
let base = volume_file_name(dir, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
let old_source_size = 20 * 1024 * 1024i64;
let dat_size = 60 * 1024 * 1024i64;
write_sized_dat(&format!("{}.dat", base), dat_size);
write_ec_vif(&base, old_source_size);
write_ecx_ending_at(&base, dat_size);
for i in 0..total {
write_sized(
&format!("{}.ec{:02}", base, i),
calculate_expected_shard_size(old_source_size, ds),
);
}
assert!(
!loc.validate_ec_volume("", vid),
"a stale .vif was trusted for partial shards under an .ecx of the grown .dat",
);
// The same shards under an .ecx that stays within the recorded size
// are that encode's: keep them.
write_ecx_ending_at(&base, old_source_size);
assert!(
loc.validate_ec_volume("", vid),
"shards whose .ecx and length match the recorded source must be kept",
);
}
// Only the .ecx the mount opens speaks for the shards: a non-empty
// data-dir .ecx within the recorded size wins over an older shared-idx
// .ecx pointing past it, and the shards stay.
#[test]
fn test_validate_ec_volume_checks_the_ecx_the_mount_opens() {
let tmp = TempDir::new().unwrap();
let root = tmp.path().to_str().unwrap();
let (data, idx) = (format!("{root}/data"), format!("{root}/idx"));
for d in [&data, &idx] {
fs::create_dir_all(d).unwrap();
}
let loc = DiskLocation::new(
&data,
&idx,
10,
DiskType::HardDrive,
MinFreeSpace::Percent(1.0),
Vec::new(),
)
.unwrap();
let vid = VolumeId(80);
let base = volume_file_name(&data, "", vid);
let idx_base = volume_file_name(&idx, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let source_size = 30 * 1024 * 1024i64;
write_ec_vif(&base, source_size);
write_ecx_ending_at(&base, source_size);
write_ecx_ending_at(&idx_base, source_size + 20 * 1024 * 1024);
write_sized(
&format!("{}.ec09", base),
calculate_expected_shard_size(source_size, ds),
);
write_sized_dat(&format!("{}.dat", base), source_size + 10 * 1024 * 1024);
assert!(
loc.validate_ec_volume("", vid),
"an .ecx the mount ignores decided against the shards",
);
// With no data-dir .ecx the mount opens the shared one, which indexes
// past the recorded size: the old rule applies and reclaims.
fs::remove_file(format!("{}.ecx", base)).unwrap();
assert!(
!loc.validate_ec_volume("", vid),
"the shared .ecx the mount opens was not checked",
);
}
// The .ecx extent is sized with the needle version the encode's .vif
// records, as the mount reads it, not the version of the foreign .dat.
#[test]
fn test_validate_ec_volume_sizes_the_ecx_with_the_encode_version() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let vid = VolumeId(81);
let base = volume_file_name(dir, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let source_size = 30 * 1024 * 1024i64;
let vif = VifVolumeInfo {
version: 2,
dat_file_size: source_size,
ec_shard_config: Some(crate::storage::volume::VifEcShardConfig {
data_shards: 10,
parity_shards: 4,
..Default::default()
}),
..Default::default()
};
fs::write(
format!("{}.vif", base),
serde_json::to_string(&vif).unwrap(),
)
.unwrap();
// Ends exactly at the source under version 2; version 3 would put it
// 8 bytes past.
write_ecx_ending_at_version(&base, source_size, Version(2));
write_sized(
&format!("{}.ec09", base),
calculate_expected_shard_size(source_size, ds),
);
write_sized_dat(&format!("{}.dat", base), source_size + 10 * 1024 * 1024);
assert!(
loc.validate_ec_volume("", vid),
"the .ecx was sized with the foreign .dat's needle version, not the encode's",
);
}
// An interrupted write leaves a torn .ecx tail; the whole entries before
// it still show the re-encode's .ecx indexing past the stale recorded size.
#[test]
fn test_validate_ec_volume_torn_ecx_tail_still_reclaims_re_encode() {
use std::io::Write;
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let vid = VolumeId(82);
let base = volume_file_name(dir, "", vid);
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let total = crate::storage::erasure_coding::ec_shard::TOTAL_SHARDS_COUNT;
let old_source_size = 20 * 1024 * 1024i64;
let dat_size = 60 * 1024 * 1024i64;
write_sized_dat(&format!("{}.dat", base), dat_size);
write_ec_vif(&base, old_source_size);
write_ecx_ending_at(&base, dat_size);
fs::OpenOptions::new()
.append(true)
.open(format!("{}.ecx", base))
.unwrap()
.write_all(&[1, 2, 3])
.unwrap();
for i in 0..total {
write_sized(
&format!("{}.ec{:02}", base, i),
calculate_expected_shard_size(old_source_size, ds),
);
}
assert!(
!loc.validate_ec_volume("", vid),
"a torn .ecx tail hid the entries past the stale recorded size",
);
}
// A .vif without a recorded source size keeps the old size check against
// the .dat, in both directions.
#[test]
fn test_validate_ec_volume_no_recorded_size_keeps_old_rule() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let loc = test_location(dir);
let base = volume_file_name(dir, "", VolumeId(77));
let ds = crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
write_ec_vif(&base, 0);
write_sized(
&format!("{}.ec00", base),
calculate_expected_shard_size(30 * 1024 * 1024, ds),
);
write_sized(&format!("{}.dat", base), 40 * 1024 * 1024);
assert!(
!loc.validate_ec_volume("", VolumeId(77)),
"without a recorded size, shards smaller than the .dat's full encode should be reclaimable",
);
write_sized(&format!("{}.dat", base), 30 * 1024 * 1024);
assert!(
loc.validate_ec_volume("", VolumeId(77)),
"without a recorded size, shards matching the .dat's full encode must be kept",
);
}
// The per-disk generation reader behind the fenced EC teardown: a present .vif
// yields its generation (or 0 with no EC config), a missing .vif is unreadable
// (preserved, fail-safe), and the idx dir is a fallback for the split-disk layout.
@@ -48,30 +48,28 @@ pub fn find_dat_file_size_with_dirs(
ec00.read_exact(&mut sb_buf)?;
let version = Version(sb_buf[0]);
// At least the superblock size
let extent = ecx_needle_extent(&format!("{}.ecx", ecx_base), version, deleted)?;
Ok(extent.max(SUPER_BLOCK_SIZE as i64))
}
// Start with at least the superblock size
let mut dat_size: i64 = SUPER_BLOCK_SIZE as i64;
/// Where the furthest live needle indexed by the `.ecx` at `ecx_path` ends in
/// the source `.dat`, or 0 when it indexes none. Needles in `deleted` count as
/// deleted. Mirrors Go's EcxNeedleExtent.
pub fn ecx_needle_extent(
ecx_path: &str,
version: Version,
deleted: &HashSet<NeedleId>,
) -> io::Result<i64> {
let ecx_data = std::fs::read(ecx_path)?;
let (entries, _) = ecx_data.as_chunks::<NEEDLE_MAP_ENTRY_SIZE>();
let mut extent = 0i64;
for entry in entries {
let (key, offset, size) = idx_entry_from_bytes(entry);
// Scan .ecx entries
let ecx_path = format!("{}.ecx", ecx_base);
let ecx_data = std::fs::read(&ecx_path)?;
let entry_count = ecx_data.len() / NEEDLE_MAP_ENTRY_SIZE;
for i in 0..entry_count {
let start = i * NEEDLE_MAP_ENTRY_SIZE;
let (key, offset, size) =
idx_entry_from_bytes(&ecx_data[start..start + NEEDLE_MAP_ENTRY_SIZE]);
if size.is_deleted() || deleted.contains(&key) {
continue;
}
extent = extent.max(offset.to_actual_offset() + get_actual_size(size, version));
let entry_stop = offset.to_actual_offset() + get_actual_size(size, version);
if entry_stop > dat_size {
dat_size = entry_stop;
}
}
Ok(extent)
Ok(dat_size)
}
/// Whether the `.ecx` in `ecx_dir` indexes a needle deleted neither there nor
+1 -10
View File
@@ -1056,18 +1056,9 @@ func (c *commandFsMergeVolumes) uploadManifestChunk(
uploadUrl := fmt.Sprintf("http://%s/%s", commandEnv.AdjustedUrl(assignResp.Location), assignResp.FileId)
jwt := security.EncodedJwt(assignResp.Auth)
if jwt == "" {
v := util.GetViper()
if signingKey := v.GetString("jwt.signing.key"); signingKey != "" {
expiresAfterSec := v.GetInt("jwt.signing.expires_after_seconds")
jwt = security.GenJwtForVolumeServer(security.SigningKey(signingKey), expiresAfterSec, assignResp.FileId)
}
}
uploadResult, err := uploader.UploadData(ctx, data, &operation.UploadOption{
UploadUrl: uploadUrl,
Jwt: jwt,
Jwt: volumeWriteJwt(assignResp.Auth, assignResp.FileId),
})
if err == nil && uploadResult.Error != "" {
err = fmt.Errorf("upload: %s", uploadResult.Error)
+160 -62
View File
@@ -21,6 +21,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"go.uber.org/atomic"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -37,6 +38,8 @@ type commandFsVerify struct {
verbose *bool
metadataFromLog *bool
pruneEntries *bool
restore *restoreSource
uploadRestored restoreUploadFn
concurrency *int
modifyTimeAgoAtSec int64
writer io.Writer
@@ -51,13 +54,32 @@ func (c *commandFsVerify) Name() string {
func (c *commandFsVerify) Help() string {
return `recursively verify all files under a directory
fs.verify [-v] [-modifyTimeAgo 1h] [-pruneEntries] [-concurrency 4] /buckets/dir
fs.verify [-v] [-modifyTimeAgo 1h] [-pruneEntries] [-restoreFrom /dir] [-concurrency 4] /buckets/dir
-pruneEntries deletes filer entries whose needles are missing from every
volume location holding the volume (data lost, e.g. after a volume
truncation). The delete only applies when the entry is unchanged since
verification, so a re-uploaded file is never pruned.
-restoreFrom recovers needles missing from every location out of regular
volume files left on disk, <collection>_<vid>.dat/.idx or <vid>.dat/.idx in
the given directory, opened read-only. A needle is restorable when the last
live .idx record of its key holds the chunk's cookie, passes its CRC, covers
the chunk's size and, for an MD5-sized chunk ETag, matches it. A later
tombstone in the .idx does not prevent the restore: the filer still
references the needle, so its intact bytes are kept.
The bytes are uploaded in their stored form (a gzipped needle stays
gzipped) to a file id the filer assigns in the volume file's collection,
read back, and the entry's chunk is repointed at them, keeping its offset,
size, ETag and flags. All restorable chunks of an entry go in one update,
which only applies when the entry is unchanged since verification.
A missing chunk held in a chunk manifest is restored by uploading a
rewritten manifest; the chunks held by a restored manifest are checked on
the next run. Chunks with a cipher key are not restored, nor is an entry
without a TTL whose path rule sets one, since the update would take it.
An entry is never pruned while the restore source holds, or cannot be read
for, a missing needle of it.
`
}
@@ -74,10 +96,22 @@ func (c *commandFsVerify) Do(args []string, commandEnv *CommandEnv, writer io.Wr
c.concurrency = fsVerifyCommand.Int("concurrency", 0, "number of parallel verification per volume server")
c.metadataFromLog = fsVerifyCommand.Bool("metadataFromLog", false, "Using filer log to get metadata")
c.pruneEntries = fsVerifyCommand.Bool("pruneEntries", false, "delete filer entries whose needles are missing from all volume locations (data lost); a changed entry is never deleted")
restoreFrom := fsVerifyCommand.String("restoreFrom", "", "directory of leftover <collection>_<vid>.dat/.idx files to restore needles missing from all volume locations")
if err = fsVerifyCommand.Parse(args); err != nil {
return err
}
if *restoreFrom != "" {
if c.restore, err = openRestoreSource(*restoreFrom); err != nil {
return fmt.Errorf("open restore source: %w", err)
}
c.uploadRestored = c.uploadRestoredBytes
defer func() {
c.restore.Close()
c.restore = nil
}()
}
path, parseErr := commandEnv.parseUrl(findInputDirectory(fsVerifyCommand.Args()))
if parseErr != nil {
return parseErr
@@ -105,15 +139,19 @@ func (c *commandFsVerify) Do(args []string, commandEnv *CommandEnv, writer io.Wr
defer close(c.waitChan[volumeServerStr])
}
}
var fCount, eCount, pCount uint64
var counts fsVerifyCounts
if *c.metadataFromLog {
var wg sync.WaitGroup
fCount, eCount, pCount, err = c.verifyProcessMetadata(path, &wg)
counts, err = c.verifyProcessMetadata(path, &wg)
wg.Wait()
} else {
fCount, eCount, pCount, err = c.verifyTraverseBfs(path)
counts, err = c.verifyTraverseBfs(path)
}
if c.restore != nil {
fmt.Fprintf(writer, "verified %d files, error %d files, pruned %d entries, restored %d entries \n", counts.verified, counts.errors, counts.pruned, counts.restored)
} else {
fmt.Fprintf(writer, "verified %d files, error %d files, pruned %d entries \n", counts.verified, counts.errors, counts.pruned)
}
fmt.Fprintf(writer, "verified %d files, error %d files, pruned %d entries \n", fCount, eCount, pCount)
return err
}
@@ -164,31 +202,65 @@ type ItemEntry struct {
rawChunks []*filer_pb.FileChunk
path util.FullPath
attr *filer_pb.FuseAttributes
// a manifest could not be resolved, so chunks are the readable ones
manifestUnresolved bool
}
type fsVerifyCounts struct {
verified, errors, pruned, restored uint64
}
// repairEntry restores an entry's missing needles when a restore source is
// set, and prunes it when none of them is restorable.
func (c *commandFsVerify) repairEntry(path util.FullPath, attr *filer_pb.FuseAttributes, rawChunks, missingChunks []*filer_pb.FileChunk, counts *fsVerifyCounts) {
if len(missingChunks) == 0 {
return
}
if c.restore != nil {
restored, restorable := c.restoreEntry(path, attr, rawChunks, missingChunks)
if restored {
counts.restored++
}
if restorable {
return
}
}
if !*c.pruneEntries {
return
}
pruned, pruneErr := c.pruneEntry(path, attr, rawChunks)
if pruneErr != nil {
fmt.Fprintf(c.writer, "prune %s failed: %v\n", path, pruneErr)
} else if pruned {
counts.pruned++
}
}
// resolveAndVerify expands chunk manifests, cut to their spans since chunks
// past a shortened manifest are never read, and verifies the entry's needles.
// An unresolvable manifest is an entry-level failure even when raw chunks are
// healthy; raw chunks are still checked so a missing manifest needle can be pruned.
func (c *commandFsVerify) resolveAndVerify(entryPath string, chunks []*filer_pb.FileChunk, errorChunksCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, hasMissingNeedles bool) {
// healthy; the readable chunks are still checked so a missing manifest needle
// can be pruned.
func (c *commandFsVerify) resolveAndVerify(entryPath string, chunks []*filer_pb.FileChunk, errorChunksCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, missingChunks []*filer_pb.FileChunk) {
dataChunks := chunks
manifestResolveFailed := false
if resolved, manifestChunks, resolveErr := filer.ResolveChunkManifest(context.Background(), filer.LookupFn(c.env), chunks, 0, math.MaxInt64, nil, true); resolveErr == nil {
dataChunks = append(resolved, manifestChunks...)
} else {
manifestResolveFailed = true
fmt.Fprintf(c.writer, "file: %s failed to resolve chunk manifest (%v), verifying raw chunks\n", entryPath, resolveErr)
fmt.Fprintf(c.writer, "file: %s failed to resolve chunk manifest (%v), verifying readable chunks\n", entryPath, resolveErr)
dataChunks = readableChunks(filer.LookupFn(c.env), chunks, math.MaxInt64)
}
verified, hasMissingNeedles = c.verifyEntry(entryPath, dataChunks, errorChunksCount, wg)
verified, missingChunks = c.verifyEntry(entryPath, dataChunks, errorChunksCount, wg)
if manifestResolveFailed && verified {
// an unreadable manifest is an entry-level failure even with healthy raw needles
verified = false
errorChunksCount.CompareAndSwap(0, 1)
}
return verified, hasMissingNeedles
return verified, missingChunks
}
func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup) (fileCount uint64, errCount uint64, prunedCount uint64, err error) {
func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup) (counts fsVerifyCounts, err error) {
processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
message := resp.EventNotification
if resp.EventNotification.NewEntry == nil {
@@ -200,7 +272,7 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup)
}
entryPath := fmt.Sprintf("%s/%s", message.NewParentPath, message.NewEntry.Name)
errorChunksCount := atomic.NewUint64(0)
verified, hasMissingNeedles := c.resolveAndVerify(entryPath, message.NewEntry.Chunks, errorChunksCount, wg)
verified, missingChunks := c.resolveAndVerify(entryPath, message.NewEntry.Chunks, errorChunksCount, wg)
if !verified {
if err = c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
entryResp, errReq := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
@@ -216,18 +288,9 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup)
if entryResp.Entry.Attributes.Mtime == message.NewEntry.Attributes.Mtime &&
bytes.Equal(entryResp.Entry.Attributes.Md5, message.NewEntry.Attributes.Md5) {
fmt.Fprintf(c.writer, "file: %s needles:%d failed:%d\n", entryPath, chunkCount, errorChunksCount.Load())
errCount++
if *c.pruneEntries && hasMissingNeedles {
pruned, pruneErr := c.pruneEntry(
util.NewFullPath(message.NewParentPath, message.NewEntry.Name),
message.NewEntry.Attributes,
message.NewEntry.Chunks)
if pruneErr != nil {
fmt.Fprintf(c.writer, "prune %s failed: %v\n", entryPath, pruneErr)
} else if pruned {
prunedCount++
}
}
counts.errors++
c.repairEntry(util.NewFullPath(message.NewParentPath, message.NewEntry.Name),
message.NewEntry.Attributes, message.NewEntry.Chunks, missingChunks, &counts)
}
return nil
}); err != nil {
@@ -238,7 +301,7 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup)
if *c.verbose {
fmt.Fprintf(c.writer, "file: %s needles:%d verified\n", entryPath, chunkCount)
}
fileCount++
counts.verified++
return nil
}
metadataFollowOption := &pb.MetadataFollowOption{
@@ -255,7 +318,29 @@ func (c *commandFsVerify) verifyProcessMetadata(path string, wg *sync.WaitGroup)
FilerTokenSource: c.env.option.FilerTokenSource,
}
err = pb.FollowMetadata(c.env.FilerAddress(), c.env.option.GrpcDialOption, metadataFollowOption, processEventFn)
return fileCount, errCount, prunedCount, err
return counts, err
}
// readableChunks expands the manifests it can read, one level at a time and
// cut to their spans like ResolveChunkManifest, and keeps each one it cannot
// read as a chunk to verify, so a missing manifest at any depth is checked
// like any other needle. Chunks starting at or past end are never read.
func readableChunks(lookupFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, end int64) (readable []*filer_pb.FileChunk) {
for _, chunk := range chunks {
if chunk.Offset >= end {
continue
}
readable = append(readable, chunk)
if !chunk.IsChunkManifest {
continue
}
held, err := filer.ResolveOneChunkManifest(context.Background(), lookupFn, chunk, nil)
if err != nil {
continue
}
readable = append(readable, readableChunks(lookupFn, held, min(end, chunk.Offset+int64(chunk.Size)))...)
}
return readable
}
// isNeedleMissingError reports whether a VolumeNeedleStatus error means the
@@ -286,13 +371,12 @@ func isNeedleMissingError(err error) bool {
}
// verifyEntry verifies all chunks of an entry. It returns verified=false when
// any chunk failed. hasMissingNeedles is true when at least one needle is
// missing from every volume location holding its volume, i.e. the data is
// lost rather than a transient or routing error.
func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk, errorCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, hasMissingNeedles bool) {
// any chunk failed. missingChunks are the chunks whose needle is missing from
// every volume location holding its volume, i.e. the data is lost rather than
// a transient or routing error.
func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk, errorCount *atomic.Uint64, wg *sync.WaitGroup) (verified bool, missingChunks []*filer_pb.FileChunk) {
fileMsg := fmt.Sprintf("file:%s", path)
itemIsVerifed := atomic.NewBool(true)
hasMissingNeedlesFlag := atomic.NewBool(false)
// tracks this entry's in-flight verifications so the missing-needle
// decision at the end of each chunk is deterministic
itemWg := &sync.WaitGroup{}
@@ -353,7 +437,7 @@ func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk,
}
itemWg.Wait()
if chunkMissingLocations.Load() == uint64(len(volumeIds)) {
hasMissingNeedlesFlag.Store(true)
missingChunks = append(missingChunks, chunk)
}
} else {
if !*c.metadataFromLog {
@@ -365,10 +449,12 @@ func (c *commandFsVerify) verifyEntry(path string, chunks []*filer_pb.FileChunk,
itemIsVerifed.Store(false)
errorCount.Add(1)
}
break
if c.restore == nil {
break
}
}
}
return itemIsVerifed.Load(), hasMissingNeedlesFlag.Load()
return itemIsVerifed.Load(), missingChunks
}
// deleteEntryCutoff splits an entry mtime into the conditional-delete fields:
@@ -394,7 +480,6 @@ func deleteEntryCutoff(mtimeSec int64, mtimeNsec int32) (sec, ns int64, ok bool)
// entry is only counted as pruned when a follow-up lookup confirms it is gone.
func (c *commandFsVerify) pruneEntry(path util.FullPath, attr *filer_pb.FuseAttributes, expectedChunks []*filer_pb.FileChunk) (pruned bool, err error) {
dir, name := path.DirAndName()
expectedIds := chunkFingerprints(expectedChunks)
lookupErr := c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
lookupResp, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{
Directory: dir,
@@ -406,16 +491,7 @@ func (c *commandFsVerify) pruneEntry(path util.FullPath, attr *filer_pb.FuseAttr
}
return err
}
att := lookupResp.Entry.GetAttributes()
if att.GetMtime() != attr.GetMtime() || att.GetMtimeNs() != attr.GetMtimeNs() {
fmt.Fprintf(c.writer, "skip pruning %s: entry changed since verification\n", path)
return nil
}
if md5 := attr.GetMd5(); len(md5) > 0 && !bytes.Equal(att.GetMd5(), md5) {
fmt.Fprintf(c.writer, "skip pruning %s: entry changed since verification\n", path)
return nil
}
if !chunksEqual(chunkFingerprints(lookupResp.Entry.GetChunks()), expectedIds) {
if entryChangedSince(lookupResp.Entry, attr, expectedChunks) {
fmt.Fprintf(c.writer, "skip pruning %s: entry changed since verification\n", path)
return nil
}
@@ -463,6 +539,19 @@ func (c *commandFsVerify) pruneEntry(path util.FullPath, attr *filer_pb.FuseAttr
return pruned, lookupErr
}
// entryChangedSince reports whether the entry differs from the one verified,
// by mtime, md5, or chunk set (a same-second rewrite changes only the chunks).
func entryChangedSince(entry *filer_pb.Entry, attr *filer_pb.FuseAttributes, chunks []*filer_pb.FileChunk) bool {
att := entry.GetAttributes()
if att.GetMtime() != attr.GetMtime() || att.GetMtimeNs() != attr.GetMtimeNs() {
return true
}
if md5 := attr.GetMd5(); len(md5) > 0 && !bytes.Equal(att.GetMd5(), md5) {
return true
}
return !chunksEqual(chunkFingerprints(entry.GetChunks()), chunkFingerprints(chunks))
}
// chunkFingerprints maps the file id of every chunk to a set, so two chunk
// lists count as identical when they reference the same needles.
func chunkFingerprints(chunks []*filer_pb.FileChunk) map[string]struct{} {
@@ -488,27 +577,35 @@ func chunksEqual(a, b map[string]struct{}) bool {
return true
}
func (c *commandFsVerify) verifyTraverseBfs(path string) (fileCount uint64, errCount uint64, prunedCount uint64, err error) {
func (c *commandFsVerify) verifyTraverseBfs(path string) (counts fsVerifyCounts, err error) {
timeNowAtSec := time.Now().Unix()
return fileCount, errCount, prunedCount, doTraverseBfsAndSaving(c.env, c.writer, path, false, false,
err = doTraverseBfsAndSaving(c.env, c.writer, path, false, false,
func(ctx context.Context, entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {
if c.modifyTimeAgoAtSec > 0 {
if entry.Entry.Attributes != nil && c.modifyTimeAgoAtSec < timeNowAtSec-entry.Entry.Attributes.Mtime {
return nil
}
}
entryPath := util.NewFullPath(entry.Dir, entry.Entry.Name)
manifestUnresolved := false
dataChunks, manifestChunks, resolveErr := filer.ResolveChunkManifest(context.Background(), filer.LookupFn(c.env), entry.Entry.GetChunks(), 0, math.MaxInt64, nil, true)
if resolveErr != nil {
return fmt.Errorf("failed to ResolveChunkManifest: %+v", resolveErr)
if c.restore == nil {
return fmt.Errorf("failed to ResolveChunkManifest: %+v", resolveErr)
}
// a missing manifest needle may be restorable
fmt.Fprintf(c.writer, "file: %s failed to resolve chunk manifest (%v), verifying readable chunks\n", entryPath, resolveErr)
dataChunks, manifestChunks, manifestUnresolved = readableChunks(filer.LookupFn(c.env), entry.Entry.GetChunks(), math.MaxInt64), nil, true
}
dataChunks = append(dataChunks, manifestChunks...)
if len(dataChunks) > 0 {
select {
case outputChan <- &ItemEntry{
chunks: dataChunks,
rawChunks: entry.Entry.GetChunks(),
path: util.NewFullPath(entry.Dir, entry.Entry.Name),
attr: entry.Entry.GetAttributes(),
chunks: dataChunks,
rawChunks: entry.Entry.GetChunks(),
path: entryPath,
attr: entry.Entry.GetAttributes(),
manifestUnresolved: manifestUnresolved,
}:
case <-ctx.Done():
return ctx.Err()
@@ -522,22 +619,23 @@ func (c *commandFsVerify) verifyTraverseBfs(path string) (fileCount uint64, errC
for itemEntry := range outputChan {
i := itemEntry.(*ItemEntry)
itemPath := string(i.path)
if verified, hasMissingNeedles := c.verifyEntry(itemPath, i.chunks, itemErrCount, &wg); verified {
verified, missingChunks := c.verifyEntry(itemPath, i.chunks, itemErrCount, &wg)
if verified && i.manifestUnresolved {
verified = false
itemErrCount.Add(1)
}
if verified {
if *c.verbose {
fmt.Fprintf(c.writer, "file: %s needles:%d verified\n", itemPath, len(i.chunks))
}
fileCount++
} else if *c.pruneEntries && hasMissingNeedles {
pruned, pruneErr := c.pruneEntry(i.path, i.attr, i.rawChunks)
if pruneErr != nil {
fmt.Fprintf(c.writer, "prune %s failed: %v\n", itemPath, pruneErr)
} else if pruned {
prunedCount++
}
counts.verified++
} else {
c.repairEntry(i.path, i.attr, i.rawChunks, missingChunks, &counts)
}
}
wg.Wait()
errCount = itemErrCount.Load()
counts.errors = itemErrCount.Load()
return nil
})
return counts, err
}
+442
View File
@@ -0,0 +1,442 @@
package shell
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"maps"
"slices"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
"google.golang.org/protobuf/proto"
)
// restoreUploadFn stores data under a new file id; gzipped says data is
// already gzip-compressed and must be stored that way.
type restoreUploadFn func(target restoreTarget, data []byte, gzipped bool, mimeType string) (fileId string, err error)
// restoreTarget is where a restored needle is assigned: the entry's path and
// lifetime, so the new needle expires with the entry, and the collection.
type restoreTarget struct {
path util.FullPath
collection string
ttlSec int32
}
type restorableChunk struct {
chunk *filer_pb.FileChunk
collection string
}
// restoreEntry copies the restorable missing chunks of an entry from the
// restore source into new needles and repoints the entry at them in one
// update. restorable reports that at least one missing chunk has intact bytes
// in the restore source, or may have, whether or not the update landed.
func (c *commandFsVerify) restoreEntry(path util.FullPath, attr *filer_pb.FuseAttributes, rawChunks, missing []*filer_pb.FileChunk) (restored, restorable bool) {
var ready []restorableChunk
mayHold := false
seen := make(map[string]bool)
for _, chunk := range missing {
fileId := chunk.GetFileIdString()
if seen[fileId] {
continue
}
seen[fileId] = true
_, collection, err := c.readRestorableNeedle(chunk)
if err != nil {
fmt.Fprintf(c.writer, "not restorable %s chunk %s: %v\n", path, fileId, err)
mayHold = mayHold || restoreSourceMayHold(err)
continue
}
ready = append(ready, restorableChunk{chunk: chunk, collection: collection})
}
if len(ready) == 0 {
return false, mayHold
}
dir, name := path.DirAndName()
var current *filer_pb.Entry
err := c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
resp, err := filer_pb.LookupEntry(context.Background(), client, &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: name})
if err != nil {
return err
}
current = resp.Entry
return nil
})
if errors.Is(err, filer_pb.ErrNotFound) {
fmt.Fprintf(c.writer, "skip restoring %s: entry deleted since verification\n", path)
return false, true
}
if err != nil {
fmt.Fprintf(c.writer, "restore %s failed: %v\n", path, err)
return false, true
}
if entryChangedSince(current, attr, rawChunks) {
fmt.Fprintf(c.writer, "skip restoring %s: entry changed since verification\n", path)
return false, true
}
ttlSec := current.GetAttributes().GetTtlSec()
if ttlSec == 0 {
// the filer gives an entry and needles without a TTL the path rule's
ruleTtlSec, err := c.pathRuleTtlSec(path)
if err != nil {
fmt.Fprintf(c.writer, "restore %s failed: %v\n", path, err)
return false, true
}
if ruleTtlSec > 0 {
fmt.Fprintf(c.writer, "skip restoring %s: the entry has no TTL, but its path rule would give the restored entry and needles one\n", path)
return false, true
}
}
newFileIds := make(map[string]string)
var uploaded []orphanedNeedle
for _, r := range ready {
// read again rather than held, so one needle at a time is in memory
oldFileId := r.chunk.GetFileIdString()
n, _, err := c.readRestorableNeedle(r.chunk)
var fileId string
if err == nil {
fileId, err = c.uploadRestored(restoreTarget{path, r.collection, ttlSec}, n.Data, n.IsCompressed(), restoreMimeType(n))
}
if err != nil {
fmt.Fprintf(c.writer, "not restored %s chunk %s: %v\n", path, oldFileId, err)
continue
}
newFileIds[oldFileId] = fileId
uploaded = append(uploaded, newOrphanedNeedle(fileId))
}
if len(newFileIds) == 0 {
return false, true
}
updated := proto.Clone(current).(*filer_pb.Entry)
applied := make(map[string]string)
for i, chunk := range updated.Chunks {
oldFileId := chunk.GetFileIdString()
if fileId, found := newFileIds[oldFileId]; found {
updated.Chunks[i] = withFileId(chunk, fileId)
applied[oldFileId] = fileId
} else if chunk.IsChunkManifest {
rewritten, manifestUploads, err := c.rewriteRestoredManifest(restoreTarget{path, ready[0].collection, ttlSec}, chunk, newFileIds, applied)
if err != nil {
fmt.Fprintf(c.writer, "restore %s: rewrite manifest %s: %v\n", path, oldFileId, err)
continue
}
if rewritten != nil {
updated.Chunks[i] = rewritten
uploaded = append(uploaded, manifestUploads...)
}
}
}
var unused []orphanedNeedle
for _, oldFileId := range slices.Sorted(maps.Keys(newFileIds)) {
if _, found := applied[oldFileId]; !found {
fmt.Fprintf(c.writer, "not restored %s chunk %s: no chunk list it is in could be rewritten\n", path, oldFileId)
unused = append(unused, newOrphanedNeedle(newFileIds[oldFileId]))
}
}
deleteOrphanedNeedles(c.env, path, unused, true)
if len(applied) == 0 {
return false, true
}
// A conditional create replaces the entry: UpdateEntry refuses while the
// stored entry holds a manifest the filer cannot read, which is the very
// state a restored manifest repairs.
err = c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer_pb.CreateEntry(context.Background(), client, &filer_pb.CreateEntryRequest{
Directory: dir,
Entry: updated,
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{
{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: current},
}},
})
})
if errors.Is(err, filer_pb.ErrPreconditionFailed) {
fmt.Fprintf(c.writer, "skip restoring %s: entry changed since verification\n", path)
deleteOrphanedNeedles(c.env, path, uploaded, true)
return false, true
}
if errors.Is(err, filer_pb.ErrReadOnly) {
fmt.Fprintf(c.writer, "skip restoring %s: path is read-only\n", path)
deleteOrphanedNeedles(c.env, path, uploaded, true)
return false, true
}
if err != nil {
// the update may still have landed, so the new needles stay
fmt.Fprintf(c.writer, "restore %s failed: %v\n", path, err)
return false, true
}
for _, oldFileId := range slices.Sorted(maps.Keys(applied)) {
fmt.Fprintf(c.writer, "restored %s chunk %s -> %s\n", path, oldFileId, applied[oldFileId])
}
for _, r := range ready {
if _, found := applied[r.chunk.GetFileIdString()]; found && r.chunk.IsChunkManifest {
fmt.Fprintf(c.writer, "restored %s manifest %s: run fs.verify again to check the chunks it holds\n", path, r.chunk.GetFileIdString())
}
}
return true, true
}
// pathRuleTtlSec is the TTL the filer.conf rule for path sets, as the filer
// reads it.
func (c *commandFsVerify) pathRuleTtlSec(path util.FullPath) (int32, error) {
fc, err := filer.ReadFilerConfFromClient(context.Background(), c.env, c.env.MasterClient)
if err != nil {
return 0, err
}
ttl, _ := needle.ReadTTL(fc.MatchStorageRule(string(path)).GetTtl())
return int32(ttl.Minutes()) * 60, nil
}
// readRestorableNeedle reads a missing chunk's needle from the restore source
// and checks it is the content the chunk names.
func (c *commandFsVerify) readRestorableNeedle(chunk *filer_pb.FileChunk) (*needle.Needle, string, error) {
vid := needle.VolumeId(chunk.Fid.GetVolumeId())
n, err := c.restore.readNeedle(vid, types.NeedleId(chunk.Fid.GetFileKey()), types.Cookie(chunk.Fid.GetCookie()))
if err != nil {
return nil, "", err
}
if len(chunk.CipherKey) > 0 {
return nil, "", restoreSourceMayHoldError{errors.New("encrypted chunk, skipped")}
}
if n.IsChunkedManifest() {
return nil, "", restoreSourceMayHoldError{errors.New("needle is a volume-level chunk manifest")}
}
if err := checkRestoredContent(chunk, n); err != nil {
return nil, "", err
}
return n, c.restore.volumes[vid].collection, nil
}
// checkRestoredContent compares the needle's content with what the chunk
// records: a manifest must parse; data must cover the chunk's size (a
// truncated file keeps a shorter size) and match an MD5-sized ETag.
func checkRestoredContent(chunk *filer_pb.FileChunk, n *needle.Needle) error {
data := n.Data
if n.IsCompressed() || chunk.IsCompressed {
decompressed, err := util.DecompressData(data)
if err != nil {
return fmt.Errorf("decompress: %w", err)
}
data = decompressed
}
if chunk.IsChunkManifest {
if err := proto.Unmarshal(data, &filer_pb.FileChunkManifest{}); err != nil {
return fmt.Errorf("manifest does not parse: %w", err)
}
return nil
}
if uint64(len(data)) < chunk.Size {
return fmt.Errorf("needle holds %d bytes, chunk needs %d", len(data), chunk.Size)
}
if chunk.SseType == filer_pb.SSEType_NONE && !chunkETagMatches(chunk.ETag, data) {
err := fmt.Errorf("content does not match chunk etag %s", chunk.ETag)
if util.CheckDigest(util.DigestMd5) != nil {
// without MD5 an MD5 ETag of intact content cannot match either
return restoreSourceMayHoldError{err}
}
return err
}
return nil
}
// chunkETagMatches checks an ETag holding a 16-byte digest, base64 or hex,
// against MD5 and truncated SHA-256 of data. Other ETags, like the needle CRC
// older writers recorded, say nothing about the content and pass.
func chunkETagMatches(etag string, data []byte) bool {
digest, err := base64.StdEncoding.DecodeString(etag)
if err != nil || len(digest) != 16 {
if digest, err = hex.DecodeString(etag); err != nil || len(digest) != 16 {
return true
}
}
if bytes.Equal(digest, util.Md5For(util.DigestSha256, data)) {
return true
}
return util.CheckDigest(util.DigestMd5) == nil && bytes.Equal(digest, util.Md5For(util.DigestMd5, data))
}
// restoreMimeType keeps the needle's mime unless the volume server would gzip
// an uncompressed needle for it, which would change its stored form.
func restoreMimeType(n *needle.Needle) string {
mimeType := string(n.Mime)
if n.IsCompressed() {
return mimeType
}
if compress, sure := util.IsCompressableFileType("", mimeType); mimeType == "" || compress && sure {
return "application/octet-stream"
}
return mimeType
}
func withFileId(chunk *filer_pb.FileChunk, fileId string) *filer_pb.FileChunk {
repointed := proto.Clone(chunk).(*filer_pb.FileChunk)
repointed.Fid, _ = filer_pb.ToFileIdObject(fileId)
repointed.FileId = ""
return repointed
}
func newOrphanedNeedle(fileId string) orphanedNeedle {
fid, _ := filer_pb.ToFileIdObject(fileId)
return orphanedNeedle{volumeId: fid.GetVolumeId(), fileId: fileId}
}
// rewriteRestoredManifest repoints the chunks a manifest holds, nested
// manifests included, and stores the result as a new manifest needle. It
// returns nil when the manifest holds none of newFileIds, and the manifest
// needles it uploaded otherwise.
func (c *commandFsVerify) rewriteRestoredManifest(target restoreTarget, manifest *filer_pb.FileChunk, newFileIds, applied map[string]string) (*filer_pb.FileChunk, []orphanedNeedle, error) {
if len(manifest.CipherKey) > 0 {
return nil, nil, errors.New("encrypted manifest")
}
held, err := filer.ResolveOneChunkManifest(context.Background(), filer.LookupFn(c.env), manifest, nil)
if err != nil {
return nil, nil, err
}
repointed := make(map[string]string)
var uploaded []orphanedNeedle
fail := func(err error) (*filer_pb.FileChunk, []orphanedNeedle, error) {
deleteOrphanedNeedles(c.env, target.path, uploaded, true)
return nil, nil, err
}
for i, chunk := range held {
oldFileId := chunk.GetFileIdString()
if fileId, found := newFileIds[oldFileId]; found {
held[i] = withFileId(chunk, fileId)
repointed[oldFileId] = fileId
} else if chunk.IsChunkManifest {
nested, nestedUploads, err := c.rewriteRestoredManifest(target, chunk, newFileIds, repointed)
if err != nil {
// the parent keeps referencing it as before
fmt.Fprintf(c.writer, "restore %s: rewrite manifest %s: %v\n", target.path, oldFileId, err)
continue
}
if nested != nil {
held[i] = nested
uploaded = append(uploaded, nestedUploads...)
}
}
}
if len(repointed) == 0 {
return nil, nil, nil
}
filer_pb.BeforeEntrySerialization(held)
blob, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: held})
if err != nil {
return fail(err)
}
fileId, err := c.uploadRestored(target, blob, false, "")
if err != nil {
return fail(err)
}
maps.Copy(applied, repointed)
// the ETag stays: an entry without an md5 derives its own from it
rewritten := withFileId(manifest, fileId)
rewritten.IsCompressed = false
return rewritten, append(uploaded, newOrphanedNeedle(fileId)), nil
}
// uploadRestoredBytes assigns a file id through the filer, uploads data in
// the given stored form, and reads it back: the restore only counts when the
// volume server holds exactly these bytes, gzipped exactly when asked.
func (c *commandFsVerify) uploadRestoredBytes(target restoreTarget, data []byte, gzipped bool, mimeType string) (string, error) {
var assign *filer_pb.AssignVolumeResponse
err := c.env.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.AssignVolume(context.Background(), &filer_pb.AssignVolumeRequest{
Count: 1,
Collection: target.collection,
TtlSec: target.ttlSec,
Path: target.path.Sanitized(),
ExpectedDataSize: uint64(len(data)),
})
if err != nil {
return err
}
if resp.Error != "" {
return errors.New(resp.Error)
}
if resp.Location == nil {
return errors.New("no location")
}
assign = resp
return nil
})
if err != nil {
return "", fmt.Errorf("assign volume: %w", err)
}
uploader, err := operation.NewUploader()
if err != nil {
return "", err
}
url := fmt.Sprintf("http://%s/%s", c.env.AdjustedUrl(assign.Location), assign.FileId)
option := &operation.UploadOption{
UploadUrl: url,
MimeType: mimeType,
IsInputCompressed: gzipped,
Jwt: volumeWriteJwt(assign.Auth, assign.FileId),
}
if !gzipped {
// keeps the uploader from compressing; the checksum it computes
// on its regular path is supplied here
option.IsReplication = true
option.ContentCrc32c = needle.ContentCrc32c(data)
}
result, err := uploader.UploadData(context.Background(), data, option)
if err == nil && result.Error != "" {
err = errors.New(result.Error)
}
if err == nil {
err = readBackRestored(url, assign.FileId, data, gzipped)
}
if err != nil {
deleteOrphanedNeedles(c.env, target.path, []orphanedNeedle{newOrphanedNeedle(assign.FileId)}, true)
return "", fmt.Errorf("upload %s: %w", assign.FileId, err)
}
return assign.FileId, nil
}
func readBackRestored(url, fileId string, data []byte, gzipped bool) error {
resp, body, err := readUrl(url, filer.JwtForVolumeServer(fileId))
if err != nil {
return fmt.Errorf("read back: %w", err)
}
defer util_http.CloseResponse(resp)
got, err := io.ReadAll(body)
if err != nil {
return fmt.Errorf("read back: %w", err)
}
if storedGzipped := resp.Header.Get("Content-Encoding") == "gzip"; storedGzipped != gzipped {
return fmt.Errorf("read back: stored gzipped=%v, want %v", storedGzipped, gzipped)
}
if !bytes.Equal(got, data) {
return fmt.Errorf("read back %d bytes differ from the %d uploaded", len(got), len(data))
}
return nil
}
// volumeWriteJwt is the assignment's write token, or one signed with the
// configured key when the filer returned none.
func volumeWriteJwt(auth, fileId string) security.EncodedJwt {
if auth != "" {
return security.EncodedJwt(auth)
}
v := util.GetViper()
if signingKey := v.GetString("jwt.signing.key"); signingKey != "" {
return security.GenJwtForVolumeServer(security.SigningKey(signingKey), v.GetInt("jwt.signing.expires_after_seconds"), fileId)
}
return ""
}
@@ -0,0 +1,193 @@
package shell
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
)
// errNotInRestoreSource means the restore source holds no live record of the
// needle, as opposed to holding bytes that fail a check.
var errNotInRestoreSource = errors.New("not in restore source")
// restoreSourceMayHoldError marks a needle the restore source holds, or could
// not be read to tell, that is still not restored; its entry is not pruned.
type restoreSourceMayHoldError struct{ error }
func (e restoreSourceMayHoldError) Unwrap() error { return e.error }
func restoreSourceMayHold(err error) bool {
return errors.As(err, new(restoreSourceMayHoldError))
}
// restoreSource reads needles from regular volume files left on disk outside
// any volume server, <collection>_<vid>.dat/.idx or <vid>.dat/.idx.
type restoreSource struct {
volumes map[needle.VolumeId]*restoreVolume
}
// restoreVolume loads its .idx on the first lookup: a directory of many
// volumes usually holds few that missing chunks name.
type restoreVolume struct {
collection string
idxPath string
datPath string
dat backend.BackendStorageFile
version needle.Version
needles map[types.NeedleId]restoreNeedleLocation
indexErr error
}
type restoreNeedleLocation struct {
offset types.Offset
size types.Size
}
func openRestoreSource(dir string) (*restoreSource, error) {
dirEntries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
source := &restoreSource{volumes: make(map[needle.VolumeId]*restoreVolume)}
opened := false
defer func() {
if !opened {
source.Close()
}
}()
for _, dirEntry := range dirEntries {
if !strings.HasSuffix(dirEntry.Name(), ".idx") {
continue
}
name := strings.TrimSuffix(dirEntry.Name(), ".idx")
base := filepath.Join(dir, name)
collection := ""
if i := strings.LastIndex(name, "_"); i > 0 {
collection, name = name[:i], name[i+1:]
}
vid, parseErr := needle.NewVolumeId(name)
if parseErr != nil {
continue
}
if existing, found := source.volumes[vid]; found {
return nil, fmt.Errorf("volume %d is in both %s and %s", vid, existing.datPath, base+".dat")
}
volume, openErr := openRestoreVolume(base)
if openErr != nil {
return nil, fmt.Errorf("volume %d: %w", vid, openErr)
}
volume.collection = collection
source.volumes[vid] = volume
}
if len(source.volumes) == 0 {
return nil, fmt.Errorf("no <vid>.idx or <collection>_<vid>.idx volume files in %s", dir)
}
opened = true
return source, nil
}
func openRestoreVolume(base string) (*restoreVolume, error) {
info, hasRemoteFile, _, err := volume_info.MaybeLoadVolumeInfo(base + ".vif")
if err != nil {
return nil, err
}
if hasRemoteFile {
return nil, fmt.Errorf("%s.vif points at a remote .dat", base)
}
if info.BytesOffset != 0 && info.BytesOffset != types.OffsetSize {
return nil, fmt.Errorf("%s.vif records %d-byte offsets, this binary reads %d-byte offsets", base, info.BytesOffset, types.OffsetSize)
}
datFile, err := os.Open(base + ".dat")
if err != nil {
return nil, err
}
dat := backend.NewDiskFile(datFile)
superBlock, err := super_block.ReadSuperBlock(dat)
if err != nil {
dat.Close()
return nil, err
}
if !needle.IsSupportedVersion(superBlock.Version) {
dat.Close()
return nil, fmt.Errorf("%s.dat has unsupported needle version %d", base, superBlock.Version)
}
return &restoreVolume{idxPath: base + ".idx", datPath: base + ".dat", dat: dat, version: superBlock.Version}, nil
}
// loadRestoreIndex maps each key to its last live record. A later tombstone
// does not hide an earlier record: a needle deleted on the volume but still
// referenced by the filer is worth restoring when its bytes are intact.
func loadRestoreIndex(idxPath string) (map[types.NeedleId]restoreNeedleLocation, error) {
idxFile, err := os.Open(idxPath)
if err != nil {
return nil, err
}
defer idxFile.Close()
// a cut-short last record would read as a key the volume never held
if info, err := idxFile.Stat(); err != nil {
return nil, err
} else if info.Size()%types.NeedleMapEntrySize != 0 {
return nil, fmt.Errorf("read %s: size %d is not a multiple of %d", idxPath, info.Size(), types.NeedleMapEntrySize)
}
needles := make(map[types.NeedleId]restoreNeedleLocation)
err = idx.WalkIndexFile(idxFile, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
if !offset.IsZero() && size.IsValid() {
needles[key] = restoreNeedleLocation{offset: offset, size: size}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("read %s: %w", idxPath, err)
}
return needles, nil
}
func (s *restoreSource) Close() {
for _, v := range s.volumes {
v.dat.Close()
}
}
// readNeedle returns the needle a file id names, after checking that the
// record holds that key and cookie and that its data matches its CRC.
func (s *restoreSource) readNeedle(vid needle.VolumeId, key types.NeedleId, cookie types.Cookie) (*needle.Needle, error) {
v, found := s.volumes[vid]
if !found {
return nil, errNotInRestoreSource
}
if v.needles == nil && v.indexErr == nil {
v.needles, v.indexErr = loadRestoreIndex(v.idxPath)
}
if v.indexErr != nil {
return nil, restoreSourceMayHoldError{v.indexErr}
}
loc, found := v.needles[key]
if !found {
return nil, errNotInRestoreSource
}
n := &needle.Needle{}
if err := n.ReadData(v.dat, loc.offset.ToActualOffset(), loc.size, v.version); err != nil {
err = fmt.Errorf("read %s at %d: %w", v.datPath, loc.offset.ToActualOffset(), err)
if errors.Is(err, needle.ErrorCorrupted) || errors.Is(err, needle.ErrorSizeMismatch) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return nil, err
}
return nil, restoreSourceMayHoldError{err}
}
if n.Id != key {
return nil, fmt.Errorf("%s at %d holds needle %s, want %s", v.datPath, loc.offset.ToActualOffset(), n.Id, key)
}
if n.Cookie != cookie {
return nil, fmt.Errorf("needle %s in %s has cookie %08x, want %08x", key, v.datPath, uint32(n.Cookie), uint32(cookie))
}
return n, nil
}
@@ -0,0 +1,263 @@
package shell
import (
"bytes"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
"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"
)
// testRestoreVolume writes a regular volume's .dat and .idx the way a volume
// server lays them out, for restore source tests.
type testRestoreVolume struct {
t *testing.T
dat *backend.DiskFile
idx *os.File
}
func newTestRestoreVolume(t *testing.T, base string) *testRestoreVolume {
t.Helper()
datFile, err := os.Create(base + ".dat")
if err != nil {
t.Fatal(err)
}
superBlock := super_block.SuperBlock{Version: needle.GetCurrentVersion(), ReplicaPlacement: &super_block.ReplicaPlacement{}, Ttl: &needle.TTL{}}
if _, err := datFile.Write(superBlock.Bytes()); err != nil {
t.Fatal(err)
}
idxFile, err := os.Create(base + ".idx")
if err != nil {
t.Fatal(err)
}
v := &testRestoreVolume{t: t, dat: backend.NewDiskFile(datFile), idx: idxFile}
t.Cleanup(v.close)
return v
}
func (v *testRestoreVolume) write(key uint64, cookie uint32, data []byte, compressed bool) {
v.t.Helper()
n := &needle.Needle{Id: types.NeedleId(key), Cookie: types.Cookie(cookie), Data: data}
n.Checksum = needle.NewCRC(n.Data)
if compressed {
n.SetIsCompressed()
}
offset, _, _, err := n.Append(v.dat, needle.GetCurrentVersion())
if err != nil {
v.t.Fatal(err)
}
if _, err := v.idx.Write(needle_map.ToBytes(n.Id, types.ToOffset(int64(offset)), n.Size)); err != nil {
v.t.Fatal(err)
}
}
func (v *testRestoreVolume) delete(key uint64) {
v.t.Helper()
if _, err := v.idx.Write(needle_map.ToBytes(types.NeedleId(key), types.Offset{}, types.TombstoneFileSize)); err != nil {
v.t.Fatal(err)
}
}
func (v *testRestoreVolume) close() {
v.dat.Close()
v.idx.Close()
}
func TestRestoreSourceReadsLastLiveRecord(t *testing.T) {
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "pics_7"))
v.write(1, 0x11, []byte("first"), false)
v.write(2, 0x22, []byte("overwritten"), false)
v.write(2, 0x23, []byte("overwrite"), false)
v.write(3, 0x33, []byte("deleted later"), false)
v.delete(3)
v.write(4, 0x44, []byte("deleted"), false)
v.delete(4)
v.close()
source, err := openRestoreSource(dir)
if err != nil {
t.Fatal(err)
}
defer source.Close()
volume := source.volumes[7]
if volume == nil || volume.collection != "pics" {
t.Fatalf("volume 7 = %+v, want collection pics", volume)
}
if volume.needles != nil {
t.Errorf("index loaded before the first lookup")
}
for _, c := range []struct {
key uint64
cookie uint32
want string
}{
{1, 0x11, "first"},
{2, 0x23, "overwrite"},
{3, 0x33, "deleted later"},
{4, 0x44, "deleted"},
} {
n, err := source.readNeedle(7, types.NeedleId(c.key), types.Cookie(c.cookie))
if err != nil {
t.Errorf("needle %d: %v", c.key, err)
continue
}
if string(n.Data) != c.want {
t.Errorf("needle %d holds %q, want %q", c.key, n.Data, c.want)
}
}
if len(volume.needles) != 4 {
t.Errorf("indexed %d needles, want 4", len(volume.needles))
}
// the earlier record of key 2 carried another cookie
if _, err := source.readNeedle(7, 2, 0x22); err == nil || !strings.Contains(err.Error(), "cookie") {
t.Errorf("stale cookie: got %v, want a cookie mismatch", err)
}
if _, err := source.readNeedle(7, 9, 0x99); !errors.Is(err, errNotInRestoreSource) {
t.Errorf("unknown key: got %v, want errNotInRestoreSource", err)
}
if _, err := source.readNeedle(8, 1, 0x11); !errors.Is(err, errNotInRestoreSource) {
t.Errorf("unknown volume: got %v, want errNotInRestoreSource", err)
}
}
func TestRestoreSourceRejectsCorruptedNeedle(t *testing.T) {
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, []byte("intact bytes"), false)
v.close()
datPath := filepath.Join(dir, "7.dat")
dat, err := os.ReadFile(datPath)
if err != nil {
t.Fatal(err)
}
i := bytes.Index(dat, []byte("intact"))
dat[i] ^= 0xff
if err := os.WriteFile(datPath, dat, 0644); err != nil {
t.Fatal(err)
}
source, err := openRestoreSource(dir)
if err != nil {
t.Fatal(err)
}
defer source.Close()
if source.volumes[7].collection != "" {
t.Errorf("collection %q, want none", source.volumes[7].collection)
}
if _, err := source.readNeedle(7, 1, 0x11); !errors.Is(err, needle.ErrorCorrupted) {
t.Fatalf("got %v, want a CRC failure", err)
}
}
func TestRestoreSourceOpen(t *testing.T) {
t.Run("empty directory", func(t *testing.T) {
if _, err := openRestoreSource(t.TempDir()); err == nil {
t.Fatal("want an error for a directory without volume files")
}
})
t.Run("same volume twice", func(t *testing.T) {
dir := t.TempDir()
newTestRestoreVolume(t, filepath.Join(dir, "a_7")).close()
newTestRestoreVolume(t, filepath.Join(dir, "b_7")).close()
if _, err := openRestoreSource(dir); err == nil || !strings.Contains(err.Error(), "volume 7") {
t.Fatalf("got %v, want a duplicate volume error", err)
}
})
t.Run("unreadable idx fails only its own lookups", func(t *testing.T) {
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, []byte("kept"), false)
v.close()
newTestRestoreVolume(t, filepath.Join(dir, "8")).close()
if err := os.Remove(filepath.Join(dir, "8.idx")); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(dir, "8.idx"), 0755); err != nil {
t.Fatal(err)
}
source, err := openRestoreSource(dir)
if err != nil {
t.Fatal(err)
}
defer source.Close()
if _, err := source.readNeedle(7, 1, 0x11); err != nil {
t.Errorf("volume 7: %v", err)
}
if _, err := source.readNeedle(8, 1, 0x11); err == nil || errors.Is(err, errNotInRestoreSource) {
t.Errorf("volume 8: got %v, want the index read error", err)
}
})
t.Run("directory name is not a pattern", func(t *testing.T) {
parent := t.TempDir()
dir := filepath.Join(parent, "restore[1]")
if err := os.Mkdir(dir, 0755); err != nil {
t.Fatal(err)
}
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, []byte("kept"), false)
v.close()
if err := os.Mkdir(filepath.Join(parent, "restore1"), 0755); err != nil {
t.Fatal(err)
}
newTestRestoreVolume(t, filepath.Join(parent, "restore1", "8")).close()
source, err := openRestoreSource(dir)
if err != nil {
t.Fatal(err)
}
defer source.Close()
if _, err := source.readNeedle(7, 1, 0x11); err != nil {
t.Errorf("volume 7: %v", err)
}
if _, found := source.volumes[8]; found {
t.Error("volume 8 is read from another directory")
}
})
t.Run("idx without dat", func(t *testing.T) {
dir := t.TempDir()
newTestRestoreVolume(t, filepath.Join(dir, "7")).close()
if err := os.Remove(filepath.Join(dir, "7.dat")); err != nil {
t.Fatal(err)
}
if _, err := openRestoreSource(dir); err == nil {
t.Fatal("want an error for a missing .dat")
}
})
}
func TestRestoreSourceKeepsKeysOfACutShortIndex(t *testing.T) {
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "pics_7"))
v.write(1, 0x11, []byte("first"), false)
v.write(2, 0x22, []byte("second"), false)
v.close()
idxPath := filepath.Join(dir, "pics_7.idx")
info, err := os.Stat(idxPath)
if err != nil {
t.Fatal(err)
}
if err := os.Truncate(idxPath, info.Size()-3); err != nil {
t.Fatal(err)
}
source, err := openRestoreSource(dir)
if err != nil {
t.Fatal(err)
}
defer source.Close()
_, err = source.readNeedle(7, 2, 0x22)
if !restoreSourceMayHold(err) {
t.Fatalf("readNeedle = %v, want a may-hold error for a key the cut record held", err)
}
}
@@ -0,0 +1,562 @@
package shell
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
)
// restoreTestFiler replaces entries under the IF_ENTRY_EQUAL precondition the
// way the filer does. changeBeforeUpdate makes a client write the entry
// between the restore's lookup and its update.
type restoreTestFiler struct {
stubFilerServer
updates []*filer_pb.CreateEntryRequest
changeBeforeUpdate bool
readOnly bool
}
func (s *restoreTestFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
if s.readOnly {
return &filer_pb.CreateEntryResponse{Error: "read only", ErrorCode: filer_pb.FilerError_READ_ONLY}, nil
}
path := string(util.NewFullPath(req.Directory, req.Entry.Name))
current := s.entries[path]
if s.changeBeforeUpdate {
current.Attributes.Mtime++
}
for _, clause := range req.GetCondition().GetClauses() {
if clause.Kind == filer_pb.WriteCondition_IF_ENTRY_EQUAL && !proto.Equal(clause.ExpectedEntry, current) {
return &filer_pb.CreateEntryResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil
}
}
s.updates = append(s.updates, req)
s.entries[path] = req.Entry
return &filer_pb.CreateEntryResponse{}, nil
}
type restoreTestUpload struct {
collection string
ttlSec int32
data []byte
gzipped bool
}
func etagOf(data []byte) string {
return base64.StdEncoding.EncodeToString(util.Md5For(util.DigestMd5, data))
}
func testChunk(vid uint32, key uint64, cookie uint32, offset int64, size int, etag string) *filer_pb.FileChunk {
return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: vid, FileKey: key, Cookie: cookie}, Offset: offset, Size: uint64(size), ETag: etag, ModifiedTsNs: 1_700_000_000_000_000_000 + int64(key)}
}
func newRestoreTestCommand(t *testing.T, filer *restoreTestFiler, restoreDir string) (*commandFsVerify, *bytes.Buffer, *[]restoreTestUpload) {
t.Helper()
commandEnv, _, cleanup := newFsVerifyTestCommandEnv(t, filer, &fsVerifyTestVolumeServer{})
t.Cleanup(cleanup)
commandEnv.MasterClient = wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{})
output := &bytes.Buffer{}
c := newFsVerifyTestCommand(t, commandEnv, output)
source, err := openRestoreSource(restoreDir)
if err != nil {
t.Fatal(err)
}
t.Cleanup(source.Close)
c.restore = source
uploads := &[]restoreTestUpload{}
c.uploadRestored = func(target restoreTarget, data []byte, gzipped bool, _ string) (string, error) {
*uploads = append(*uploads, restoreTestUpload{collection: target.collection, ttlSec: target.ttlSec, data: append([]byte(nil), data...), gzipped: gzipped})
return needle.NewFileId(9, uint64(100+len(*uploads)), 0xabcd).String(), nil
}
return c, output, uploads
}
func TestFsVerifyRestoreEntry(t *testing.T) {
plain := []byte("hello restored world")
text := bytes.Repeat([]byte("compressible "), 100)
gzipped, err := util.GzipData(text)
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "pics_7"))
v.write(1, 0x11, plain, false)
v.write(2, 0x22, gzipped, true)
v.write(6, 0x66, []byte("other bytes"), false)
v.close()
mtime := time.Now().Add(-time.Hour).Unix()
attr := &filer_pb.FuseAttributes{Mtime: mtime, Md5: []byte("md5"), TtlSec: 86400}
restorable := testChunk(7, 1, 0x11, 0, len(plain), etagOf(plain))
healthy := testChunk(7, 3, 0x33, int64(len(plain)), 10, "")
compressed := testChunk(7, 2, 0x22, int64(len(plain))+10, len(text), etagOf(text))
compressed.IsCompressed = true
lost := testChunk(7, 5, 0x55, int64(len(plain)+10+len(text)), 10, "")
wrongContent := testChunk(7, 6, 0x66, int64(len(plain)+20+len(text)), 11, etagOf([]byte("expected bytes")))
chunks := []*filer_pb.FileChunk{restorable, healthy, compressed, lost, wrongContent}
missing := []*filer_pb.FileChunk{restorable, compressed, lost, wrongContent}
newEntry := func() *filer_pb.Entry {
return &filer_pb.Entry{Name: "file", Attributes: proto.Clone(attr).(*filer_pb.FuseAttributes), Chunks: chunks}
}
path := util.NewFullPath("/buckets/b", "file")
t.Run("restores what it can in one update", func(t *testing.T) {
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): newEntry()}}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
if !restored || !isRestorable {
t.Fatalf("restored=%v restorable=%v, want both\n%s", restored, isRestorable, output)
}
if len(filer.updates) != 1 {
t.Fatalf("%d updates, want 1", len(filer.updates))
}
if len(*uploads) != 2 {
t.Fatalf("%d uploads, want 2", len(*uploads))
}
// the new needle is assigned with the entry's lifetime
if u := (*uploads)[0]; !bytes.Equal(u.data, plain) || u.gzipped || u.collection != "pics" || u.ttlSec != 86400 {
t.Errorf("plain upload = %+v", u)
}
// the stored gzip bytes go up as they are, marked gzipped
if u := (*uploads)[1]; !bytes.Equal(u.data, gzipped) || !u.gzipped {
t.Errorf("compressed upload gzipped=%v, same bytes=%v", u.gzipped, bytes.Equal(u.data, gzipped))
}
repointed := func(chunk *filer_pb.FileChunk, key uint64) *filer_pb.FileChunk {
want := proto.Clone(chunk).(*filer_pb.FileChunk)
want.Fid = &filer_pb.FileId{VolumeId: 9, FileKey: key, Cookie: 0xabcd}
return want
}
got := filer.updates[0].Entry.Chunks
for i, want := range []*filer_pb.FileChunk{
repointed(restorable, 101),
healthy,
repointed(compressed, 102),
lost,
wrongContent,
} {
want.FileId, got[i].FileId = "", ""
if !proto.Equal(got[i], want) {
t.Errorf("chunk %d = %v, want %v", i, got[i], want)
}
}
for _, line := range []string{
"restored /buckets/b/file chunk " + restorable.GetFileIdString() + " -> " + needle.NewFileId(9, 101, 0xabcd).String(),
"restored /buckets/b/file chunk " + compressed.GetFileIdString() + " -> " + needle.NewFileId(9, 102, 0xabcd).String(),
"not restorable /buckets/b/file chunk " + lost.GetFileIdString() + ": not in restore source",
"not restorable /buckets/b/file chunk " + wrongContent.GetFileIdString() + ": content does not match chunk etag",
} {
if !strings.Contains(output.String(), line) {
t.Errorf("output lacks %q:\n%s", line, output)
}
}
})
t.Run("entry changed since verification", func(t *testing.T) {
changed := newEntry()
changed.Attributes.Mtime++
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): changed}}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
if restored || !isRestorable || len(*uploads) != 0 || len(filer.updates) != 0 {
t.Fatalf("restored=%v restorable=%v uploads=%d updates=%d, want only restorable", restored, isRestorable, len(*uploads), len(filer.updates))
}
if !strings.Contains(output.String(), "skip restoring /buckets/b/file: entry changed since verification") {
t.Errorf("output:\n%s", output)
}
})
t.Run("entry changes before the update", func(t *testing.T) {
filer := &restoreTestFiler{
stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): newEntry()}},
changeBeforeUpdate: true,
}
c, output, _ := newRestoreTestCommand(t, filer, dir)
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
if restored || !isRestorable || len(filer.updates) != 0 {
t.Fatalf("restored=%v restorable=%v updates=%d, want only restorable", restored, isRestorable, len(filer.updates))
}
if !strings.Contains(output.String(), "skip restoring /buckets/b/file: entry changed since verification") {
t.Errorf("output:\n%s", output)
}
})
t.Run("path turns read-only before the update", func(t *testing.T) {
filer := &restoreTestFiler{
stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): newEntry()}},
readOnly: true,
}
c, output, _ := newRestoreTestCommand(t, filer, dir)
restored, isRestorable := c.restoreEntry(path, attr, chunks, missing)
if restored || !isRestorable || len(filer.updates) != 0 {
t.Fatalf("restored=%v restorable=%v updates=%d, want only restorable", restored, isRestorable, len(filer.updates))
}
if !strings.Contains(output.String(), "skip restoring /buckets/b/file: path is read-only") {
t.Errorf("output:\n%s", output)
}
})
t.Run("restorable entry is never pruned", func(t *testing.T) {
changed := newEntry()
changed.Attributes.Mtime++
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): changed}}}
c, _, _ := newRestoreTestCommand(t, filer, dir)
prune := true
c.pruneEntries = &prune
var counts fsVerifyCounts
c.repairEntry(path, attr, chunks, missing, &counts)
if counts != (fsVerifyCounts{}) || len(filer.deleted) != 0 {
t.Fatalf("counts=%+v deleted=%v, want the entry kept", counts, filer.deleted)
}
// nothing restorable: pruned as before
changed.Attributes.Mtime--
c.repairEntry(path, attr, chunks, []*filer_pb.FileChunk{lost}, &counts)
if counts.pruned != 1 || len(filer.deleted) != 1 {
t.Fatalf("counts=%+v deleted=%v, want the entry pruned", counts, filer.deleted)
}
})
}
func TestFsVerifyRestoreKeepsEntryTheSourceMayHold(t *testing.T) {
data := []byte("encrypted bytes")
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, data, false)
v.write(2, 0x22, data, false)
v.close()
newTestRestoreVolume(t, filepath.Join(dir, "8")).close()
if err := os.Truncate(filepath.Join(dir, "7.dat"), 8+int64(needle.GetActualSize(types.Size(len(data)), needle.GetCurrentVersion()))+10); err != nil {
t.Fatal(err)
}
if err := os.Remove(filepath.Join(dir, "8.idx")); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(dir, "8.idx"), 0755); err != nil {
t.Fatal(err)
}
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
encrypted := testChunk(7, 1, 0x11, 0, len(data), "")
encrypted.CipherKey = []byte("key")
truncated := testChunk(7, 2, 0x22, 0, len(data), "")
unreadable := testChunk(8, 3, 0x33, 0, 10, "")
path := util.NewFullPath("/buckets/b", "file")
for _, c := range []struct {
name string
chunk *filer_pb.FileChunk
kept bool
}{
{"encrypted chunk held by the source", encrypted, true},
{"unreadable index", unreadable, true},
{"needle cut off the .dat", truncated, false},
} {
t.Run(c.name, func(t *testing.T) {
chunks := []*filer_pb.FileChunk{c.chunk}
entry := &filer_pb.Entry{Name: "file", Attributes: proto.Clone(attr).(*filer_pb.FuseAttributes), Chunks: chunks}
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{string(path): entry}}}
cmd, output, uploads := newRestoreTestCommand(t, filer, dir)
prune := true
cmd.pruneEntries = &prune
var counts fsVerifyCounts
cmd.repairEntry(path, attr, chunks, chunks, &counts)
if len(*uploads) != 0 || len(filer.updates) != 0 {
t.Fatalf("uploads=%d updates=%d, want none\n%s", len(*uploads), len(filer.updates), output)
}
if kept := len(filer.deleted) == 0; kept != c.kept {
t.Fatalf("kept=%v, want %v\n%s", kept, c.kept, output)
}
})
}
}
// A missing chunk held in a manifest is restored by uploading a rewritten
// manifest that points at the new needle and keeps every other chunk.
func TestFsVerifyRestoreChunkInsideManifest(t *testing.T) {
data := []byte("chunk held by a manifest")
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, data, false)
v.close()
held := []*filer_pb.FileChunk{
testChunk(7, 1, 0x11, 0, len(data), etagOf(data)),
testChunk(7, 2, 0x22, int64(len(data)), 100, ""),
}
manifest := testChunk(8, 1, 0x88, 0, len(data)+100, "manifest-etag")
manifest.IsChunkManifest = true
path := util.NewFullPath("/dir", "file")
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix(), TtlSec: 3600}
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: []*filer_pb.FileChunk{manifest}}},
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{manifest: held})},
}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, _ := c.restoreEntry(path, attr, []*filer_pb.FileChunk{manifest}, held[:1])
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
}
if (*uploads)[1].ttlSec != 3600 {
t.Errorf("manifest assigned with ttl %d, want the entry's 3600", (*uploads)[1].ttlSec)
}
m := &filer_pb.FileChunkManifest{}
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
t.Fatal(err)
}
if len(m.Chunks) != 2 || m.Chunks[0].Fid.VolumeId != 9 || m.Chunks[0].Fid.FileKey != 101 || !proto.Equal(m.Chunks[1], held[1]) {
t.Fatalf("rewritten manifest holds %v", m.Chunks)
}
if m.Chunks[0].Offset != 0 || m.Chunks[0].Size != uint64(len(data)) || m.Chunks[0].ETag != held[0].ETag {
t.Errorf("restored chunk lost its fields: %v", m.Chunks[0])
}
got := filer.updates[0].Entry.Chunks[0]
if !got.IsChunkManifest || got.Fid.FileKey != 102 || got.Size != manifest.Size || got.ETag != manifest.ETag {
t.Errorf("entry manifest chunk = %v", got)
}
if !strings.Contains(output.String(), "restored /dir/file chunk "+held[0].GetFileIdString()+" -> "+needle.NewFileId(9, 101, 0xabcd).String()) {
t.Errorf("output:\n%s", output)
}
}
// A needle referenced both directly and inside a manifest is repointed in both.
func TestFsVerifyRestoreChunkDirectAndInsideManifest(t *testing.T) {
data := []byte("chunk referenced twice")
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, data, false)
v.close()
lost := testChunk(7, 1, 0x11, 0, len(data), etagOf(data))
manifest := testChunk(8, 1, 0x88, int64(len(data)), len(data), "")
manifest.IsChunkManifest = true
held := []*filer_pb.FileChunk{testChunk(7, 1, 0x11, int64(len(data)), len(data), etagOf(data))}
path := util.NewFullPath("/dir", "file")
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
chunks := []*filer_pb.FileChunk{lost, manifest}
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: chunks}},
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{manifest: held})},
}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, _ := c.restoreEntry(path, attr, chunks, []*filer_pb.FileChunk{lost})
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
}
got := filer.updates[0].Entry.Chunks
if got[0].Fid.FileKey != 101 || !got[1].IsChunkManifest || got[1].Fid.FileKey != 102 {
t.Fatalf("entry chunks = %v", got)
}
m := &filer_pb.FileChunkManifest{}
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
t.Fatal(err)
}
if len(m.Chunks) != 1 || m.Chunks[0].Fid.FileKey != 101 {
t.Fatalf("rewritten manifest holds %v", m.Chunks)
}
}
// An unreadable nested manifest stays referenced as it was, and the parent
// is still rewritten for the restored chunk it holds.
func TestFsVerifyRestoreBesideUnreadableNestedManifest(t *testing.T) {
data := []byte("chunk beside a lost manifest")
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, data, false)
v.close()
lost := testChunk(7, 1, 0x11, 0, len(data), etagOf(data))
unreadable := testChunk(8, 2, 0x99, int64(len(data)), 100, "")
unreadable.IsChunkManifest = true
held := []*filer_pb.FileChunk{lost, unreadable}
parent := testChunk(8, 1, 0x88, 0, len(data)+100, "")
parent.IsChunkManifest = true
path := util.NewFullPath("/dir", "file")
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: []*filer_pb.FileChunk{parent}}},
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{parent: held})},
}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, _ := c.restoreEntry(path, attr, []*filer_pb.FileChunk{parent}, []*filer_pb.FileChunk{lost})
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
}
m := &filer_pb.FileChunkManifest{}
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
t.Fatal(err)
}
if len(m.Chunks) != 2 || m.Chunks[0].Fid.FileKey != 101 || !proto.Equal(m.Chunks[1], unreadable) {
t.Fatalf("rewritten parent holds %v", m.Chunks)
}
}
// An entry without a TTL under a path rule with one is not restored: the
// update and the new needles would take the rule's TTL.
func TestFsVerifyRestoreSkipsEntryWithoutTtlUnderTtlRule(t *testing.T) {
data := []byte("kept forever")
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(1, 0x11, data, false)
v.close()
conf := filer.NewFilerConf()
if err := conf.SetLocationConf(&filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/b/", Ttl: "7d"}); err != nil {
t.Fatal(err)
}
var confText bytes.Buffer
if err := conf.ToText(&confText); err != nil {
t.Fatal(err)
}
lost := testChunk(7, 1, 0x11, 0, len(data), etagOf(data))
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-30 * 24 * time.Hour).Unix()}
confPath := util.NewFullPath(filer.DirectoryEtcSeaweedFS, filer.FilerConfName)
for _, tc := range []struct {
name string
path util.FullPath
ttlSec int32
restore bool
}{
{"no TTL under a TTL rule", "/buckets/b/file", 0, false},
{"own TTL under a TTL rule", "/buckets/b/file", 3600, true},
{"no TTL outside the rule", "/buckets/c/file", 0, true},
} {
t.Run(tc.name, func(t *testing.T) {
entryAttr := proto.Clone(attr).(*filer_pb.FuseAttributes)
entryAttr.TtlSec = tc.ttlSec
testFiler := &restoreTestFiler{stubFilerServer: stubFilerServer{entries: map[string]*filer_pb.Entry{
string(tc.path): {Name: tc.path.Name(), Attributes: entryAttr, Chunks: []*filer_pb.FileChunk{lost}},
string(confPath): {Name: filer.FilerConfName, Content: confText.Bytes()},
}}}
c, output, uploads := newRestoreTestCommand(t, testFiler, dir)
restored, isRestorable := c.restoreEntry(tc.path, entryAttr, []*filer_pb.FileChunk{lost}, []*filer_pb.FileChunk{lost})
if restored != tc.restore || !isRestorable || (len(*uploads) > 0) != tc.restore {
t.Fatalf("restored=%v restorable=%v uploads=%d, want restored=%v\n%s", restored, isRestorable, len(*uploads), tc.restore, output)
}
if !tc.restore && !strings.Contains(output.String(), "skip restoring "+string(tc.path)+": the entry has no TTL") {
t.Errorf("output:\n%s", output)
}
})
}
}
func TestCheckRestoredContent(t *testing.T) {
data := []byte("0123456789")
n := &needle.Needle{Data: data}
for _, c := range []struct {
name string
chunk *filer_pb.FileChunk
ok bool
}{
{"exact", testChunk(7, 1, 1, 0, 10, etagOf(data)), true},
{"truncated chunk", testChunk(7, 1, 1, 0, 4, etagOf(data)), true},
{"needle too short", testChunk(7, 1, 1, 0, 11, etagOf(data)), false},
{"md5 mismatch", testChunk(7, 1, 1, 0, 10, etagOf([]byte("other"))), false},
{"hex md5", testChunk(7, 1, 1, 0, 10, hex.EncodeToString(util.Md5For(util.DigestMd5, data))), true},
{"hex md5 mismatch", testChunk(7, 1, 1, 0, 10, hex.EncodeToString(util.Md5For(util.DigestMd5, []byte("x")))), false},
{"truncated sha256", testChunk(7, 1, 1, 0, 10, base64.StdEncoding.EncodeToString(util.Md5For(util.DigestSha256, data))), true},
{"crc etag", testChunk(7, 1, 1, 0, 10, "1a2b3c4d"), true},
{"no etag", testChunk(7, 1, 1, 0, 10, ""), true},
{"sse chunk keeps ciphertext", &filer_pb.FileChunk{Size: 10, ETag: etagOf([]byte("plain")), SseType: filer_pb.SSEType_SSE_S3}, true},
} {
if err := checkRestoredContent(c.chunk, n); (err == nil) != c.ok {
t.Errorf("%s: err=%v, want ok=%v", c.name, err, c.ok)
}
}
// a length-delimited field longer than the blob
if err := checkRestoredContent(&filer_pb.FileChunk{IsChunkManifest: true}, &needle.Needle{Data: []byte{0x0a, 0xff}}); err == nil {
t.Error("a manifest that does not parse must fail")
}
m, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: []*filer_pb.FileChunk{testChunk(7, 2, 2, 0, 1<<20, "")}})
if err != nil {
t.Fatal(err)
}
if err := checkRestoredContent(&filer_pb.FileChunk{Size: 1 << 20, IsChunkManifest: true}, &needle.Needle{Data: m}); err != nil {
t.Errorf("manifest: %v", err)
}
gzipped, err := util.GzipData(bytes.Repeat(data, 10))
if err != nil {
t.Fatal(err)
}
compressed := &needle.Needle{Data: gzipped}
compressed.SetIsCompressed()
if err := checkRestoredContent(testChunk(7, 1, 1, 0, 100, etagOf(bytes.Repeat(data, 10))), compressed); err != nil {
t.Errorf("compressed needle: %v", err)
}
}
// A lost manifest held by a readable one is restored, and the parent is
// rewritten to point at it.
func TestFsVerifyRestoreNestedManifest(t *testing.T) {
inner := []*filer_pb.FileChunk{testChunk(7, 5, 0x55, 100, 100, "")}
blob, err := proto.Marshal(&filer_pb.FileChunkManifest{Chunks: inner})
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
v := newTestRestoreVolume(t, filepath.Join(dir, "7"))
v.write(2, 0x22, blob, false)
v.close()
nested := testChunk(7, 2, 0x22, 100, 100, "")
nested.IsChunkManifest = true
held := []*filer_pb.FileChunk{testChunk(7, 1, 0x11, 0, 100, ""), nested}
parent := testChunk(8, 1, 0x88, 0, 200, "")
parent.IsChunkManifest = true
path := util.NewFullPath("/dir", "file")
attr := &filer_pb.FuseAttributes{Mtime: time.Now().Add(-time.Hour).Unix()}
filer := &restoreTestFiler{stubFilerServer: stubFilerServer{
entries: map[string]*filer_pb.Entry{string(path): {Name: "file", Attributes: attr, Chunks: []*filer_pb.FileChunk{parent}}},
volumeUrls: map[string]string{"8": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{parent: held})},
}}
c, output, uploads := newRestoreTestCommand(t, filer, dir)
restored, _ := c.restoreEntry(path, attr, []*filer_pb.FileChunk{parent}, []*filer_pb.FileChunk{nested})
if !restored || len(filer.updates) != 1 || len(*uploads) != 2 {
t.Fatalf("restored=%v updates=%d uploads=%d\n%s", restored, len(filer.updates), len(*uploads), output)
}
if !bytes.Equal((*uploads)[0].data, blob) {
t.Error("the nested manifest was not uploaded as stored")
}
m := &filer_pb.FileChunkManifest{}
if err := proto.Unmarshal((*uploads)[1].data, m); err != nil {
t.Fatal(err)
}
if len(m.Chunks) != 2 || !proto.Equal(m.Chunks[0], held[0]) || m.Chunks[1].Fid.FileKey != 101 || !m.Chunks[1].IsChunkManifest {
t.Fatalf("rewritten parent holds %v", m.Chunks)
}
if got := filer.updates[0].Entry.Chunks[0]; got.Fid.FileKey != 102 || !got.IsChunkManifest {
t.Errorf("entry chunk = %v", got)
}
if !strings.Contains(output.String(), "restored /dir/file manifest "+nested.GetFileIdString()) {
t.Errorf("output:\n%s", output)
}
}
+80 -17
View File
@@ -201,27 +201,44 @@ func TestFsVerifyVerifyEntryPrunability(t *testing.T) {
defer cleanup()
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
verified, prunable := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified {
t.Error("expected verification failure for missing needle")
}
if !prunable {
if len(missing) != 1 {
t.Error("needle missing on the only location must be prunable")
}
})
t.Run("healthy on one of two locations", func(t *testing.T) {
t.Run("healthy on both locations", func(t *testing.T) {
commandEnv, loc, cleanup := newFsVerifyTestCommandEnv(t,
&fsVerifyTestFilerServer{},
&fsVerifyTestVolumeServer{})
defer cleanup()
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc, loc)
verified, prunable := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
if !verified {
t.Error("needle present on one location should not fail verification")
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
if !verified || len(missing) != 0 {
t.Errorf("verified=%v missing=%d, want verified and none missing", verified, len(missing))
}
if prunable {
})
t.Run("healthy on one of two locations", func(t *testing.T) {
commandEnv, healthyLoc, cleanup := newFsVerifyTestCommandEnv(t,
&fsVerifyTestFilerServer{},
&fsVerifyTestVolumeServer{})
defer cleanup()
_, missingLoc, missingCleanup := newFsVerifyTestCommandEnv(t,
&fsVerifyTestFilerServer{},
&fsVerifyTestVolumeServer{missingNeedles: map[uint64]bool{42: true}})
defer missingCleanup()
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, missingLoc, healthyLoc)
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified {
t.Error("a replica missing the needle must fail verification")
}
if len(missing) != 0 {
t.Error("needle present somewhere must not be prunable")
}
})
@@ -235,13 +252,35 @@ func TestFsVerifyVerifyEntryPrunability(t *testing.T) {
concurrency := 2
c.concurrency = &concurrency
verified, prunable := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified || !prunable {
t.Errorf("concurrent verification = (%v, %v), want (false, true)", verified, prunable)
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{deadChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified || len(missing) != 1 {
t.Errorf("concurrent verification = (%v, %d missing), want (false, 1)", verified, len(missing))
}
})
}
// With a restore source, a chunk on a volume the cluster does not know does
// not hide a later missing chunk that may be restorable.
func TestFsVerifyRestoreChecksChunksPastAnUnknownVolume(t *testing.T) {
unknown := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 99, FileKey: 1}}
lost := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: 42}}
commandEnv, loc, cleanup := newFsVerifyTestCommandEnv(t,
&fsVerifyTestFilerServer{},
&fsVerifyTestVolumeServer{missingNeedles: map[uint64]bool{42: true}})
defer cleanup()
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
verified, missing := c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{unknown, lost}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified || len(missing) != 0 {
t.Fatalf("without a restore source: verified=%v missing=%d, want the scan to stop", verified, len(missing))
}
c.restore = &restoreSource{}
verified, missing = c.verifyEntry("/buckets/b/file", []*filer_pb.FileChunk{unknown, lost}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified || len(missing) != 1 || missing[0] != lost {
t.Fatalf("with a restore source: verified=%v missing=%v, want the lost chunk", verified, missing)
}
}
// Pruning must only delete the entry when it did not change since the
// verification pass — a re-upload fixes the file and must survive.
func TestFsVerifyPruneEntryGuards(t *testing.T) {
@@ -368,12 +407,12 @@ func TestFsVerifyManifestResolutionFailure(t *testing.T) {
defer cleanup()
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
verified, hasMissing := c.resolveAndVerify("/buckets/b/file",
verified, missing := c.resolveAndVerify("/buckets/b/file",
[]*filer_pb.FileChunk{manifestChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified {
t.Error("entry with an unresolvable manifest must not count as verified")
}
if hasMissing {
if len(missing) != 0 {
t.Error("healthy raw manifest needle must not be classified as missing")
}
})
@@ -392,12 +431,12 @@ func TestFsVerifyManifestResolutionFailure(t *testing.T) {
defer cleanup()
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
verified, hasMissing := c.resolveAndVerify("/buckets/b/file",
verified, missing := c.resolveAndVerify("/buckets/b/file",
[]*filer_pb.FileChunk{manifestChunk}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified {
t.Error("entry with a missing manifest needle must not count as verified")
}
if !hasMissing {
if len(missing) != 1 {
t.Error("missing manifest needle must be classified as prunable")
}
})
@@ -418,9 +457,33 @@ func TestFsVerifyIgnoresChunksPastAManifestSpan(t *testing.T) {
commandEnv.MasterClient = wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{})
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
verified, hasMissing := c.resolveAndVerify("/buckets/b/file",
verified, missing := c.resolveAndVerify("/buckets/b/file",
[]*filer_pb.FileChunk{shortened}, atomic.NewUint64(0), &sync.WaitGroup{})
if !verified || hasMissing {
t.Fatalf("verified=%v hasMissing=%v, want the needle past the span ignored", verified, hasMissing)
if !verified || len(missing) != 0 {
t.Fatalf("verified=%v missing=%d, want the needle past the span ignored", verified, len(missing))
}
}
// A missing manifest under a readable one fails the whole resolution, so the
// readable levels are walked and the missing manifest is reported like any
// other lost needle; a chunk past the parent's span is still ignored.
func TestFsVerifyFindsMissingNestedManifest(t *testing.T) {
chunk := func(key uint64, offset int64) *filer_pb.FileChunk {
return &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: key, Cookie: 1}, Offset: offset, Size: 100}
}
nested := chunk(3, 100)
nested.IsChunkManifest = true
parent := &filer_pb.FileChunk{Fid: &filer_pb.FileId{VolumeId: 7, FileKey: 1, Cookie: 1}, Size: 200, IsChunkManifest: true}
filerServer := &stubFilerServer{volumeUrls: map[string]string{"7": startStubManifestVolume(t, map[*filer_pb.FileChunk][]*filer_pb.FileChunk{
parent: {chunk(2, 0), nested, chunk(4, 200)},
})}}
commandEnv, loc, cleanup := newFsVerifyTestCommandEnv(t, filerServer, &fsVerifyTestVolumeServer{missingNeedles: map[uint64]bool{3: true, 4: true}})
defer cleanup()
commandEnv.MasterClient = wdclient.NewMasterClient(grpc.WithTransportCredentials(insecure.NewCredentials()), "", "shell", "", "", "", pb.ServerDiscovery{})
c := newFsVerifyTestCommand(t, commandEnv, &bytes.Buffer{}, loc)
verified, missing := c.resolveAndVerify("/buckets/b/file", []*filer_pb.FileChunk{parent}, atomic.NewUint64(0), &sync.WaitGroup{})
if verified || len(missing) != 1 || missing[0].GetFileIdString() != nested.GetFileIdString() {
t.Fatalf("verified=%v missing=%v, want only the nested manifest missing", verified, missing)
}
}
+40 -82
View File
@@ -1,9 +1,7 @@
package storage
import (
"errors"
"fmt"
"io"
"os"
"path"
"regexp"
@@ -14,7 +12,6 @@ import (
"slices"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
@@ -660,27 +657,22 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
baseFileName := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
datFileName := baseFileName + ".dat"
// Custom ratio and source size come from the encode's own .vif; the
// server holds no cluster EC config in memory.
encodeInfo, ambiguous := l.ecEncodeVolumeInfo(collection, vid)
if ambiguous {
// Custom ratio comes from the volume's own .vif; the server holds no
// cluster EC config in memory.
dataShards := l.ecDataShardsFromVif(collection, vid)
if dataShards == 0 {
glog.Warningf("EC volume %d: sibling .vif files disagree on the encode; keeping EC shards", vid)
return true
}
dataShards := erasure_coding.DataShardsCount
if ds := encodeInfo.GetEcShardConfig().GetDataShards(); ds > 0 {
dataShards = int(ds)
}
// On-disk .dat size, or -1 when absent (an empty <= superblock .dat is a
// stub). A transient stat error keeps the shards rather than deleting.
var datSize, expectedShardSize int64 = -1, -1
var expectedShardSize int64 = -1
datExists := false
if datFileInfo, err := os.Stat(datFileName); err == nil {
if datFileInfo.Size() > int64(super_block.SuperBlockSize) {
datExists = true
datSize = datFileInfo.Size()
expectedShardSize = calculateExpectedShardSize(datSize, dataShards)
expectedShardSize = calculateExpectedShardSize(datFileInfo.Size(), dataShards)
}
} else if !os.IsNotExist(err) {
glog.Warningf("EC volume %d: cannot stat .dat %s (%v); keeping EC shards", vid, datFileName, err)
@@ -720,20 +712,6 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
if shardCount == 0 {
return false
}
// Shards that are exactly the full encode of the source size the .vif
// records, under an .ecx indexing nothing past that size, were made from
// that source. A .dat of any other size is not it (e.g. a replica that
// kept taking writes), so its size says nothing about these shards: keep
// them, and leave the .dat unloaded so it cannot collide with the EC
// volume. The .ecx check catches a re-encode interrupted under an earlier
// encode's .vif: it writes the .ecx of the grown .dat before the shards.
if recorded := encodeInfo.GetDatFileSize(); recorded > 0 && datSize != recorded &&
actualShardSize == calculateExpectedShardSize(recorded, dataShards) &&
!l.ecxIndexesPast(collection, vid, encodeNeedleVersion(encodeInfo), recorded) {
glog.Warningf("EC volume %d: .dat is %d bytes but the .vif records an encode source of %d bytes; keeping the EC shards and leaving the .dat in place untouched",
vid, datSize, recorded)
return true
}
if expectedShardSize > 0 && actualShardSize > 0 && actualShardSize < expectedShardSize {
glog.Warningf("EC volume %d: %d shards of %d bytes are smaller than the .dat's full encode (%d bytes); reclaiming the complete .dat",
vid, shardCount, actualShardSize, expectedShardSize)
@@ -742,72 +720,52 @@ func (l *DiskLocation) validateEcVolume(collection string, vid needle.VolumeId)
return true
}
// ecxIndexesPast reports whether the .ecx the mount would open for
// (collection, vid) -- the data dir's when non-empty, else the idx dir's --
// indexes a live needle ending past size. A missing or unreadable file
// reports false: a doubt keeps the shards. A torn tail is what an
// interrupted write leaves, so the whole entries before it still count.
func (l *DiskLocation) ecxIndexesPast(collection string, vid needle.VolumeId, version needle.Version, size int64) bool {
ecxBase := erasure_coding.EcShardFileName(collection, l.Directory, int(vid))
if fi, err := os.Stat(ecxBase + ".ecx"); (err != nil || fi.Size() == 0) && l.IdxDirectory != l.Directory {
ecxBase = erasure_coding.EcShardFileName(collection, l.IdxDirectory, int(vid))
}
extent, err := erasure_coding.EcxNeedleExtent(ecxBase, version)
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
return false
}
return extent > size
}
// encodeNeedleVersion is the needle version the encode's .vif records, as the
// mount reads it, defaulting to the current version when unset.
func encodeNeedleVersion(info *volume_server_pb.VolumeInfo) needle.Version {
if v := info.GetVersion(); v > 0 {
return needle.Version(v)
}
return needle.GetCurrentVersion()
}
// ecEncodeVolumeInfo returns the .vif describing the encode of an EC volume:
// the first with an EC shard config in the data dir, the idx dir, then the
// sibling data dir the mount takes it from under a shared idx dir. Without
// one it falls back to the first .vif found in the data or idx dir, which
// may be nil. ambiguous is set when sibling .vif files disagree on the run.
func (l *DiskLocation) ecEncodeVolumeInfo(collection string, vid needle.VolumeId) (info *volume_server_pb.VolumeInfo, ambiguous bool) {
var fallback *volume_server_pb.VolumeInfo
load := func(vifName string) *volume_server_pb.VolumeInfo {
vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vifName)
if !found {
return nil
}
if fallback == nil {
fallback = vi
}
if vi.GetEcShardConfig().GetDataShards() > 0 {
return vi
}
return nil
}
// ecDataShardsFromVif resolves the data-shard count for an EC volume from
// its own .vif (EcShardConfig), checking the data dir, the idx dir, then the
// sibling data dir the mount takes the .vif from under a shared idx dir. The
// .vif is the source of truth for custom ratios on the volume server, which
// never holds the cluster EC config in memory. Falls back to the default
// ratio when the .vif carries no EC shard config.
func (l *DiskLocation) ecDataShardsFromVif(collection string, vid needle.VolumeId) int {
// At most two dirs to check; avoid slice/map allocations on this
// per-volume startup path.
if l.Directory != "" {
if vi := load(erasure_coding.EcShardFileName(collection, l.Directory, int(vid)) + ".vif"); vi != nil {
return vi, false
if ds := ecDataShardsFromVifDir(collection, l.Directory, vid); ds > 0 {
return ds
}
}
if l.IdxDirectory != "" && l.IdxDirectory != l.Directory {
if vi := load(erasure_coding.EcShardFileName(collection, l.IdxDirectory, int(vid)) + ".vif"); vi != nil {
return vi, false
if ds := ecDataShardsFromVifDir(collection, l.IdxDirectory, vid); ds > 0 {
return ds
}
vif, ambiguous := erasure_coding.SiblingEcConfigVif(collection, vid, l.Directory, l.IdxDirectory, l.storeDirs)
if ambiguous {
return nil, true
return 0
}
if vif != "" {
if vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vif); found && vi.GetEcShardConfig().GetDataShards() > 0 {
return vi, false
if ds := ecDataShardsFromVifPath(vif); ds > 0 {
return ds
}
}
}
return fallback, false
return erasure_coding.DataShardsCount
}
// ecDataShardsFromVifDir returns the .vif EcShardConfig data-shard count for
// (collection, vid) under dir, or 0 when absent / not custom.
func ecDataShardsFromVifDir(collection, dir string, vid needle.VolumeId) int {
return ecDataShardsFromVifPath(erasure_coding.EcShardFileName(collection, dir, int(vid)) + ".vif")
}
// ecDataShardsFromVifPath returns the EcShardConfig data-shard count recorded
// in one .vif, or 0 when absent / not custom.
func ecDataShardsFromVifPath(vifName string) int {
if vi, _, found, _ := volume_info.MaybeLoadVolumeInfo(vifName); found && vi.EcShardConfig != nil {
if ds := int(vi.EcShardConfig.DataShards); ds > 0 {
return ds
}
}
return 0
}
// removeEcVolumeFiles removes all EC-related files for a volume
@@ -5,13 +5,8 @@ import (
"path/filepath"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
)
func writeSizedFile(t *testing.T, path string, size int64) {
@@ -106,331 +101,3 @@ func TestValidateEcVolume_TransientStatErrorKeeps(t *testing.T) {
t.Fatal("validateEcVolume returned delete on a transient stat error; must keep on ambiguity")
}
}
func writeEcVif(t *testing.T, base string, datFileSize int64) {
t.Helper()
vi := &volume_server_pb.VolumeInfo{
Version: uint32(needle.GetCurrentVersion()),
DatFileSize: datFileSize,
EcShardConfig: &volume_server_pb.EcShardConfig{
DataShards: uint32(erasure_coding.DataShardsCount),
ParityShards: uint32(erasure_coding.ParityShardsCount),
},
}
if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil {
t.Fatalf("save .vif: %v", err)
}
}
// A .dat larger than the source the .vif records sits beside a full-size
// shard of that encode: it is not the shards' source, so the shards stay, the
// .dat is not loaded, and nothing on disk is touched.
func TestLoadExistingVolume_ForeignDatBesideEcShardsKeepsBoth(t *testing.T) {
store := newTestStore(t, 1)
l := store.Locations[0]
const vid = needle.VolumeId(74)
mountTestVolume(t, l, vid, "")
l.UnloadVolume(vid)
base := erasure_coding.EcShardFileName("", l.Directory, int(vid))
sourceSize := int64(30 * 1024 * 1024)
writeEcVif(t, base, sourceSize)
shardSize := calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount)
writeSizedFile(t, base+erasure_coding.ToExt(9), shardSize)
// The .ecx indexes a needle ending exactly at the source size.
writeEcxEndingAt(t, base, sourceSize)
writeSizedFile(t, base+".ecj", 0)
// Grown past the source by later writes: its full encode would be larger
// than the shard, which used to read as an interrupted local encode.
foreignSize := sourceSize + 10*1024*1024
if calculateExpectedShardSize(foreignSize, erasure_coding.DataShardsCount) <= shardSize {
t.Fatal("test setup: the foreign .dat must encode to larger shards")
}
if err := os.Truncate(base+".dat", foreignSize); err != nil {
t.Fatal(err)
}
want := map[string]int64{}
for _, ext := range []string{".dat", ".idx", ".vif", ".ecx", ".ecj", erasure_coding.ToExt(9)} {
fi, err := os.Stat(base + ext)
if err != nil {
t.Fatalf("stat %s: %v", ext, err)
}
want[ext] = fi.Size()
}
vifBefore, err := os.ReadFile(base + ".vif")
if err != nil {
t.Fatal(err)
}
if !l.validateEcVolume("", vid) {
t.Fatal("validateEcVolume would delete shards whose .vif names a different source size than the .dat beside them")
}
l.loadExistingVolume(filepath.Base(base)+".idx", NeedleMapInMemory, true, 0, 0, false)
if _, found := l.FindVolume(vid); found {
t.Fatal("a .dat that is not the encode source was loaded beside its EC shards")
}
for ext, size := range want {
fi, err := os.Stat(base + ext)
if err != nil {
t.Fatalf("%s is gone: %v", ext, err)
}
if fi.Size() != size {
t.Fatalf("%s size changed: %d -> %d", ext, size, fi.Size())
}
}
if vifAfter, _ := os.ReadFile(base + ".vif"); string(vifAfter) != string(vifBefore) {
t.Fatal(".vif was rewritten")
}
}
// The .dat matches the recorded source size and the shards are short of its
// full encode: an interrupted local encode, still reclaimed.
func TestValidateEcVolume_InterruptedEncodeWithRecordedSizeReclaims(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
base := erasure_coding.EcShardFileName("", l.Directory, 75)
datSize := int64(30 * 1024 * 1024)
writeSizedFile(t, base+".dat", datSize)
writeEcVif(t, base, datSize)
partialShardSize := calculateExpectedShardSize(datSize, erasure_coding.DataShardsCount) / 3
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
writeSizedFile(t, base+erasure_coding.ToExt(i), partialShardSize)
}
if l.validateEcVolume("", 75) {
t.Fatal("validateEcVolume kept partial shards beside the recorded source .dat")
}
}
// The .vif is written after the shards, so an interrupted re-encode of a
// volume that was once EC-decoded still has the old encode's .vif. Shards that
// are not that encode's full size are not described by it: reclaim as before.
func TestValidateEcVolume_InterruptedReEncodeWithStaleVifReclaims(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
base := erasure_coding.EcShardFileName("", l.Directory, 76)
oldSourceSize := int64(20 * 1024 * 1024)
datSize := int64(60 * 1024 * 1024)
writeSizedFile(t, base+".dat", datSize)
writeEcVif(t, base, oldSourceSize)
partialShardSize := calculateExpectedShardSize(datSize, erasure_coding.DataShardsCount) / 2
if partialShardSize == calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount) {
t.Fatal("test setup: partial shards must not match the stale encode's size")
}
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
writeSizedFile(t, base+erasure_coding.ToExt(i), partialShardSize)
}
if l.validateEcVolume("", 76) {
t.Fatal("validateEcVolume kept partial shards of an interrupted re-encode because of a stale .vif")
}
}
// A .vif without a recorded source size keeps the old size check against the
// .dat, in both directions.
func TestValidateEcVolume_NoRecordedSizeKeepsOldRule(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
base := erasure_coding.EcShardFileName("", l.Directory, 77)
shardSize := calculateExpectedShardSize(30*1024*1024, erasure_coding.DataShardsCount)
writeEcVif(t, base, 0)
writeSizedFile(t, base+erasure_coding.ToExt(0), shardSize)
writeSizedFile(t, base+".dat", 40*1024*1024)
if l.validateEcVolume("", 77) {
t.Fatal("without a recorded size, shards smaller than the .dat's full encode should be reclaimable")
}
writeSizedFile(t, base+".dat", 30*1024*1024)
if !l.validateEcVolume("", 77) {
t.Fatal("without a recorded size, shards matching the .dat's full encode must be kept")
}
}
// Under a shared -dir.idx the encode's .vif can sit on a sibling data disk,
// where the mount also takes it from. The recorded source size must be read
// from there too, or the shards fall back to the .dat size check and go.
func TestValidateEcVolume_ForeignDatKeepsShardsWithSiblingVif(t *testing.T) {
root := t.TempDir()
dataA, dataB, idx := filepath.Join(root, "a"), filepath.Join(root, "b"), filepath.Join(root, "idx")
for _, d := range []string{dataA, dataB, idx} {
if err := os.Mkdir(d, 0o755); err != nil {
t.Fatal(err)
}
}
l := newTestDiskLocation(dataA)
l.IdxDirectory = idx
l.storeDirs = []string{dataA, dataB}
const vid = 78
baseA := erasure_coding.EcShardFileName("", dataA, vid)
sourceSize := int64(30 * 1024 * 1024)
writeEcVif(t, erasure_coding.EcShardFileName("", dataB, vid), sourceSize)
writeSizedFile(t, erasure_coding.EcShardFileName("", idx, vid)+".ecx", 0)
writeSizedFile(t, baseA+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
writeSizedFile(t, baseA+".dat", sourceSize+10*1024*1024)
if !l.validateEcVolume("", vid) {
t.Fatal("validateEcVolume ignored the sibling .vif's source size and would delete the shards")
}
}
// writeEcxEndingAt writes an .ecx with one live needle ending at end in a
// current-version .dat.
func writeEcxEndingAt(t *testing.T, base string, end int64) {
t.Helper()
writeEcxEndingAtVersion(t, base, end, needle.GetCurrentVersion())
}
func writeEcxEndingAtVersion(t *testing.T, base string, end int64, version needle.Version) {
t.Helper()
size := types.Size(1000)
offset := end - needle.GetActualSize(size, version)
entry := needle_map.ToBytes(1, types.ToOffset(offset), size)
if err := os.WriteFile(base+".ecx", entry, 0o644); err != nil {
t.Fatalf("write .ecx: %v", err)
}
}
// writeSizedDat writes a .dat of size whose superblock names the current
// needle version.
func writeSizedDat(t *testing.T, path string, size int64) {
t.Helper()
writeSizedFile(t, path, size)
f, err := os.OpenFile(path, os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if _, err := f.WriteAt([]byte{byte(needle.GetCurrentVersion())}, 0); err != nil {
t.Fatal(err)
}
}
// A re-encode of a grown .dat interrupted under an earlier encode's .vif,
// with every partial shard exactly as long as that earlier encode's full
// shards. The re-encode wrote the .ecx of the grown .dat first, so it indexes
// needles past the recorded size: the shards are not that encode's, and the
// complete .dat is reclaimed.
func TestValidateEcVolume_InterruptedReEncodeMatchingStaleLengthReclaims(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
const vid = 79
base := erasure_coding.EcShardFileName("", l.Directory, vid)
oldSourceSize := int64(20 * 1024 * 1024)
datSize := int64(60 * 1024 * 1024)
writeSizedDat(t, base+".dat", datSize)
writeEcVif(t, base, oldSourceSize)
writeEcxEndingAt(t, base, datSize)
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
writeSizedFile(t, base+erasure_coding.ToExt(i), calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount))
}
if l.validateEcVolume("", vid) {
t.Fatal("validateEcVolume trusted a stale .vif for partial shards under an .ecx of the grown .dat")
}
// The same shards under an .ecx that stays within the recorded size are
// that encode's: keep them.
writeEcxEndingAt(t, base, oldSourceSize)
if !l.validateEcVolume("", vid) {
t.Fatal("validateEcVolume dropped shards whose .ecx and length match the recorded source")
}
}
// Only the .ecx the mount opens speaks for the shards: a non-empty data-dir
// .ecx within the recorded size wins over an older shared-idx .ecx pointing
// past it, and the shards stay.
func TestValidateEcVolume_ChecksTheEcxTheMountOpens(t *testing.T) {
root := t.TempDir()
data, idx := filepath.Join(root, "data"), filepath.Join(root, "idx")
for _, d := range []string{data, idx} {
if err := os.Mkdir(d, 0o755); err != nil {
t.Fatal(err)
}
}
l := newTestDiskLocation(data)
l.IdxDirectory = idx
const vid = 80
base := erasure_coding.EcShardFileName("", data, vid)
idxBase := erasure_coding.EcShardFileName("", idx, vid)
sourceSize := int64(30 * 1024 * 1024)
writeEcVif(t, base, sourceSize)
writeEcxEndingAt(t, base, sourceSize)
writeEcxEndingAt(t, idxBase, sourceSize+20*1024*1024)
writeSizedFile(t, base+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
writeSizedDat(t, base+".dat", sourceSize+10*1024*1024)
if !l.validateEcVolume("", vid) {
t.Fatal("an .ecx the mount ignores decided against the shards")
}
// With no data-dir .ecx the mount opens the shared one, which indexes
// past the recorded size: the old rule applies and reclaims.
if err := os.Remove(base + ".ecx"); err != nil {
t.Fatal(err)
}
if l.validateEcVolume("", vid) {
t.Fatal("the shared .ecx the mount opens was not checked")
}
}
// The .ecx extent is sized with the needle version the encode's .vif records,
// as the mount reads it, not the version of the foreign .dat beside it.
func TestValidateEcVolume_SizesTheEcxWithTheEncodeVersion(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
const vid = 81
base := erasure_coding.EcShardFileName("", l.Directory, vid)
sourceSize := int64(30 * 1024 * 1024)
vi := &volume_server_pb.VolumeInfo{
Version: uint32(needle.Version2),
DatFileSize: sourceSize,
EcShardConfig: &volume_server_pb.EcShardConfig{
DataShards: uint32(erasure_coding.DataShardsCount),
ParityShards: uint32(erasure_coding.ParityShardsCount),
},
}
if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil {
t.Fatal(err)
}
// Ends exactly at the source under version 2; version 3 would put it
// 8 bytes past.
writeEcxEndingAtVersion(t, base, sourceSize, needle.Version2)
writeSizedFile(t, base+erasure_coding.ToExt(9), calculateExpectedShardSize(sourceSize, erasure_coding.DataShardsCount))
writeSizedDat(t, base+".dat", sourceSize+10*1024*1024)
if !l.validateEcVolume("", vid) {
t.Fatal("the .ecx was sized with the foreign .dat's needle version, not the encode's")
}
}
// An interrupted write leaves a torn .ecx tail; the whole entries before it
// still show the re-encode's .ecx indexing past the stale recorded size.
func TestValidateEcVolume_TornEcxTailStillReclaimsReEncode(t *testing.T) {
l := newTestDiskLocation(t.TempDir())
const vid = 82
base := erasure_coding.EcShardFileName("", l.Directory, vid)
oldSourceSize := int64(20 * 1024 * 1024)
datSize := int64(60 * 1024 * 1024)
writeSizedDat(t, base+".dat", datSize)
writeEcVif(t, base, oldSourceSize)
writeEcxEndingAt(t, base, datSize)
f, err := os.OpenFile(base+".ecx", os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write([]byte{1, 2, 3}); err != nil {
t.Fatal(err)
}
f.Close()
for i := 0; i < erasure_coding.TotalShardsCount; i++ {
writeSizedFile(t, base+erasure_coding.ToExt(i), calculateExpectedShardSize(oldSourceSize, erasure_coding.DataShardsCount))
}
if l.validateEcVolume("", vid) {
t.Fatal("a torn .ecx tail hid the entries past the stale recorded size")
}
}
+7 -12
View File
@@ -109,25 +109,20 @@ func FindDatFileSize(shard0FileName, indexBaseFileName string) (datSize int64, e
// when all needles are deleted (see issue #7748).
datSize = int64(super_block.SuperBlockSize)
extent, err := EcxNeedleExtent(indexBaseFileName, version)
if extent > datSize {
datSize = extent
}
return
}
// EcxNeedleExtent returns where the furthest live needle indexed by
// indexBaseFileName.ecx ends in the source .dat, or 0 when it indexes none.
func EcxNeedleExtent(indexBaseFileName string, version needle.Version) (extent int64, err error) {
err = iterateEcxFile(indexBaseFileName, func(key types.NeedleId, offset types.Offset, size types.Size) error {
if size.IsDeleted() {
return nil
}
if end := offset.ToActualOffset() + needle.GetActualSize(size, version); end > extent {
extent = end
entryStopOffset := offset.ToActualOffset() + needle.GetActualSize(size, version)
if datSize < entryStopOffset {
datSize = entryStopOffset
}
return nil
})
return
}