mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* feat: weed fix -verify to resync past damaged regions in .dat Plain `weed fix` walks .dat by trusting each needle header, so a damaged region in the middle loses or misindexes everything after it, and a torn or garbage tail ends up in the index and keeps the volume read-only. -verify reads every needle, checks structure and CRC32, and on a failure searches forward at needle alignment for the next verifiable needle. Each skipped region is reported as zero-fill / garbage / garbage+zeros with its length, zero windows and the fid of the needle that was hit. The index is rebuilt from verified needles only (old one kept as .idx.bak); -truncateTail cuts trailing garbage so the load-time integrity check passes, -dryRun only reports. Works with the 5BytesOffset build. * feat: add weed fix.verify, a read-only check of .dat files Runs the same needle/CRC verification and resync scan as `weed fix -verify` but never writes: no .idx rebuild, no truncation. Takes folders and/or .dat files, filters with -collection / -volumeId, prints the damaged regions (optionally to -report) and exits 0 when clean, 3 when damage was found and 1 when a file could not be verified. The scan options are shared with `weed fix -verify`. * feat: weed fix -compact, verify and compact a damaged volume in one pass -compact implies -verify. While the .dat is scanned, every verified needle gets an index entry, and from the first damaged region in the middle of the file the needle bytes are streamed into a new .cpd as well (the intact prefix before it is copied as one block). The result is a .dat without the damaged regions and an append-ordered .idx that matches it exactly, so a full volume scrub no longer complains about the .dat size. The compaction revision is bumped like a vacuum does. A volume without damage is left untouched, and damage only at the tail is just cut off in place, so neither costs a .dat copy. The old .idx is kept as .idx.bak and the old .dat as .dat.bak (-deleteOriginal removes it). The free space needed for the new .dat is checked before anything is written, a failing swap is rolled back, and progress is printed every 30s. * refactor: reuse backend, super block and throttler code in weed fix -compact - create the .cpd with backend.CreateVolumeFile and preallocate the bound of the new .dat; the result is truncated to its real length at the end - read the super block with super_block.ReadSuperBlock (also in the verifier) and write the bumped compaction revision with SuperBlock.Bytes() - throttle the .dat writes with util.WriteThrottler (-compactionMBps) - fsync the directory before and after swapping the new files in ReadSuperBlock cannot read a super block with extra data, so such volumes are rejected with its error instead of being handled by a hand-written parser. * refactor: drop helpers that duplicate existing code in weed fix -compact / fix.verify - util.FsyncDir instead of a local fsyncDir - io.NewOffsetWriter instead of a hand-written WriterAt adapter; the throttle now sits in one small writer wrapper used for both the prefix copy (via io.CopyBuffer) and the streamed needles, replacing the manual copy loop - needle.NewVolumeId instead of strconv for volume ids parsed from file names * fix: resync in weed fix -verify must not accept payload-less look-alikes After damage, a few bytes of a needle's tail followed by the next record's header could parse as a payload-less needle and be confirmed only because the file ended right after it, so a made-up key got into the index and swallowed the real delete record behind it. A payload-less candidate is now accepted without a verifiable successor only if it is a size-0 tombstone ending exactly at the end of the file (or, with a set timestamp, leaving less than a header); a set but implausible v3 timestamp rejects it. Anything else needs the next needle to verify. * test: recovery integration tests for damaged .dat heads (#5674, #12914) - zero-filled head (aligned and cut next record): all survivors indexed, region reported as zero-fill, trailing tombstone kept - plain weed fix stops at the first bad header (#12914 item 1) while -verify recovers the needles behind it - a needle rewritten after a damaged region is indexed at its newest copy - a zeroed superblock fails with an explicit unsupported-version error and fix.verify counts it as not verifiable (exit 1) - v1/v2 needle layouts verify cleanly * fix: reject a super block extra in fix -verify A super block extra describes an erasure-coded layout; the .dat behind it was re-striped into .ecXX shards and is not a plain needle file. Scanning it as one silently produced damage reports instead of telling the operator the file is out of scope. Return an explicit error instead. * fix: guard fix -verify/-compact against pending compaction commits and -dir.idx - refuse to start while a .cpc marker exists: an interrupted vacuum commit is pending and the volume server must reconcile it first (roll forward/back); writing a rebuilt .idx or new .cpd/.cpx over that decision would race it - clear a stale .cpc after a completed swap so it can never be rolled forward later (defensive; the start guard already refuses this state) - spell out in the help and print after a rebuild that the index is written next to the .dat: with a separate -dir.idx directory the .idx must be moved there and any stale .ldb dropped - tests: refusal leaves the marker and writes no .idx; a completed swap clears a marker that slipped past the guard * refactor: narrow this change to weed fix -verify Drop weed fix.verify and weed fix -compact from this change; they follow in their own pull requests. -report, -windowMB and -zeroWindow go with them: the scan uses fixed windows and prints its report to stdout. * fix: weed fix -verify: address review findings - -maxNeedleSizeMB limits only guesses made while resynchronising; a record reached at a known boundary may be as large as the file allows - a v2/v3 record whose parsed fields do not add up to its size, or a live record without data, is damage: a zero fill over the data length used to pass as an empty file because the CRC is only checked when there is data - a stamped v3 delete record found after damage stands on its own when its time is believable, not older than the last verified record and followed by zero padding, so a delete before a damaged tail is not lost - a read error while searching for the next needle fails the run instead of ending the scan and treating the rest as a garbage tail - keys whose newest record is damaged while an older copy is indexed are reported as stale-version warnings - the rebuilt index is staged as .idx.tmp and swapped in when complete; a stale .ldb next to it is removed so the volume server rebuilds it - -ignoreError reports a volume that cannot be verified and goes on - -truncateTail does not cut a tail it could not read and removes a partial tail backup - volume ids are parsed as uint32 - the test fixture stamps every record the way the volume server does * fix: weed fix -verify: prove deletes found after damage, swap the index safely - a delete record found while resynchronising must prove itself: a v3 one needs a believable time not older than the last verified record and zero padding (every v3 writer stamps deletes); a v1/v2 one needs the following records to reach data that passes its CRC, or the exact end of the file. Stray bytes in a zero-filled region used to pass as deletes of live keys. - the rebuilt index is fsynced before the swap, the previous one is kept as a hard link, and the new one replaces it in one rename, so a live .idx exists at every moment - .sdx and .rdb caches are removed with the .ldb - -verify exits non-zero when it found damage, like plain fix and -verifyCrc - with -ignoreError a file name whose volume id does not fit uint32 is reported and the batch goes on - the help and the printed hint say that a volume server prefers an .idx next to the .dat over the one in -dir.idx * fix: reject weed fix flag combinations -verify cannot honour -verify -remoteFile skipped an explicit .dat and reported success, -dryRun and -truncateTail were silently ignored without -verify, and -dryRun -ecx still rebuilt EC indexes. Check the combinations before any file is touched. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: apply -volumeId before rejecting an out-of-range volume file name With -volumeId set, an unrelated file such as 4294967296.dat aborted the run before the filter could skip it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: check the data length before reading a record body in fix -verify A damaged size field at a known record boundary made the scan allocate and read a body of that size before rejecting it. Check that the data length after the header fits the record first, as the resync probe already does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: accept a v1/v2 delete chain that reaches the end of the file on its last probe Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep an implausible needle timestamp out of the fix -verify resync baseline The data CRC does not cover the v3 timestamp, so a corrupted one passed and then rejected every genuine delete record found after later damage. Report it as a warning instead of using it as the lower bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: stop fix -verify on a read error at a known record boundary An EIO while reading a record was treated like damaged bytes: the scan resynchronised past the unread record and the rebuilt index dropped it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: sync the fix -verify tail backup before truncating the .dat A crash right after the truncate could persist it before the backup's data or directory entry, losing the cut bytes from both files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: let fix -verify -truncateTail retry when a tail backup already exists After a backup succeeded and the truncate failed, the next run hit the existing backup and could not get past O_EXCL. Keep the first backup and save the tail under a new name, as the index backup does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: drop stale index caches before fix -verify swaps in the new index Removing them after the rename left a window where a crash paired the new .idx with the old .ldb, whose newer LOG skips the replay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: pin fix -verify fixtures to needle version 3 -verify reads v1 to v3 records, so its fixtures should not follow the build's current needle version. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: refuse fix -verify on remote-tiered volumes A remote-tiered volume is read from its remote .dat through the existing .idx, so rebuilding that index from a local .dat would point it at the wrong bytes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: pick a free backup name when fix -verify retries within one second backupName fell back to path.bak.<unix time> without checking it, so a second retry in the same second reused that name and the exclusive create (or the .idx hard link) failed. Add a .<n> suffix until the name is free. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: refuse fix -verify when the volume info cannot be read An unreadable or unparsable .vif may name a remote tier, so treat it like one and keep the existing index. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: pass weed fix -verify options explicitly * feat: move weed fix -verify into a weed fix.recover command * docs: weed fix.recover help, point weed fix at it * fix: keep the volume file helpers below runFix Leaves the region between VisitNeedle and runFix as on master. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: build fix.recover fixtures at needle version 3 fix.recover reads needle versions 1 to 3, so its tests must not follow GetCurrentVersion; writeFixTestVolume now takes the version. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: whitefox <whitefox@mayflower.work> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
434 lines
15 KiB
Go
434 lines
15 KiB
Go
package command
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
|
)
|
|
|
|
type verifyFixtureNeedle struct {
|
|
id uint64
|
|
offset int64
|
|
disk int64
|
|
}
|
|
|
|
// buildVerifyFixture writes count needles with ids 1..count, then a delete
|
|
// record for id 1, and returns the .dat path with the layout of every record.
|
|
func buildVerifyFixture(t *testing.T, count int) (string, []verifyFixtureNeedle) {
|
|
t.Helper()
|
|
datName := filepath.Join(t.TempDir(), "1.dat")
|
|
version := needle.Version3
|
|
|
|
df, err := os.OpenFile(datName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
datBackend := backend.NewDiskFile(df)
|
|
defer datBackend.Close()
|
|
sb := super_block.SuperBlock{
|
|
Version: version,
|
|
ReplicaPlacement: &super_block.ReplicaPlacement{},
|
|
Ttl: &needle.TTL{},
|
|
}
|
|
if _, err := datBackend.WriteAt(sb.Bytes(), 0); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
var layout []verifyFixtureNeedle
|
|
var lastAppendAtNs uint64
|
|
for i := 1; i <= count; i++ {
|
|
n := new(needle.Needle)
|
|
n.Id = types.Uint64ToNeedleId(uint64(i))
|
|
n.Cookie = types.Uint32ToCookie(uint32(0x1000 + i))
|
|
n.Data = make([]byte, 1000+i*37)
|
|
if _, err := rand.Read(n.Data); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
n.Checksum = needle.NewCRC(n.Data)
|
|
// stamp every record the way the volume server does
|
|
n.UpdateAppendAtNs(lastAppendAtNs)
|
|
lastAppendAtNs = n.AppendAtNs
|
|
offset, _, actual, err := n.Append(datBackend, version)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
layout = append(layout, verifyFixtureNeedle{uint64(i), int64(offset), actual})
|
|
}
|
|
del := new(needle.Needle)
|
|
del.Id = types.Uint64ToNeedleId(1)
|
|
del.UpdateAppendAtNs(lastAppendAtNs)
|
|
offset, _, actual, err := del.Append(datBackend, version)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
layout = append(layout, verifyFixtureNeedle{1, int64(offset), actual})
|
|
if err := datBackend.Sync(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return datName, layout
|
|
}
|
|
|
|
func runVerify(t *testing.T, datName string) (*datVerifySummary, []datAnomaly, map[uint64]bool) {
|
|
t.Helper()
|
|
seen := map[uint64]bool{}
|
|
sum, anomalies, err := verifyDatFile(datName, 1, datVerifyOptions{window: 64 << 10, zeroWindow: 512}, func(n *needle.Needle, offset int64) {
|
|
if n.Size.IsValid() {
|
|
seen[uint64(n.Id)] = true
|
|
}
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return sum, anomalies, seen
|
|
}
|
|
|
|
func patchDat(t *testing.T, datName string, off int64, data []byte) {
|
|
t.Helper()
|
|
f, err := os.OpenFile(datName, os.O_RDWR, 0644)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer f.Close()
|
|
if _, err := f.WriteAt(data, off); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func TestVerifyDatFileClean(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 20)
|
|
sum, anomalies, seen := runVerify(t, datName)
|
|
if len(anomalies) != 0 || sum.Needles != 20 || sum.Tombstones != 1 || len(seen) != 20 {
|
|
t.Fatalf("clean volume: needles=%d tombstones=%d anomalies=%v", sum.Needles, sum.Tombstones, anomalies)
|
|
}
|
|
last := layout[len(layout)-1]
|
|
if sum.CleanEnd != last.offset+last.disk || sum.TailGarbage {
|
|
t.Fatalf("clean end %d, want %d", sum.CleanEnd, last.offset+last.disk)
|
|
}
|
|
}
|
|
|
|
func TestVerifyDatFileZeroFilledMiddle(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 20)
|
|
// zero needles 5..7 completely, like a lost block range
|
|
start := layout[4].offset
|
|
end := layout[6].offset + layout[6].disk
|
|
patchDat(t, datName, start, make([]byte, end-start))
|
|
|
|
sum, anomalies, seen := runVerify(t, datName)
|
|
if len(anomalies) != 1 || anomalies[0].Kind != "zero-fill" || anomalies[0].Offset != start || anomalies[0].Length != end-start {
|
|
t.Fatalf("want one zero-fill region [%d,%d), got %+v", start, end, anomalies)
|
|
}
|
|
for id := uint64(1); id <= 20; id++ {
|
|
if want := id < 5 || id > 7; seen[id] != want {
|
|
t.Errorf("needle %d: seen=%v want %v", id, seen[id], want)
|
|
}
|
|
}
|
|
if sum.ZeroBytes != end-start || sum.TailGarbage {
|
|
t.Errorf("zero bytes %d, tail garbage %v", sum.ZeroBytes, sum.TailGarbage)
|
|
}
|
|
}
|
|
|
|
func TestVerifyDatFileFlippedPayloadByte(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 20)
|
|
patchDat(t, datName, layout[9].offset+types.NeedleHeaderSize+100, []byte{0xde, 0xad})
|
|
|
|
_, anomalies, seen := runVerify(t, datName)
|
|
if len(anomalies) != 1 || !strings.Contains(anomalies[0].Detail, "invalid CRC") || !strings.Contains(anomalies[0].Detail, "fid:1,") {
|
|
t.Fatalf("want one CRC anomaly naming the fid, got %+v", anomalies)
|
|
}
|
|
if seen[10] || len(seen) != 19 {
|
|
t.Fatalf("needle 10 must be dropped and the other 19 kept, seen=%d", len(seen))
|
|
}
|
|
}
|
|
|
|
func TestVerifyDatFileCorruptHeaderSizeDoesNotSwallowNeighbours(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 20)
|
|
// inflate needle 3's size so it appears to cover several following needles
|
|
badSize := make([]byte, 4)
|
|
badSize[2], badSize[3] = 0x40, 0x00 // 16384
|
|
patchDat(t, datName, layout[2].offset+types.CookieSize+types.NeedleIdSize, badSize)
|
|
|
|
_, anomalies, seen := runVerify(t, datName)
|
|
if len(anomalies) != 1 {
|
|
t.Fatalf("want one anomaly, got %+v", anomalies)
|
|
}
|
|
if seen[3] || len(seen) != 19 {
|
|
t.Fatalf("only needle 3 may be lost, seen=%d", len(seen))
|
|
}
|
|
}
|
|
|
|
func TestVerifyDatFileRandomGarbageRegion(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 20)
|
|
start := layout[11].offset + 10 // misaligned start inside needle 12
|
|
end := layout[13].offset + layout[13].disk
|
|
junk := make([]byte, end-start)
|
|
if _, err := rand.Read(junk); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
patchDat(t, datName, start, junk)
|
|
|
|
_, anomalies, seen := runVerify(t, datName)
|
|
if len(anomalies) != 1 || anomalies[0].Kind != "garbage" {
|
|
t.Fatalf("want one garbage region, got %+v", anomalies)
|
|
}
|
|
for id := uint64(1); id <= 20; id++ {
|
|
if want := id < 12 || id > 14; seen[id] != want {
|
|
t.Errorf("needle %d: seen=%v want %v", id, seen[id], want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestVerifyDatFileTornTailAndTruncate(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 20)
|
|
// cut the file in the middle of the last data needle's body, then tack on zeros
|
|
cut := layout[19].offset + layout[19].disk/2
|
|
if err := os.Truncate(datName, cut); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f, err := os.OpenFile(datName, os.O_WRONLY|os.O_APPEND, 0644)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f.Write(make([]byte, 5000))
|
|
f.Close()
|
|
|
|
sum, anomalies, seen := runVerify(t, datName)
|
|
if !sum.TailGarbage || sum.CleanEnd != layout[19].offset || len(seen) != 19 {
|
|
t.Fatalf("tail garbage=%v cleanEnd=%d (want %d) seen=%d anomalies=%+v", sum.TailGarbage, sum.CleanEnd, layout[19].offset, len(seen), anomalies)
|
|
}
|
|
if err := truncateDatTail(datName, sum.CleanEnd); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := os.Stat(datName + ".tail." + "0.bak"); err == nil {
|
|
t.Fatal("unexpected backup name")
|
|
}
|
|
if matches, _ := filepath.Glob(datName + ".tail.*.bak"); len(matches) != 1 {
|
|
t.Fatalf("the partially written needle should have been saved, got %v", matches)
|
|
}
|
|
sum, anomalies, _ = runVerify(t, datName)
|
|
if sum.TailGarbage || len(anomalies) != 0 || sum.CleanEnd != layout[19].offset {
|
|
t.Fatalf("after truncate: %+v %+v", sum, anomalies)
|
|
}
|
|
}
|
|
|
|
// TestFixVerifyLoadsWritable corrupts a volume in the middle and at the tail,
|
|
// rebuilds it with fix.recover, and loads it with the real volume code to
|
|
// make sure the load-time integrity check no longer flips it read-only.
|
|
func TestFixVerifyLoadsWritable(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 30)
|
|
dir := filepath.Dir(datName)
|
|
|
|
start := layout[9].offset
|
|
end := layout[11].offset + layout[11].disk
|
|
patchDat(t, datName, start, make([]byte, end-start))
|
|
cut := layout[29].offset + layout[29].disk/2
|
|
if err := os.Truncate(datName, cut); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// a stale index left over from before the damage
|
|
if err := os.WriteFile(filepath.Join(dir, "1.idx"), make([]byte, 16*5), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if err := recoverOneVolume(dir, "1", 1, filepath.Join(dir, "1.idx"), recoverOptions{includeDeleted: true, truncateTail: true, maxNeedleSizeMB: 64}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if _, err := os.Stat(filepath.Join(dir, "1.idx.bak")); err != nil {
|
|
t.Errorf("old index should have been kept: %v", err)
|
|
}
|
|
v, err := storage.NewVolume(dir, dir, "", 1, storage.NeedleMapInMemory, nil, nil, 0, needle.Version3, 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("load volume: %v", err)
|
|
}
|
|
defer v.Close()
|
|
// IsReadOnly needs a disk location the test volume does not have, so run
|
|
// the same load-time integrity check the volume server uses to flip it.
|
|
idxFile, err := os.Open(filepath.Join(dir, "1.idx"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer idxFile.Close()
|
|
if _, err := storage.CheckVolumeDataIntegrity(v, idxFile); err != nil {
|
|
t.Fatalf("integrity check would mark the volume read-only: %v", err)
|
|
}
|
|
if _, errs := v.ScrubIndex(); len(errs) != 0 {
|
|
t.Fatalf("index scrub: %v", errs)
|
|
}
|
|
// 29 needles were written before the torn one; 3 were zeroed
|
|
if got := v.FileCount(); got != 26 {
|
|
t.Errorf("file count %d, want 26", got)
|
|
}
|
|
}
|
|
|
|
// A file that is legitimately all zeros is an ordinary needle: it has a real
|
|
// header (non-zero id) and a CRC, so it must verify, and it must not be
|
|
// mistaken for damage or swallowed when a damaged region sits next to it.
|
|
func TestVerifyDatFileLegitimateZeroPayload(t *testing.T) {
|
|
datName := filepath.Join(t.TempDir(), "1.dat")
|
|
version := needle.Version3
|
|
df, err := os.OpenFile(datName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b := backend.NewDiskFile(df)
|
|
defer b.Close()
|
|
sb := super_block.SuperBlock{Version: version, ReplicaPlacement: &super_block.ReplicaPlacement{}, Ttl: &needle.TTL{}}
|
|
if _, err := b.WriteAt(sb.Bytes(), 0); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var layout []verifyFixtureNeedle
|
|
for i := 1; i <= 6; i++ {
|
|
n := new(needle.Needle)
|
|
n.Id = types.Uint64ToNeedleId(uint64(i))
|
|
n.Cookie = types.Uint32ToCookie(7)
|
|
n.Data = make([]byte, 100000) // i == 2, 3, 5: stays all zeros
|
|
if i != 2 && i != 3 && i != 5 {
|
|
rand.Read(n.Data)
|
|
}
|
|
n.Checksum = needle.NewCRC(n.Data)
|
|
off, _, actual, err := n.Append(b, version)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
layout = append(layout, verifyFixtureNeedle{uint64(i), int64(off), actual})
|
|
}
|
|
_ = b.Sync()
|
|
|
|
sum, anomalies, seen := runVerify(t, datName)
|
|
if len(anomalies) != 0 || sum.Needles != 6 || len(seen) != 6 {
|
|
t.Fatalf("zero-payload needles must verify: needles=%d anomalies=%+v", sum.Needles, anomalies)
|
|
}
|
|
|
|
// destroy needle 4 (random data) between two zero-payload needles
|
|
patchDat(t, datName, layout[3].offset, make([]byte, layout[3].disk))
|
|
sum, anomalies, seen = runVerify(t, datName)
|
|
if len(anomalies) != 1 || anomalies[0].Kind != "zero-fill" || anomalies[0].Offset != layout[3].offset || anomalies[0].Length != layout[3].disk {
|
|
t.Fatalf("want exactly needle 4 reported as zero-fill, got %+v", anomalies)
|
|
}
|
|
if len(seen) != 5 || seen[4] || !seen[2] || !seen[3] || !seen[5] {
|
|
t.Fatalf("zero-payload neighbours must survive: seen=%v", seen)
|
|
}
|
|
}
|
|
|
|
// super_block.ReadSuperBlock cannot read a super block with extra data (it parses
|
|
// zeros as protobuf), so the volume server cannot load such a volume either. The
|
|
// tools must reject it cleanly instead of guessing at the layout.
|
|
func TestSuperBlockExtraIsRejectedCleanly(t *testing.T) {
|
|
datName, _ := buildVerifyFixture(t, 5)
|
|
orig, err := os.ReadFile(datName)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sb := super_block.SuperBlock{
|
|
Version: needle.Version3, ReplicaPlacement: &super_block.ReplicaPlacement{}, Ttl: &needle.TTL{},
|
|
Extra: &master_pb.SuperBlockExtra{ErasureCoding: &master_pb.SuperBlockExtra_ErasureCoding{Data: 10, Parity: 4}},
|
|
}
|
|
if err := os.WriteFile(datName, append(sb.Bytes(), orig[8:]...), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, _, err := verifyDatFile(datName, 1, datVerifyOptions{}, func(*needle.Needle, int64) {}); err == nil || !strings.Contains(err.Error(), "super block extra") {
|
|
t.Fatalf("want a clear super block error, got %v", err)
|
|
}
|
|
}
|
|
|
|
// Garbage over the header of the last data needle leaves a few payload-less
|
|
// bytes (the needle's tail and the delete record behind it) that must not be
|
|
// mistaken for a needle, while the real delete record must still be found.
|
|
func TestVerifyDatFileNoFalsePositiveAfterDamagedLastHeader(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 20)
|
|
garbage := make([]byte, 16)
|
|
for i := range garbage {
|
|
garbage[i] = 0xa5
|
|
}
|
|
patchDat(t, datName, layout[19].offset, garbage)
|
|
|
|
sum, anomalies, seen := runVerify(t, datName)
|
|
for id := range seen {
|
|
if id < 1 || id > 19 {
|
|
t.Errorf("needle id %d does not exist in the volume", id)
|
|
}
|
|
}
|
|
if len(seen) != 19 || seen[20] {
|
|
t.Fatalf("want needles 1..19, got %d (20 seen: %v)", len(seen), seen[20])
|
|
}
|
|
if sum.Tombstones != 1 || sum.TailGarbage || len(anomalies) != 1 {
|
|
t.Errorf("the delete record behind the damage must survive: tombstones=%d tail=%v anomalies=%+v", sum.Tombstones, sum.TailGarbage, anomalies)
|
|
}
|
|
}
|
|
|
|
// A retry after a failed truncation finds the first tail backup in place; it
|
|
// keeps it and saves the tail again under a new name.
|
|
func TestTruncateDatTailKeepsEarlierBackup(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 3)
|
|
cleanEnd := layout[3].offset + layout[3].disk
|
|
f, err := os.OpenFile(datName, os.O_WRONLY|os.O_APPEND, 0644)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f.Write([]byte("not a needle"))
|
|
f.Close()
|
|
first := fmt.Sprintf("%s.tail.%d.bak", datName, cleanEnd)
|
|
if err := os.WriteFile(first, []byte("earlier"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
captureStdout(t, func() {
|
|
if err := truncateDatTail(datName, cleanEnd); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
})
|
|
if b, _ := os.ReadFile(first); string(b) != "earlier" {
|
|
t.Fatalf("the earlier backup was overwritten: %q", b)
|
|
}
|
|
if matches, _ := filepath.Glob(first + ".*"); len(matches) != 1 {
|
|
t.Fatalf("want a second backup next to %s, got %v", first, matches)
|
|
}
|
|
if st, _ := os.Stat(datName); st.Size() != cleanEnd {
|
|
t.Fatalf("size %d, want %d", st.Size(), cleanEnd)
|
|
}
|
|
}
|
|
|
|
func TestTruncateDatTailRetriesInOneSecond(t *testing.T) {
|
|
datName, layout := buildVerifyFixture(t, 3)
|
|
cleanEnd := layout[3].offset + layout[3].disk
|
|
first := fmt.Sprintf("%s.tail.%d.bak", datName, cleanEnd)
|
|
now := time.Now().Unix()
|
|
for _, name := range []string{first, fmt.Sprintf("%s.%d", first, now), fmt.Sprintf("%s.%d", first, now+1)} {
|
|
if err := os.WriteFile(name, []byte("earlier"), 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
for retry := 0; retry < 3; retry++ {
|
|
f, err := os.OpenFile(datName, os.O_WRONLY|os.O_APPEND, 0644)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f.Write([]byte("not a needle"))
|
|
f.Close()
|
|
captureStdout(t, func() {
|
|
if err := truncateDatTail(datName, cleanEnd); err != nil {
|
|
t.Fatalf("retry %d: %v", retry, err)
|
|
}
|
|
})
|
|
}
|
|
matches, _ := filepath.Glob(first + ".*")
|
|
if len(matches) != 5 {
|
|
t.Fatalf("want 5 backups next to %s, got %v", first, matches)
|
|
}
|
|
for _, name := range []string{first, fmt.Sprintf("%s.%d", first, now), fmt.Sprintf("%s.%d", first, now+1)} {
|
|
if b, _ := os.ReadFile(name); string(b) != "earlier" {
|
|
t.Fatalf("%s was overwritten: %q", name, b)
|
|
}
|
|
}
|
|
}
|