From dcce121d95a15f76510d336759f3b18f1dbefb40 Mon Sep 17 00:00:00 2001 From: Konstantin Lebedev <9497591+kmlebedev@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:24:05 +0500 Subject: [PATCH] weed fix.recover: recover needles past damaged .dat regions (#13002) * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * fix: pick a free backup name when fix -verify retries within one second backupName fell back to path.bak. 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 . suffix until the name is free. Co-Authored-By: Claude Opus 5.5 * 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 * 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 * 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 --------- Co-authored-by: whitefox Co-authored-by: Chris Lu Co-authored-by: Claude Opus 5.5 --- weed/command/command.go | 1 + weed/command/compact_test.go | 4 +- weed/command/fix.go | 110 ++- weed/command/fix_recover.go | 98 +++ weed/command/fix_recover_test.go | 109 +++ weed/command/fix_test.go | 17 +- weed/command/fix_verify.go | 836 ++++++++++++++++++++ weed/command/fix_verify_integration_test.go | 253 ++++++ weed/command/fix_verify_review_test.go | 528 +++++++++++++ weed/command/fix_verify_test.go | 433 ++++++++++ 10 files changed, 2339 insertions(+), 50 deletions(-) create mode 100644 weed/command/fix_recover.go create mode 100644 weed/command/fix_recover_test.go create mode 100644 weed/command/fix_verify.go create mode 100644 weed/command/fix_verify_integration_test.go create mode 100644 weed/command/fix_verify_review_test.go create mode 100644 weed/command/fix_verify_test.go diff --git a/weed/command/command.go b/weed/command/command.go index 2370ad81af..32d204c548 100644 --- a/weed/command/command.go +++ b/weed/command/command.go @@ -30,6 +30,7 @@ var Commands = []*Command{ cmdFilerSynchronize, cmdFilerSyncVerify, cmdFix, + cmdFixRecover, cmdFuse, cmdIam, cmdImage, diff --git a/weed/command/compact_test.go b/weed/command/compact_test.go index d1f66a065d..6d640006fa 100644 --- a/weed/command/compact_test.go +++ b/weed/command/compact_test.go @@ -102,7 +102,7 @@ func TestCompactDataMethodSkipsUnreadableRecord(t *testing.T) { t.Run(tc.name, func(t *testing.T) { for method, want := range map[string][]uint64{"data": tc.wantData, "index": tc.wantIndex} { dir := t.TempDir() - base, offsets := writeFixTestVolume(t, dir, 5) + base, offsets := writeFixTestVolume(t, dir, 5, needle.GetCurrentVersion()) doFixOneVolume(dir, "fix_7", "fix", 7, true) tc.corrupt(t, base, offsets) @@ -122,7 +122,7 @@ func TestCompactDataMethodSkipsUnreadableRecord(t *testing.T) { func TestCompactFailureLeavesNoOutput(t *testing.T) { dir := t.TempDir() - base, _ := writeFixTestVolume(t, dir, 5) + base, _ := writeFixTestVolume(t, dir, 5, needle.GetCurrentVersion()) doFixOneVolume(dir, "fix_7", "fix", 7, true) if err := os.Mkdir(base+".cpd", 0755); err != nil { t.Fatal(err) diff --git a/weed/command/fix.go b/weed/command/fix.go index 5b3c7de3cc..d118ff23a3 100644 --- a/weed/command/fix.go +++ b/weed/command/fix.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "io/fs" + "math" "os" "path" "sort" @@ -34,7 +35,7 @@ var cmdFix = &Command{ Long: `Fix runs the SeaweedFS fix command on local dat files ( or remote files) or whole folders to re-create the index .idx file. If fixing remote files, you need to synchronize master.toml to the same directory on the current node as on the master node. You Need to stop the volume server when running this command. Use -ecx to rebuild a lost EC index (.ecx) — and the .vif when missing — from the local .ec## shards. - On a damaged .dat, fix indexes only the needles before the first unreadable header or a record cut off by the end of the file, and exits non-zero; repair from a replica, or run fix on a copy, before compacting or loading the volume. + On a damaged .dat, fix indexes only the needles before the first unreadable header or a record cut off by the end of the file, and exits non-zero; repair from a replica, or run fix on a copy, before compacting or loading the volume. To recover the needles after the damage, use "weed fix.recover". With -ignoreError, fix keeps going and writes what it could index, but still exits non-zero if any volume failed. With -verifyCrc, fix also reads every needle, indexes the ones whose data fails its CRC check as deleted, and exits non-zero if it found any. `, @@ -112,27 +113,10 @@ func (scanner *VolumeFileScanner4Fix) VisitNeedle(n *needle.Needle, offset int64 func runFix(cmd *Command, args []string) bool { for _, arg := range args { - basePath, f := path.Split(util.ResolvePath(arg)) - if util.FolderExists(arg) { - basePath = arg - f = "" - } - - files := []fs.DirEntry{} - if f == "" { - fileInfo, err := os.ReadDir(basePath) - if err != nil { - fmt.Println(err) - return false - } - files = fileInfo - } else { - fileInfo, err := os.Stat(arg) - if err != nil { - fmt.Println(err) - return false - } - files = []fs.DirEntry{fs.FileInfoToDirEntry(fileInfo)} + basePath, files, err := listVolumeFiles(arg) + if err != nil { + fmt.Println(err) + return false } ext := ".dat" @@ -143,29 +127,19 @@ func runFix(cmd *Command, args []string) bool { } for _, file := range files { - if !strings.HasSuffix(file.Name(), ext) { - continue - } - if *fixVolumeCollection != "" { - if !strings.HasPrefix(file.Name(), *fixVolumeCollection+"_") { + vf, ok, parseErr := selectVolumeFile(file.Name(), ext, *fixVolumeCollection, *fixVolumeId) + if parseErr != nil { + fmt.Printf("Failed to parse volume id from %s: %v\n", vf.baseFileName, parseErr) + if *fixIgnoreError { + SetCommandExitStatus(1) continue } - } - baseFileName := file.Name()[:len(file.Name())-4] - collection, volumeIdStr := "", baseFileName - if sepIndex := strings.LastIndex(baseFileName, "_"); sepIndex > 0 { - collection = baseFileName[:sepIndex] - volumeIdStr = baseFileName[sepIndex+1:] - } - volumeId, parseErr := strconv.ParseInt(volumeIdStr, 10, 64) - if parseErr != nil { - fmt.Printf("Failed to parse volume id from %s: %v\n", baseFileName, parseErr) return false } - if *fixVolumeId != 0 && *fixVolumeId != volumeId { + if !ok { continue } - doFixOneVolume(basePath, baseFileName, collection, volumeId, *fixIncludeDeleted) + doFixOneVolume(basePath, vf.baseFileName, vf.collection, vf.volumeId, *fixIncludeDeleted) } if *fixGenerateEcx { @@ -177,6 +151,64 @@ func runFix(cmd *Command, args []string) bool { return true } +// listVolumeFiles returns the folder and the entries one command line +// argument names: every entry of a folder, or the single file given. +func listVolumeFiles(arg string) (basePath string, files []fs.DirEntry, err error) { + basePath, f := path.Split(util.ResolvePath(arg)) + if util.FolderExists(arg) { + files, err = os.ReadDir(arg) + return arg, files, err + } + if f == "" { + files, err = os.ReadDir(basePath) + return basePath, files, err + } + fileInfo, err := os.Stat(arg) + if err != nil { + return basePath, nil, err + } + return basePath, []fs.DirEntry{fs.FileInfoToDirEntry(fileInfo)}, nil +} + +// volumeFile is a volume file name split into its parts. +type volumeFile struct { + baseFileName string + collection string + volumeId int64 +} + +// selectVolumeFile parses a [collection_]id file name. ok is false when +// the name does not end in ext or the collection or volumeId filter (when +// set) excludes it; the filter applies before the range check, so a file it +// excludes is never an error. An id that is not a number or does not fit a +// uint32 is an error. +func selectVolumeFile(name, ext, collection string, volumeId int64) (vf volumeFile, ok bool, err error) { + if !strings.HasSuffix(name, ext) { + return vf, false, nil + } + if collection != "" && !strings.HasPrefix(name, collection+"_") { + return vf, false, nil + } + vf.baseFileName = name[:len(name)-len(ext)] + idStr := vf.baseFileName + if sepIndex := strings.LastIndex(vf.baseFileName, "_"); sepIndex > 0 { + vf.collection = vf.baseFileName[:sepIndex] + idStr = vf.baseFileName[sepIndex+1:] + } + id, err := strconv.ParseInt(idStr, 10, 64) + if err == nil && volumeId != 0 && volumeId != id { + return vf, false, nil + } + if err == nil && (id < 0 || id > math.MaxUint32) { + err = fmt.Errorf("volume id %d out of range", id) + } + if err != nil { + return vf, false, err + } + vf.volumeId = id + return vf, true, nil +} + // fixEcxFromShardsInDir finds EC volumes in files (identified by their .ec00 // data shard) and regenerates the .ecx (and .vif when missing) for each, // honoring the -collection and -volumeId filters. diff --git a/weed/command/fix_recover.go b/weed/command/fix_recover.go new file mode 100644 index 0000000000..9ef6da4ade --- /dev/null +++ b/weed/command/fix_recover.go @@ -0,0 +1,98 @@ +package command + +import ( + "fmt" + "path" + + "github.com/seaweedfs/seaweedfs/weed/glog" +) + +func init() { + cmdFixRecover.Run = runFixRecover // break init cycle +} + +var cmdFixRecover = &Command{ + UsageLine: "fix.recover [-volumeId=234] [-collection=bigData] [-dryRun] [-truncateTail] /data/dir | /data/dir/bigData_234.dat ...", + Short: "recover the needles that survive damage in .dat files and rebuild their index", + Long: `fix.recover reads every needle of the given .dat files (or of all .dat files in the given folders) and +checks its structure and CRC. When a record is damaged it searches forward for the next record that +verifies, reports the skipped region, and goes on, so one bad region does not hide the rest of the +volume. The .idx is rebuilt from the verified needles only. Damaged needles are reported, not repaired: +restore them from a replica. + + Stop the volume server before running this command. + Each damaged region is reported with its offset, length, kind (zero-fill, garbage, garbage+zeros) + and, when still readable, the file id of the header that was hit. A key whose newest copy is + damaged while an older copy is indexed is reported as a stale-version warning. + The rebuilt .idx is written next to the .dat; a volume server started with -dir.idx uses an .idx + next to the .dat in preference to the one in that directory. The previous .idx is kept as .idx.bak, + and stale .ldb, .sdx and .rdb caches next to it are removed; the volume server rebuilds them. + -dryRun only reports. -truncateTail cuts garbage after the last valid needle, so the load-time + integrity check passes; a tail that is not all zeros is saved to .tail..bak first. + The command refuses a volume while a .cpc compaction commit marker exists (start the volume server + once so it reconciles the interrupted vacuum, then re-run), a volume on a remote tier, and an + erasure-coded layout. + Exit status is non-zero when damage or a stale version was found or a volume could not be read; + with -ignoreError the run goes on with the next volume. +`, +} + +var ( + fixRecoverCollection = cmdFixRecover.Flag.String("collection", "", "an optional volume collection name, if specified only it will be processed") + fixRecoverVolumeId = cmdFixRecover.Flag.Int64("volumeId", 0, "an optional volume id, if not 0 (default) only it will be processed") + fixRecoverIncludeDeleted = cmdFixRecover.Flag.Bool("includeDeleted", true, "include deleted entries in the index file") + fixRecoverIgnoreError = cmdFixRecover.Flag.Bool("ignoreError", false, "report a volume that cannot be recovered and go on with the next one") + fixRecoverDryRun = cmdFixRecover.Flag.Bool("dryRun", false, "only report, do not touch .idx or .dat") + fixRecoverTruncateTail = cmdFixRecover.Flag.Bool("truncateTail", false, "cut garbage after the last valid needle off the .dat (non-zero tails are saved to .tail..bak first), so the load-time integrity check passes") + fixRecoverMaxNeedleMB = cmdFixRecover.Flag.Int("maxNeedleSizeMB", 64, "largest needle payload accepted while searching for the next valid needle after damage; a needle with a corrupted header larger than this cannot be recovered") +) + +func runFixRecover(cmd *Command, args []string) bool { + if len(args) == 0 { + fmt.Println("fix.recover: give at least one folder or .dat file") + return false + } + for _, arg := range args { + basePath, files, err := listVolumeFiles(arg) + if err != nil { + fmt.Println(err) + return false + } + for _, file := range files { + vf, ok, parseErr := selectVolumeFile(file.Name(), ".dat", *fixRecoverCollection, *fixRecoverVolumeId) + if parseErr != nil { + fmt.Printf("Failed to parse volume id from %s: %v\n", vf.baseFileName, parseErr) + if *fixRecoverIgnoreError { + SetCommandExitStatus(1) + continue + } + return false + } + if !ok { + continue + } + doRecoverOneVolume(basePath, vf.baseFileName, vf.volumeId) + } + } + return true +} + +// doRecoverOneVolume recovers one volume with the command line options and +// honours -ignoreError. +func doRecoverOneVolume(basePath, baseFileName string, volumeId int64) { + err := recoverOneVolume(basePath, baseFileName, volumeId, path.Join(basePath, baseFileName+".idx"), recoverOptions{ + includeDeleted: *fixRecoverIncludeDeleted, + dryRun: *fixRecoverDryRun, + truncateTail: *fixRecoverTruncateTail, + maxNeedleSizeMB: *fixRecoverMaxNeedleMB, + }) + if err == nil { + return + } + if *fixRecoverIgnoreError { + glog.Error(err) + SetCommandExitStatus(1) + return + } + glog.Fatal(err) +} diff --git a/weed/command/fix_recover_test.go b/weed/command/fix_recover_test.go new file mode 100644 index 0000000000..1966f10937 --- /dev/null +++ b/weed/command/fix_recover_test.go @@ -0,0 +1,109 @@ +package command + +import ( + "bytes" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/storage/types" +) + +func TestSelectVolumeFile(t *testing.T) { + for _, tc := range []struct { + name, ext string + volumeId int64 + want volumeFile + wantOk bool + wantErr bool + collection string + }{ + {name: "fix_7.dat", ext: ".dat", want: volumeFile{"fix_7", "fix", 7}, wantOk: true}, + {name: "7.dat", ext: ".dat", want: volumeFile{"7", "", 7}, wantOk: true}, + {name: "fix_7.idx", ext: ".dat"}, + {name: "fix_7.dat", ext: ".dat", volumeId: 8}, + {name: "fix_7.dat", ext: ".dat", collection: "other"}, + {name: "fix_4294967296.dat", ext: ".dat", volumeId: 7}, + {name: "x_99999999999.dat", ext: ".dat", wantErr: true}, + {name: "x_abc.dat", ext: ".dat", wantErr: true}, + } { + vf, ok, err := selectVolumeFile(tc.name, tc.ext, tc.collection, tc.volumeId) + if (err != nil) != tc.wantErr { + t.Errorf("%s: err = %v, want error %v", tc.name, err, tc.wantErr) + continue + } + if ok != tc.wantOk || (ok && vf != tc.want) { + t.Errorf("%s: got %+v ok=%v, want %+v ok=%v", tc.name, vf, ok, tc.want, tc.wantOk) + } + } +} + +func TestRunFixRecoverNeedsAPath(t *testing.T) { + captureStdout(t, func() { + if runFixRecover(cmdFixRecover, nil) { + t.Error("fix.recover without a path was accepted") + } + }) +} + +func TestRunFixRecoverRebuildsIndex(t *testing.T) { + dir := t.TempDir() + base, offsets := writeFixTestVolume(t, dir, 6, needle.Version3) + patchDat(t, base+".dat", offsets[2], bytes.Repeat([]byte{0xA5}, types.NeedleHeaderSize)) + withVerifyFlags(t, false) + + captureStdout(t, func() { + if !runFixRecover(cmdFixRecover, []string{dir}) { + t.Error("fix.recover failed on a damaged volume") + } + }) + if got := indexedKeys(t, base+".idx"); !slices.Equal(got, []uint64{1, 2, 4, 5, 6}) { + t.Fatalf("recovered keys %v, want [1 2 4 5 6]", got) + } + if CommandExitStatus() != 1 { + t.Fatalf("exit status %d, want 1 after damage", CommandExitStatus()) + } +} + +func TestRunFixRecoverVolumeIdFilter(t *testing.T) { + dir := t.TempDir() + writeFixTestVolume(t, dir, 2, needle.Version3) + if err := os.Rename(filepath.Join(dir, "fix_7.dat"), filepath.Join(dir, "fix_8.dat")); err != nil { + t.Fatal(err) + } + writeFixTestVolume(t, dir, 3, needle.Version3) + withVerifyFlags(t, false) + saved := *fixRecoverVolumeId + *fixRecoverVolumeId = 7 + t.Cleanup(func() { *fixRecoverVolumeId = saved }) + + captureStdout(t, func() { + if !runFixRecover(cmdFixRecover, []string{dir}) { + t.Error("fix.recover failed") + } + }) + if got := indexedKeys(t, filepath.Join(dir, "fix_7.idx")); len(got) != 3 { + t.Fatalf("volume 7 keys %v, want 3", got) + } + if _, err := os.Stat(filepath.Join(dir, "fix_8.idx")); !os.IsNotExist(err) { + t.Fatal("volume 8 was touched despite -volumeId=7") + } +} + +// Old scripts that pass the recovery flags to weed fix must fail loudly +// instead of silently running a plain fix. +func TestFixNoLongerAcceptsRecoverFlags(t *testing.T) { + for _, name := range []string{"verify", "dryRun", "truncateTail", "maxNeedleSizeMB"} { + if cmdFix.Flag.Lookup(name) != nil { + t.Errorf("weed fix still defines -%s", name) + } + if name != "verify" && cmdFixRecover.Flag.Lookup(name) == nil { + t.Errorf("weed fix.recover lacks -%s", name) + } + } + if cmdFix.Flag.Lookup("verifyCrc") == nil { + t.Error("weed fix lost -verifyCrc") + } +} diff --git a/weed/command/fix_test.go b/weed/command/fix_test.go index 7ad994002c..00442d7a42 100644 --- a/weed/command/fix_test.go +++ b/weed/command/fix_test.go @@ -86,10 +86,9 @@ func TestSaveToIdxWritesOffsetOrder(t *testing.T) { // writeFixTestVolume writes a .dat holding needles 1..count and returns its // base path and the offset of each needle, in key order. -func writeFixTestVolume(t *testing.T, dir string, count int) (string, []int64) { +func writeFixTestVolume(t *testing.T, dir string, count int, version needle.Version) (string, []int64) { t.Helper() base := filepath.Join(dir, "fix_7") - version := needle.GetCurrentVersion() f, err := os.OpenFile(base+".dat", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { t.Fatal(err) @@ -161,7 +160,7 @@ func TestFixSkipsRecordPastEndOfDat(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { dir := t.TempDir() - base, offsets := writeFixTestVolume(t, dir, 5) + base, offsets := writeFixTestVolume(t, dir, 5, needle.GetCurrentVersion()) tc.corrupt(t, base+".dat", offsets[4]) commandExitStatus = 0 doFixOneVolume(dir, "fix_7", "fix", 7, true) @@ -182,7 +181,7 @@ func TestFixIgnoreErrorReportsIncompleteScan(t *testing.T) { t.Run("bad header", func(t *testing.T) { dir := t.TempDir() - base, offsets := writeFixTestVolume(t, dir, 5) + base, offsets := writeFixTestVolume(t, dir, 5, needle.GetCurrentVersion()) overwriteAt(t, base+".dat", offsets[2], bytes.Repeat([]byte{0xa5}, 16)) commandExitStatus = 0 doFixOneVolume(dir, "fix_7", "fix", 7, false) @@ -196,7 +195,7 @@ func TestFixIgnoreErrorReportsIncompleteScan(t *testing.T) { t.Run("bad super block keeps the existing index", func(t *testing.T) { dir := t.TempDir() - base, _ := writeFixTestVolume(t, dir, 3) + base, _ := writeFixTestVolume(t, dir, 3, needle.GetCurrentVersion()) overwriteAt(t, base+".dat", 0, bytes.Repeat([]byte{0xa5}, 8)) if err := os.WriteFile(base+".idx", []byte("previous index"), 0644); err != nil { t.Fatal(err) @@ -245,7 +244,7 @@ func TestFixVerifyCrcIndexesDamagedNeedlesAsDeleted(t *testing.T) { savedVerify, savedStatus := *fixVerifyCrc, commandExitStatus defer func() { *fixVerifyCrc, commandExitStatus = savedVerify, savedStatus }() dir := t.TempDir() - base, offsets := writeFixTestVolume(t, dir, 5) + base, offsets := writeFixTestVolume(t, dir, 5, needle.GetCurrentVersion()) f, err := os.OpenFile(base+".dat", os.O_RDWR, 0644) if err != nil { t.Fatal(err) @@ -353,7 +352,7 @@ func (f failingReadAt) ReadAt(p []byte, off int64) (int, error) { // A needle -verifyCrc cannot read fails the scan instead of being dropped. func TestFixVerifyCrcFailsOnReadError(t *testing.T) { dir := t.TempDir() - base, offsets := writeFixTestVolume(t, dir, 3) + base, offsets := writeFixTestVolume(t, dir, 3, needle.GetCurrentVersion()) f, err := os.Open(base + ".dat") if err != nil { t.Fatal(err) @@ -371,7 +370,7 @@ func TestFixVerifyCrcFailsOnReadError(t *testing.T) { func TestLocalDatSizeIgnoresRemoteTier(t *testing.T) { dir := t.TempDir() - base, _ := writeFixTestVolume(t, dir, 2) + base, _ := writeFixTestVolume(t, dir, 2, needle.GetCurrentVersion()) info, err := os.Stat(base + ".dat") if err != nil { t.Fatal(err) @@ -392,7 +391,7 @@ func TestFixTruncatedDeleteKeepsKeyDeleted(t *testing.T) { savedStatus := commandExitStatus defer func() { commandExitStatus = savedStatus }() dir := t.TempDir() - base, _ := writeFixTestVolume(t, dir, 3) + base, _ := writeFixTestVolume(t, dir, 3, needle.GetCurrentVersion()) f, err := os.OpenFile(base+".dat", os.O_RDWR, 0644) if err != nil { t.Fatal(err) diff --git a/weed/command/fix_verify.go b/weed/command/fix_verify.go new file mode 100644 index 0000000000..0151fabe78 --- /dev/null +++ b/weed/command/fix_verify.go @@ -0,0 +1,836 @@ +package command + +import ( + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path" + "strconv" + "strings" + "time" + + "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" + "github.com/seaweedfs/seaweedfs/weed/storage/volume_info" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// printAnomalies writes one tab separated line per damaged region. +func printAnomalies(volumeId int64, anomalies []datAnomaly) { + for _, a := range anomalies { + fmt.Printf("volume=%d\tkind=%s\toffset=%d\tlength=%d\t%s\n", volumeId, a.Kind, a.Offset, a.Length, a.Detail) + } +} + +func printVerifySummary(volumeId int64, sum *datVerifySummary, took time.Duration) { + fmt.Printf("volume %d: %d needles + %d tombstones verified in %v; %d damaged regions (%d bytes, %d of them zero), %d warnings; clean end %d of %d\n", + volumeId, sum.Needles, sum.Tombstones, took.Round(time.Millisecond), + sum.BadRegions, sum.BadBytes, sum.ZeroBytes, sum.Warnings, sum.CleanEnd, sum.FileSize) +} + +// maxNonDataLen bounds the v2/v3 needle section that follows the payload: +// flags, name, mime, last-modified, ttl and pairs. +const maxNonDataLen = 1 + 1 + 255 + 1 + 255 + needle.LastModifiedBytesLength + needle.TtlBytesLength + 2 + 65535 + +var ( + errZeroNeedleId = errors.New("zero needle id") + errDatRead = errors.New("read .dat") +) + +type datVerifyOptions struct { + maxNeedleSize int64 + window int + zeroWindow int + // Progress, when set, is called every few thousand needles with the current offset. + Progress func(pos, total int64) +} + +// datVisitor receives the events of one scan. raw header and body are only valid during the call. +type datVisitor struct { + needle func(n *needle.Needle, offset int64, header, body []byte) error + // damage is called for every skipped region [start, end); tail is true when nothing valid follows. + damage func(start, end int64, tail bool) error +} + +func (o *datVerifyOptions) normalize() { + if o.zeroWindow <= 0 { + o.zeroWindow = 4096 + } + if o.maxNeedleSize <= 0 { + o.maxNeedleSize = 64 << 20 + } + if o.window < o.zeroWindow { + o.window = o.zeroWindow + } + // keep the window a multiple of both the zero window and the needle alignment + step := o.zeroWindow + for step%types.NeedlePaddingSize != 0 { + step++ + } + o.window -= o.window % step + if o.window == 0 { + o.window = step + } +} + +type datAnomaly struct { + Offset int64 + Length int64 + Kind string + Detail string +} + +type datVerifySummary struct { + FileSize int64 + CleanEnd int64 // end of the last valid needle + Needles int + Tombstones int + BadRegions int + BadBytes int64 + ZeroBytes int64 + TailGarbage bool + Warnings int + // DamagedRecords are the records whose header still parsed inside a damaged region. + DamagedRecords []damagedRecord +} + +// damagedRecord is a key whose record at Offset could not be verified. +type damagedRecord struct { + Key types.NeedleId + Offset int64 +} + +// staleVersionWarnings reports keys whose newest record was damaged while an +// older copy of the same key made it into the rebuilt index. +func staleVersionWarnings(nm *needle_map.MemDb, damaged []damagedRecord) []datAnomaly { + var warnings []datAnomaly + for _, d := range damaged { + v, ok := nm.Get(d.Key) + if !ok || v.Offset.ToActualOffset() >= d.Offset { + continue + } + warnings = append(warnings, datAnomaly{Offset: d.Offset, Kind: "stale-version", + Detail: fmt.Sprintf("key=%s: the record at %d is damaged, the rebuilt index points at the older copy at %d", d.Key, d.Offset, v.Offset.ToActualOffset())}) + } + return warnings +} + +// datWindow serves small reads out of a large sequential window. +type datWindow struct { + f io.ReaderAt + size int64 + buf []byte + off int64 + n int +} + +func (w *datWindow) readAt(p []byte, off int64) error { + if off < 0 || off+int64(len(p)) > w.size { + return io.ErrUnexpectedEOF + } + if len(p) > len(w.buf) { + n, err := w.f.ReadAt(p, off) + switch { + case n == len(p): + return nil + case err == nil || err == io.EOF: + return io.ErrUnexpectedEOF + } + return fmt.Errorf("%w at %d: %w", errDatRead, off, err) + } + if off < w.off || off+int64(len(p)) > w.off+int64(w.n) { + n, err := w.f.ReadAt(w.buf, off) + if err != nil && err != io.EOF { + return fmt.Errorf("%w at %d: %w", errDatRead, off, err) + } + w.off, w.n = off, n + if off+int64(len(p)) > w.off+int64(w.n) { + return io.ErrUnexpectedEOF + } + } + copy(p, w.buf[off-w.off:]) + return nil +} + +type datVerifier struct { + f io.ReaderAt + vid needle.VolumeId + version needle.Version + base int64 + size int64 + opts datVerifyOptions + win *datWindow + body []byte + hdr [types.NeedleHeaderSize]byte + lastAppendAtNs uint64 + anomalies []datAnomaly + sum datVerifySummary +} + +// readNeedleAt reads and fully verifies the needle at off. When the header +// parsed but the rest did not, the partially filled needle is returned with the +// error so callers can report which file id was hit. bounded applies +// -maxNeedleSizeMB, which only limits guesses made while resynchronising: a +// record reached at a known boundary may be as large as the file allows. +func (s *datVerifier) readNeedleAt(off int64, bounded bool) (n *needle.Needle, disk int64, err error) { + defer func() { + if r := recover(); r != nil { + disk, err = 0, fmt.Errorf("needle parse panic: %v", r) + } + }() + hdr := s.hdr[:] + if err = s.win.readAt(hdr, off); err != nil { + return nil, 0, fmt.Errorf("short header: %w", err) + } + n = new(needle.Needle) + n.ParseNeedleHeader(hdr) + if n.Id == 0 { + return nil, 0, errZeroNeedleId + } + if n.Size < 0 || (bounded && int64(n.Size) > s.opts.maxNeedleSize) { + return n, 0, fmt.Errorf("implausible size %d", n.Size) + } + disk = needle.GetActualSize(n.Size, s.version) + if off+disk > s.size { + return n, 0, fmt.Errorf("needle extends past end of .dat (%d > %d)", off+disk, s.size) + } + if s.version != needle.Version1 && n.Size > 0 { + var b [4]byte + if err = s.win.readAt(b[:], off+types.NeedleHeaderSize); err != nil { + return n, 0, fmt.Errorf("read data size: %w", err) + } + if dataSize := binary.BigEndian.Uint32(b[:]); !dataSizeFits(n.Size, dataSize) { + return n, 0, fmt.Errorf("data size %d does not fit a record of size %d", dataSize, n.Size) + } + } + bodyLen := int(disk - types.NeedleHeaderSize) + if cap(s.body) < bodyLen { + s.body = make([]byte, bodyLen) + } + body := s.body[:bodyLen] + if err = s.win.readAt(body, off+types.NeedleHeaderSize); err != nil { + return n, 0, fmt.Errorf("read body: %w", err) + } + if err = n.ReadNeedleBodyBytes(body, s.version); err != nil { + return n, 0, err + } + if err = checkRecordFields(n, s.version); err != nil { + return n, 0, err + } + return n, disk, nil +} + +// dataSizeFits reports whether a v2/v3 live record of the given size can hold +// dataSize bytes of data and the fields that follow it. +func dataSizeFits(size types.Size, dataSize uint32) bool { + return size >= 5 && int64(dataSize)+5 <= int64(size) && int64(size)-4-int64(dataSize) <= maxNonDataLen +} + +// checkRecordFields rejects a v2/v3 record whose parsed fields do not add up +// to its size. The writer only stores the data length and the fields after it +// when there is data, so a live record always has data, and the CRC check +// only runs when it does: a zero fill over the data length would otherwise +// pass as an empty file. +func checkRecordFields(n *needle.Needle, version needle.Version) error { + if version == needle.Version1 || n.Size <= 0 { + return nil + } + if n.DataSize == 0 { + return fmt.Errorf("record of size %d carries no data", n.Size) + } + fields := 4 + int64(n.DataSize) + 1 + if n.HasName() { + fields += 1 + int64(n.NameSize) + } + if n.HasMime() { + fields += 1 + int64(n.MimeSize) + } + if n.HasLastModifiedDate() { + fields += needle.LastModifiedBytesLength + } + if n.HasTtl() { + fields += needle.TtlBytesLength + } + if n.HasPairs() { + fields += 2 + int64(n.PairsSize) + } + if fields != int64(n.Size) { + return fmt.Errorf("record size %d does not match its fields (%d bytes)", n.Size, fields) + } + return nil +} + +// candidateOK decides whether the bytes at off look like the start of a real +// needle. Cheap header and structure checks run first so that scanning +// megabytes of garbage never triggers a full read per offset. +func (s *datVerifier) candidateOK(h *needle.Needle, chunk []byte, i int, off int64) bool { + disk := needle.GetActualSize(h.Size, s.version) + if off+disk > s.size { + return false + } + if s.version != needle.Version1 && h.Size > 0 { + var dataSize uint32 + if i+types.NeedleHeaderSize+4 <= len(chunk) { + dataSize = binary.BigEndian.Uint32(chunk[i+types.NeedleHeaderSize:]) + } else { + var b [4]byte + if _, err := s.f.ReadAt(b[:], off+types.NeedleHeaderSize); err != nil { + return false + } + dataSize = binary.BigEndian.Uint32(b[:]) + } + if !dataSizeFits(h.Size, dataSize) { + return false + } + var flags [1]byte + if _, err := s.f.ReadAt(flags[:], off+types.NeedleHeaderSize+4+int64(dataSize)); err != nil { + return false + } + if flags[0]&0x40 != 0 { // unused flag bit + return false + } + } + n, disk, err := s.readNeedleAt(off, true) + if err != nil { + return false + } + if len(n.Data) > 0 { + return true // the payload CRC matched; a false positive is not realistic + } + // No payload to checksum: only a delete record (size 0) gets here, since a + // live record without data fails checkRecordFields. A delete found while + // resynchronising must prove itself, or stray bytes in a damaged region + // could delete a live file. Every v3 writer stamps a delete record, so it + // needs a believable time, not older than the last verified record, and + // zero padding. v1/v2 records carry no time: the chain that follows must + // reach a record whose data passes its CRC, or end exactly at the file end. + if s.version == needle.Version3 { + return n.AppendAtNs != 0 && plausibleAppendAtNs(n.AppendAtNs) && n.AppendAtNs >= s.lastAppendAtNs && + allZero(s.body[needle.NeedleChecksumSize+types.TimestampSize:disk-types.NeedleHeaderSize]) + } + return s.chainReachesData(off + disk) +} + +// chainReachesData follows the records from off and reports whether they +// reach one whose data verifies, or end exactly at the end of the file. +func (s *datVerifier) chainReachesData(off int64) bool { + for i := 0; i < 16; i++ { + if off == s.size { + return true + } + n, disk, err := s.readNeedleAt(off, true) + if err != nil { + return false + } + if len(n.Data) > 0 { + return true + } + off += disk + } + return off == s.size +} + +func allZero(b []byte) bool { + for _, c := range b { + if c != 0 { + return false + } + } + return true +} + +// plausibleAppendAtNs tells a real append timestamp (v3 needles) from garbage. +func plausibleAppendAtNs(ns uint64) bool { + return ns >= uint64(time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC).UnixNano()) && + ns <= uint64(time.Now().Add(48*time.Hour).UnixNano()) +} + +// findNext scans from the given offset at needle alignment for the next +// offset where a needle verifies. It returns -1 when none is left. +func (s *datVerifier) findNext(from int64) (int64, error) { + p := from + if r := (p - s.base) % types.NeedlePaddingSize; r != 0 { + p += types.NeedlePaddingSize - r + } + chunk := make([]byte, s.opts.window) + var probe needle.Needle + for p+types.NeedleHeaderSize <= s.size { + n, err := s.f.ReadAt(chunk, p) + if err != nil && err != io.EOF { + return -1, fmt.Errorf("read at %d while searching for the next needle: %w", p, err) + } + i := 0 + for ; i+types.NeedleHeaderSize <= n; i += types.NeedlePaddingSize { + probe.ParseNeedleHeader(chunk[i : i+types.NeedleHeaderSize]) + if probe.Id == 0 || probe.Size < 0 || int64(probe.Size) > s.opts.maxNeedleSize { + continue + } + if off := p + int64(i); s.candidateOK(&probe, chunk[:n], i, off) { + return off, nil + } + } + if n < len(chunk) || i == 0 { + break + } + p += int64(i) + } + return -1, nil +} + +type regionStats struct { + zeroBytes int64 + zeroWindows int64 + windows int64 + longestZeroRun int64 + head string +} + +// describeRegion classifies a damaged region: how much of it is zeros, how many +// whole zeroWindow-sized blocks are zero, and the longest zero run. +func (s *datVerifier) describeRegion(start, end int64) regionStats { + var st regionStats + w := s.opts.zeroWindow + chunk := make([]byte, s.opts.window) + var run int64 + for pos := start; pos < end; { + want := int64(len(chunk)) + if end-pos < want { + want = end - pos + } + n, err := s.f.ReadAt(chunk[:want], pos) + if n == 0 && err != nil { + break + } + b := chunk[:n] + if pos == start { + h := b + if len(h) > 16 { + h = h[:16] + } + st.head = hex.EncodeToString(h) + } + for off := 0; off < len(b); off += w { + e := off + w + if e > len(b) { + e = len(b) + } + allZero := true + for _, c := range b[off:e] { + if c == 0 { + st.zeroBytes++ + run++ + continue + } + allZero = false + if run > st.longestZeroRun { + st.longestZeroRun = run + } + run = 0 + } + st.windows++ + if allZero { + st.zeroWindows++ + } + } + pos += int64(n) + } + if run > st.longestZeroRun { + st.longestZeroRun = run + } + return st +} + +func (s *datVerifier) recordBad(start, end int64, tail bool, cause error, hit *needle.Needle) { + st := s.describeRegion(start, end) + length := end - start + kind := "garbage" + switch { + case st.zeroBytes == length: + kind = "zero-fill" + case st.zeroWindows > 0: + kind = "garbage+zeros" + } + if tail { + kind = "tail-" + kind + } + detail := fmt.Sprintf("cause=%q zeroBytes=%d zeroWindows=%d/%d(%dB) longestZeroRun=%d head=%s", + cause, st.zeroBytes, st.zeroWindows, st.windows, s.opts.zeroWindow, st.longestZeroRun, st.head) + if hit != nil && hit.Id != 0 { + detail += fmt.Sprintf(" header=fid:%s,size:%d", needle.NewFileIdFromNeedle(s.vid, hit).String(), hit.Size) + s.sum.DamagedRecords = append(s.sum.DamagedRecords, damagedRecord{Key: hit.Id, Offset: start}) + } + s.anomalies = append(s.anomalies, datAnomaly{Offset: start, Length: length, Kind: kind, Detail: detail}) + s.sum.BadRegions++ + s.sum.BadBytes += length + s.sum.ZeroBytes += st.zeroBytes +} + +// verifyDatFile walks a .dat from the first needle to the end, calling visit for +// every needle that verifies. Damage never aborts the walk: the scanner looks +// for the next verifiable needle and records the skipped bytes as an anomaly. +func verifyDatFile(datName string, vid needle.VolumeId, opts datVerifyOptions, visit func(n *needle.Needle, offset int64)) (*datVerifySummary, []datAnomaly, error) { + return verifyDatFileWith(datName, vid, opts, &datVisitor{needle: func(n *needle.Needle, offset int64, _, _ []byte) error { + visit(n, offset) + return nil + }}) +} + +func verifyDatFileWith(datName string, vid needle.VolumeId, opts datVerifyOptions, v *datVisitor) (*datVerifySummary, []datAnomaly, error) { + opts.normalize() + f, err := os.Open(datName) + if err != nil { + return nil, nil, err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return nil, nil, err + } + + // the DiskFile wrapper only reads the super block; f stays ours and is closed above + sb, err := super_block.ReadSuperBlock(backend.NewDiskFile(f)) + if err != nil { + return nil, nil, err + } + version := sb.Version + if version < needle.Version1 || version > needle.Version3 { + return nil, nil, fmt.Errorf("%s: unsupported needle version %d in super block", datName, version) + } + // A super block extra describes an erasure-coded volume layout; its .dat was + // re-striped into .ecXX shards and is not a plain needle file any more. + if sb.ExtraSize > 0 || sb.Extra != nil { + return nil, nil, fmt.Errorf("%s: super block extra (erasure-coded layout) is not supported", datName) + } + base := int64(sb.BlockSize()) + + s := &datVerifier{ + f: f, vid: vid, version: version, base: base, size: st.Size(), opts: opts, + win: &datWindow{f: f, size: st.Size(), buf: make([]byte, opts.window)}, + } + s.sum.FileSize = s.size + + damage := func(start, end int64, tail bool) error { + if v.damage == nil { + return nil + } + return v.damage(start, end, tail) + } + + pos := base + for count := 0; pos < s.size; count++ { + if opts.Progress != nil && count&0xfff == 0 { + opts.Progress(pos, s.size) + } + if s.size-pos < types.NeedleHeaderSize { + s.recordBad(pos, s.size, true, errors.New("partial header at end of file"), nil) + s.sum.TailGarbage = true + if err := damage(pos, s.size, true); err != nil { + return nil, nil, err + } + break + } + n, disk, err := s.readNeedleAt(pos, false) + if err == nil { + if n.Size.IsValid() { + s.sum.Needles++ + } else { + s.sum.Tombstones++ + } + if n.AppendAtNs != 0 { + switch { + case !plausibleAppendAtNs(n.AppendAtNs): + s.anomalies = append(s.anomalies, datAnomaly{Offset: pos, Kind: "timestamp-implausible", + Detail: fmt.Sprintf("appendAtNs %d is outside the plausible range", n.AppendAtNs)}) + s.sum.Warnings++ + case n.AppendAtNs < s.lastAppendAtNs: + s.anomalies = append(s.anomalies, datAnomaly{Offset: pos, Kind: "timestamp-regression", + Detail: fmt.Sprintf("appendAtNs %d is older than the previous needle (%d)", n.AppendAtNs, s.lastAppendAtNs)}) + s.sum.Warnings++ + s.lastAppendAtNs = n.AppendAtNs + default: + s.lastAppendAtNs = n.AppendAtNs + } + } + if v.needle != nil { + if err := v.needle(n, pos, s.hdr[:], s.body[:disk-types.NeedleHeaderSize]); err != nil { + return nil, nil, err + } + } + pos += disk + continue + } + if errors.Is(err, errDatRead) { + return nil, nil, err + } + next, ferr := s.findNext(pos + types.NeedlePaddingSize) + if ferr != nil { + return nil, nil, ferr + } + if next < 0 { + s.recordBad(pos, s.size, true, err, n) + s.sum.TailGarbage = true + if derr := damage(pos, s.size, true); derr != nil { + return nil, nil, derr + } + break + } + s.recordBad(pos, next, false, err, n) + if derr := damage(pos, next, false); derr != nil { + return nil, nil, derr + } + pos = next + } + s.sum.CleanEnd = pos + return &s.sum, s.anomalies, nil +} + +func truncateDatTail(datName string, cleanEnd int64) error { + f, err := os.OpenFile(datName, os.O_RDWR, 0644) + if err != nil { + return err + } + defer f.Close() + st, err := f.Stat() + if err != nil { + return err + } + if st.Size() <= cleanEnd { + return nil + } + // keep the cut-off bytes unless they are all zeros + buf := make([]byte, 1<<20) + nonZero := false + for off := cleanEnd; off < st.Size() && !nonZero; { + n, rerr := f.ReadAt(buf, off) + for _, c := range buf[:n] { + if c != 0 { + nonZero = true + break + } + } + off += int64(n) + if rerr == io.EOF { + break + } + if rerr != nil { + // a tail that cannot be read cannot be shown to be zeros, so it is not cut + return fmt.Errorf("read the tail at %d: %w", off, rerr) + } + } + if nonZero { + bak := backupName(fmt.Sprintf("%s.tail.%d", datName, cleanEnd)) + out, err := os.OpenFile(bak, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644) + if err != nil { + return fmt.Errorf("create tail backup %s: %w", bak, err) + } + _, err = io.Copy(out, io.NewSectionReader(f, cleanEnd, st.Size()-cleanEnd)) + if err == nil { + err = out.Sync() + } + if cerr := out.Close(); err == nil { + err = cerr + } + if err == nil { + err = util.FsyncDir(path.Dir(bak)) + } + if err != nil { + os.Remove(bak) + return fmt.Errorf("write tail backup %s: %w", bak, err) + } + fmt.Printf("saved %d bytes cut from the tail to %s\n", st.Size()-cleanEnd, bak) + } + return f.Truncate(cleanEnd) +} + +// recoverOptions are the settings of one recovery run. +type recoverOptions struct { + includeDeleted bool + dryRun bool + truncateTail bool + maxNeedleSizeMB int +} + +// recoverOneVolume rebuilds the .idx of one volume from the needles that +// verify, resynchronising past damaged regions. Errors are returned so the +// caller can honour -ignoreError and move on to the next volume. +func recoverOneVolume(basepath string, baseFileName string, volumeId int64, indexFileName string, o recoverOptions) error { + vid, err := needle.NewVolumeId(strconv.FormatInt(volumeId, 10)) + if err != nil { + return fmt.Errorf("volume ID out of range: %d", volumeId) + } + datName := path.Join(basepath, baseFileName+".dat") + + // A .cpc marker means an interrupted vacuum commit is pending: the volume + // server reconciles it on its next start (roll forward with the marker, roll + // back orphan .cpd/.cpx without it). Writing a rebuilt .idx here would race + // that decision, so make the operator settle it first. + if cpcPath := strings.TrimSuffix(datName, ".dat") + ".cpc"; util.FileExists(cpcPath) { + return fmt.Errorf("volume %d: a compaction commit is pending (%s); start the volume server once so it reconciles the interrupted vacuum, then re-run", volumeId, cpcPath) + } + _, hasRemoteFile, _, err := volume_info.MaybeLoadVolumeInfo(path.Join(basepath, baseFileName+".vif")) + if err != nil { + return fmt.Errorf("volume %d: cannot tell whether the volume is on a remote tier: %w", volumeId, err) + } + if hasRemoteFile { + return fmt.Errorf("volume %d: fix.recover needs the local .dat, the volume is read from a remote tier", volumeId) + } + + nm := needle_map.NewMemDb() + nmDeleted := needle_map.NewMemDb() + defer nm.Close() + defer nmDeleted.Close() + scanner := &VolumeFileScanner4Fix{nm: nm, nmDeleted: nmDeleted, includeDeleted: o.includeDeleted} + + opts := datVerifyOptions{maxNeedleSize: int64(o.maxNeedleSizeMB) << 20, window: 8 << 20, zeroWindow: 4096, Progress: newProgressPrinter(volumeId)} + visitor := &datVisitor{needle: func(n *needle.Needle, offset int64, header, body []byte) error { + // the version only matters for DiskSize in a debug log line + return scanner.VisitNeedle(n, offset, nil, nil) + }} + started := time.Now() + sum, anomalies, err := verifyDatFileWith(datName, vid, opts, visitor) + if err != nil { + return fmt.Errorf("verify %s: %w", datName, err) + } + stale := staleVersionWarnings(nm, sum.DamagedRecords) + sum.Warnings += len(stale) + anomalies = append(anomalies, stale...) + + printAnomalies(volumeId, anomalies) + printVerifySummary(volumeId, sum, time.Since(started)) + if sum.BadRegions > 0 || len(stale) > 0 { + // like plain fix and -verifyCrc: damage was found, so a script knows to check replicas + SetCommandExitStatus(1) + } + + if o.dryRun { + return nil + } + if sum.TailGarbage { + if o.truncateTail { + if err := truncateDatTail(datName, sum.CleanEnd); err != nil { + return fmt.Errorf("truncate %s: %w", datName, err) + } + fmt.Printf("volume %d: truncated %s to %d bytes\n", volumeId, datName, sum.CleanEnd) + } else { + fmt.Printf("volume %d: WARNING %d bytes follow the last valid needle; the volume server keeps it read-only until the tail is cut (rerun with -truncateTail)\n", + volumeId, sum.FileSize-sum.CleanEnd) + } + } + if err := installRebuiltIndex(scanner, indexFileName, volumeId); err != nil { + return err + } + printIdxDirHint(volumeId) + return nil +} + +// installRebuiltIndex writes the rebuilt index to a staging file first and +// swaps it in only once it is complete, keeping the previous index as .bak (a +// rebuilt index only knows what survived in .dat). A .ldb cache next to the +// index describes the old index, so it is dropped and the volume server +// rebuilds it from the new one. +func installRebuiltIndex(scanner *VolumeFileScanner4Fix, indexFileName string, volumeId int64) error { + staged := indexFileName + ".tmp" + if err := SaveToIdx(scanner, staged); err != nil { + os.Remove(staged) + return fmt.Errorf("save to .idx File: %v", strings.TrimSpace(err.Error())) + } + if err := syncFile(staged); err != nil { + os.Remove(staged) + return fmt.Errorf("sync %s: %w", staged, err) + } + // keep the previous index as a second link, so a live .idx exists at every moment + if _, statErr := os.Stat(indexFileName); statErr == nil { + bak := backupName(indexFileName) + if err := os.Link(indexFileName, bak); err != nil { + os.Remove(staged) + return fmt.Errorf("back up %s: %w", indexFileName, err) + } + fmt.Printf("volume %d: previous index saved as %s\n", volumeId, bak) + } + // these caches describe the previous index; drop them before the swap so a + // crash never leaves the new index next to them. The volume server rebuilds + // them from whichever index is in place. + removed := false + for _, ext := range []string{".ldb", ".sdx", ".rdb"} { + cache := strings.TrimSuffix(indexFileName, ".idx") + ext + if !util.FileExists(cache) && !util.FolderExists(cache) { + continue + } + if err := os.RemoveAll(cache); err != nil { + os.Remove(staged) + return fmt.Errorf("remove the stale %s (delete it before starting the volume server): %w", cache, err) + } + removed = true + fmt.Printf("volume %d: removed the stale %s; the volume server rebuilds it from the new index\n", volumeId, cache) + } + if removed { + if err := util.FsyncDir(path.Dir(indexFileName)); err != nil { + os.Remove(staged) + return fmt.Errorf("sync directory of %s: %w", indexFileName, err) + } + } + if err := os.Rename(staged, indexFileName); err != nil { + os.Remove(staged) + return fmt.Errorf("install %s: %w", indexFileName, err) + } + if err := util.FsyncDir(path.Dir(indexFileName)); err != nil { + return fmt.Errorf("sync directory of %s: %w", indexFileName, err) + } + return nil +} + +func syncFile(name string) error { + f, err := os.OpenFile(name, os.O_RDWR, 0) + if err != nil { + return err + } + err = f.Sync() + if cerr := f.Close(); err == nil { + err = cerr + } + return err +} + +// printIdxDirHint explains where the rebuilt index lands: next to the .dat. +// A volume server prefers an .idx next to the .dat over one in -dir.idx, so it +// picks the rebuilt index up as is. +func printIdxDirHint(volumeId int64) { + fmt.Printf("volume %d: the rebuilt index was written next to the .dat; a volume server started with -dir.idx uses it in preference to the copy in that directory\n", volumeId) +} + +// backupName returns the first free name among path.bak, path.bak. +// and path.bak... +func backupName(path string) string { + bak := path + ".bak" + if _, err := os.Lstat(bak); err != nil { + return bak + } + stamped := fmt.Sprintf("%s.bak.%d", path, time.Now().Unix()) + bak = stamped + for n := 1; ; n++ { + if _, err := os.Lstat(bak); err != nil { + return bak + } + bak = fmt.Sprintf("%s.%d", stamped, n) + } +} + +func newProgressPrinter(volumeId int64) func(pos, total int64) { + started := time.Now() + last := started + return func(pos, total int64) { + now := time.Now() + if now.Sub(last) < 30*time.Second { + return + } + last = now + fmt.Fprintf(os.Stderr, "volume %d: %.1f%% (%d of %d MB), %.0f MB/s\n", volumeId, + float64(pos)*100/float64(total), pos>>20, total>>20, float64(pos)/(1<<20)/now.Sub(started).Seconds()) + } +} diff --git a/weed/command/fix_verify_integration_test.go b/weed/command/fix_verify_integration_test.go new file mode 100644 index 0000000000..dd64f69df0 --- /dev/null +++ b/weed/command/fix_verify_integration_test.go @@ -0,0 +1,253 @@ +package command + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "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" +) + +// These integration tests pin the damage-recovery behaviour against the +// upstream issues that motivated it: +// +// - #5674: a .dat whose head (right after the superblock) is zero-filled must +// still yield every needle behind the damaged region. +// - #12914: one bad header in the middle currently makes plain `weed fix` +// drop every later needle and index nothing after the damage; `fix.recover` +// must recover the survivors, including the newest copy of a rewritten +// needle, and a zeroed superblock must be a clear error, not a silent +// version-0 parse. + +// TestIssue5674ZeroFilledHead covers the geometry reported in #5674: the +// volume starts with zeros instead of the first needle records. `fix.recover` +// must report the zero-filled region and index every surviving needle. +func TestIssue5674ZeroFilledHead(t *testing.T) { + const lostRecords = 6 + for _, tc := range []struct { + name string + misaligned bool + }{ + {"damage ends on a record boundary", false}, + {"damage cuts the next record", true}, + } { + t.Run(tc.name, func(t *testing.T) { + datName, layout := buildVerifyFixture(t, 20) + // layout[i] is needle i+1; layout[20] is the trailing delete record. + zeroEnd := layout[lostRecords].offset + if tc.misaligned { + zeroEnd += layout[lostRecords].disk / 2 + } + patchDat(t, datName, 8, make([]byte, zeroEnd-8)) // keep the 8-byte superblock + + sum, anomalies, seen := runVerify(t, datName) + + firstSurvivor := uint64(lostRecords + 1) + if tc.misaligned { + firstSurvivor = lostRecords + 2 // the cut record cannot verify + } + var want []uint64 + for id := firstSurvivor; id <= 20; id++ { + want = append(want, id) + } + var got []uint64 + for id := range seen { + got = append(got, id) + } + slices.Sort(got) + if !slices.Equal(got, want) { + t.Fatalf("recovered needles %v, want %v", got, want) + } + if len(anomalies) == 0 { + t.Fatal("the zero-filled head was not reported") + } + if anomalies[0].Offset != 8 { + t.Errorf("first anomaly starts at %d, want the head of the needle area (8)", anomalies[0].Offset) + } + if !tc.misaligned && (anomalies[0].Kind != "zero-fill" || anomalies[0].Length != zeroEnd-8) { + t.Errorf("aligned zero head: got kind %q length %d, want zero-fill %d", + anomalies[0].Kind, anomalies[0].Length, zeroEnd-8) + } + if sum.BadRegions == 0 || sum.Tombstones != 1 { + t.Errorf("bad regions=%d tombstones=%d, want damage reported and the trailing delete record kept", + sum.BadRegions, sum.Tombstones) + } + }) + } +} + +// TestIssue12914LegacyFixDropsNeedlesAfterDamage pins the behaviour reported in +// #12914 item 1: plain `weed fix` stops at the first bad header and loses every +// needle behind it; `weed fix.recover` recovers them. +func TestIssue12914LegacyFixDropsNeedlesAfterDamage(t *testing.T) { + dir := t.TempDir() + base, offsets := writeFixTestVolume(t, dir, 8, needle.Version3) + // A huge size field in the header of needle 5 makes the record run past EOF. + patchDat(t, base+".dat", offsets[4]+types.NeedleIdSize+types.CookieSize, []byte{0x7f, 0xff, 0xff, 0xf0}) + + savedIgnore, savedStatus := *fixIgnoreError, commandExitStatus + *fixIgnoreError, commandExitStatus = true, 0 + t.Cleanup(func() { + *fixIgnoreError, commandExitStatus = savedIgnore, savedStatus + }) + + doFixOneVolume(dir, "fix_7", "fix", 7, true) + if got := indexedKeys(t, base+".idx"); !slices.Equal(got, []uint64{1, 2, 3, 4}) { + t.Fatalf("plain weed fix indexed %v, want [1 2 3 4] before the damage (#12914)", got) + } + + withVerifyFlags(t, true) + doRecoverOneVolume(dir, "fix_7", 7) + if got := indexedKeys(t, base+".idx"); !slices.Equal(got, []uint64{1, 2, 3, 4, 6, 7, 8}) { + t.Fatalf("weed fix.recover indexed %v, want [1 2 3 4 6 7 8]", got) + } +} + +// TestIssue12914RewrittenNeedleBehindDamage checks that the newest copy of a +// needle rewritten after a damaged region wins over nothing: the damaged old +// record is skipped and the rebuild indexes the later copy at its real offset. +func TestIssue12914RewrittenNeedleBehindDamage(t *testing.T) { + dir := t.TempDir() + base, offsets := writeFixTestVolume(t, dir, 8, needle.Version3) + + // Rewrite needle 5 at the end of the .dat, then destroy the original record. + f, err := os.OpenFile(base+".dat", os.O_RDWR, 0644) + if err != nil { + t.Fatal(err) + } + datBackend := backend.NewDiskFile(f) + rewritten := &needle.Needle{Id: types.Uint64ToNeedleId(5), Data: bytes.Repeat([]byte{0x77}, 4321)} + rewritten.Checksum = needle.NewCRC(rewritten.Data) + newOffset, _, _, err := rewritten.Append(datBackend, needle.Version3) + if err != nil { + t.Fatal(err) + } + datBackend.Close() + patchDat(t, base+".dat", offsets[4], make([]byte, offsets[5]-offsets[4])) + + withVerifyFlags(t, true) + doRecoverOneVolume(dir, "fix_7", 7) + + got := idxOffsets(t, base+".idx") + for _, id := range []uint64{1, 2, 3, 4, 6, 7, 8} { + if _, ok := got[id]; !ok { + t.Errorf("needle %d after the damage is missing from the rebuilt index", id) + } + } + off, ok := got[5] + if !ok { + t.Fatal("rewritten needle 5 is missing from the rebuilt index") + } + if off != int64(newOffset) { + t.Fatalf("needle 5 indexed at offset %d, want the newest copy at %d", off, newOffset) + } +} + +// TestIssue5674ZeroedSuperBlock covers the second half of #5674: when the first +// bytes are gone too, the file must fail with an explicit version error instead +// of being parsed as a version-0 volume. +func TestIssue5674ZeroedSuperBlock(t *testing.T) { + datName := filepath.Join(t.TempDir(), "1.dat") + if err := os.WriteFile(datName, make([]byte, 4096), 0644); err != nil { + t.Fatal(err) + } + _, _, err := verifyDatFile(datName, 1, datVerifyOptions{}, func(*needle.Needle, int64) {}) + if err == nil || !strings.Contains(err.Error(), "unsupported needle version") { + t.Fatalf("want an explicit unsupported-version error, got %v", err) + } +} + +// TestVerifyDatFileVersion1And2 guards the supported needle-format range: the +// scan must verify volumes written with the older needle layouts, not only the +// current version. +func TestVerifyDatFileVersion1And2(t *testing.T) { + for _, version := range []needle.Version{needle.Version1, needle.Version2} { + t.Run(fmt.Sprintf("version %d", version), func(t *testing.T) { + datName := buildVerifyFixtureVersion(t, 5, version) + sum, anomalies, seen := runVerify(t, datName) + if len(anomalies) != 0 || sum.Needles != 5 || len(seen) != 5 { + t.Fatalf("needles=%d seen=%d anomalies=%+v, want a clean 5-needle volume", sum.Needles, len(seen), anomalies) + } + }) + } +} + +// buildVerifyFixtureVersion writes count needles (ids 1..count) into a volume +// whose superblock and needle records use the given version. +func buildVerifyFixtureVersion(t *testing.T, count int, version needle.Version) string { + t.Helper() + datName := filepath.Join(t.TempDir(), "1.dat") + f, err := os.OpenFile(datName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + if err != nil { + t.Fatal(err) + } + datBackend := backend.NewDiskFile(f) + 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) + } + for i := 1; i <= count; i++ { + n := &needle.Needle{Id: types.Uint64ToNeedleId(uint64(i)), Data: bytes.Repeat([]byte{byte(i)}, 700+i*11)} + n.Checksum = needle.NewCRC(n.Data) + if _, _, _, err := n.Append(datBackend, version); err != nil { + t.Fatalf("append needle %d: %v", i, err) + } + } + return datName +} + +// TestFixRefusesPendingCompactMarker: a .cpc marker means an interrupted +// vacuum commit is waiting for the volume server to reconcile it. Writing a +// rebuilt .idx on top of that decision must be refused with a +// clear, scriptable error. +func TestFixRefusesPendingCompactMarker(t *testing.T) { + dir := t.TempDir() + base, _ := writeFixTestVolume(t, dir, 3, needle.GetCurrentVersion()) + if err := os.WriteFile(base+".cpc", nil, 0644); err != nil { + t.Fatal(err) + } + + withVerifyFlags(t, true) + + doRecoverOneVolume(dir, "fix_7", 7) + if CommandExitStatus() != 1 { + t.Fatalf("exit status = %d, want 1 (pending commit marker must fail the run)", CommandExitStatus()) + } + if _, err := os.Stat(base + ".idx"); !os.IsNotExist(err) { + t.Fatal("a rebuilt .idx was written despite the pending commit marker") + } + if _, err := os.Stat(base + ".cpc"); err != nil { + t.Fatalf("the pending marker must be left for the volume server: %v", err) + } +} + +// idxOffsets returns key -> .dat offset for every entry of the rebuilt .idx. +func idxOffsets(t *testing.T, idxPath string) map[uint64]int64 { + t.Helper() + f, err := os.Open(idxPath) + if err != nil { + t.Fatalf("open idx: %v", err) + } + defer f.Close() + offsets := map[uint64]int64{} + if err := idx.WalkIndexFile(f, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error { + offsets[uint64(key)] = offset.ToActualOffset() + return nil + }); err != nil { + t.Fatalf("walk idx: %v", err) + } + return offsets +} diff --git a/weed/command/fix_verify_review_test.go b/weed/command/fix_verify_review_test.go new file mode 100644 index 0000000000..26bdfaf03b --- /dev/null +++ b/weed/command/fix_verify_review_test.go @@ -0,0 +1,528 @@ +package command + +import ( + "bytes" + "encoding/binary" + "errors" + "io" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" + "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/types" + "github.com/seaweedfs/seaweedfs/weed/storage/volume_info" +) + +// A zero fill that erases a live record's payload length and flags but keeps +// its header leaves a record that parses with no data, so its CRC is never +// checked. It must count as damage, not as an empty file. +func TestVerifyZeroedPayloadLengthIsDamage(t *testing.T) { + datName, layout := buildVerifyFixture(t, 5) + n3 := layout[2] + dataLen := 1000 + 3*37 + patchDat(t, datName, n3.offset+types.NeedleHeaderSize, make([]byte, 4+dataLen+1)) + + sum, anomalies, seen := runVerify(t, datName) + if seen[3] { + t.Fatalf("needle 3 with an erased payload length was indexed as live") + } + if len(anomalies) == 0 || sum.BadRegions == 0 { + t.Fatalf("no damage reported for the erased payload: %+v", anomalies) + } + for _, id := range []uint64{2, 4, 5} { + if !seen[id] { + t.Errorf("needle %d next to the damage was lost", id) + } + } +} + +// -maxNeedleSizeMB bounds only the search for the next needle after damage. A +// healthy needle larger than it, reached at a known record boundary, must +// still verify. +func TestVerifyLargeNeedleAtBoundaryIsNotDamage(t *testing.T) { + datName, _ := buildVerifyFixture(t, 5) + seen := map[uint64]bool{} + sum, anomalies, err := verifyDatFile(datName, 1, datVerifyOptions{maxNeedleSize: 512, 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) + } + if len(anomalies) != 0 || len(seen) != 5 || sum.Tombstones != 1 { + t.Fatalf("seen=%d tombstones=%d anomalies=%+v, want all 5 needles and the delete record", len(seen), sum.Tombstones, anomalies) + } +} + +// After damage, a delete record followed by an unreadable tail must still be +// found; dropping it brings the deleted file back. +func TestVerifyTombstoneBeforeDamagedTailIsKept(t *testing.T) { + datName, layout := buildVerifyFixture(t, 5) + patchDat(t, datName, layout[4].offset, bytes.Repeat([]byte{0xA5}, types.NeedleHeaderSize)) + f, err := os.OpenFile(datName, os.O_WRONLY|os.O_APPEND, 0644) + if err != nil { + t.Fatal(err) + } + if _, err := f.Write(bytes.Repeat([]byte{0x5A}, 64)); err != nil { + t.Fatal(err) + } + f.Close() + + deleted := false + if _, _, err := verifyDatFile(datName, 1, datVerifyOptions{window: 64 << 10, zeroWindow: 512}, func(n *needle.Needle, offset int64) { + if uint64(n.Id) == 1 && !n.Size.IsValid() && offset == layout[5].offset { + deleted = true + } + }); err != nil { + t.Fatal(err) + } + if !deleted { + t.Fatalf("the delete record for needle 1 before the damaged tail was dropped, so the file would come back") + } +} + +type failingReaderAt struct { + r io.ReaderAt + failAt int64 +} + +func (f failingReaderAt) ReadAt(p []byte, off int64) (int, error) { + if off+int64(len(p)) > f.failAt { + return 0, syscall.EIO + } + return f.r.ReadAt(p, off) +} + +// A disk read error while searching for the next needle is not the end of +// the data: it must surface as an error, not as a garbage tail to cut. +func TestFindNextReadErrorIsReported(t *testing.T) { + datName, layout := buildVerifyFixture(t, 5) + raw, err := os.Open(datName) + if err != nil { + t.Fatal(err) + } + defer raw.Close() + st, _ := raw.Stat() + r := failingReaderAt{r: raw, failAt: layout[2].offset} + opts := datVerifyOptions{window: 64 << 10, zeroWindow: 512} + opts.normalize() + s := &datVerifier{f: r, vid: 1, version: needle.Version3, base: 8, size: st.Size(), opts: opts, + win: &datWindow{f: r, size: st.Size(), buf: make([]byte, opts.window)}} + next, err := s.findNext(layout[0].offset + types.NeedlePaddingSize) + if err == nil || !errors.Is(err, syscall.EIO) { + t.Fatalf("findNext = %d, %v; want the read error", next, err) + } +} + +// When the newest record of a key is damaged, the rebuilt index points at an +// older copy. That must be reported, not done silently. +func TestStaleVersionWarnings(t *testing.T) { + nm := needle_map.NewMemDb() + defer nm.Close() + if err := nm.Set(types.NeedleId(7), types.ToOffset(800), 100); err != nil { + t.Fatal(err) + } + warnings := staleVersionWarnings(nm, []damagedRecord{ + {Key: 7, Offset: 4096}, // damaged copy after the indexed one: stale + {Key: 7, Offset: 64}, // damaged copy before the indexed one: fine + {Key: 9, Offset: 4096}, // key not indexed at all + }) + if len(warnings) != 1 || warnings[0].Kind != "stale-version" || warnings[0].Offset != 4096 { + t.Fatalf("warnings = %+v, want one stale-version at 4096", warnings) + } +} + +func TestVerifyRecordsKeysHitByDamage(t *testing.T) { + datName, layout := buildVerifyFixture(t, 5) + n3 := layout[2] + patchDat(t, datName, n3.offset+types.NeedleHeaderSize+4+100, []byte{0xFF, 0x00, 0xFF}) + sum, _, _ := runVerify(t, datName) + if len(sum.DamagedRecords) != 1 || sum.DamagedRecords[0] != (damagedRecord{Key: 3, Offset: n3.offset}) { + t.Fatalf("damaged records = %+v, want key 3 at %d", sum.DamagedRecords, n3.offset) + } +} + +func withVerifyFlags(t *testing.T, ignoreError bool) { + t.Helper() + savedIgnore, savedStatus := *fixRecoverIgnoreError, commandExitStatus + *fixRecoverIgnoreError, commandExitStatus = ignoreError, 0 + t.Cleanup(func() { *fixRecoverIgnoreError, commandExitStatus = savedIgnore, savedStatus }) +} + +// The rebuilt index is staged next to the live one and swapped in only once +// it is complete; a stale .ldb cache next to it is dropped so the volume +// server rebuilds it from the new index. +func TestFixVerifyStagesIndexAndDropsLevelDb(t *testing.T) { + dir := t.TempDir() + base, _ := writeFixTestVolume(t, dir, 3, needle.Version3) + if err := os.WriteFile(base+".idx", []byte("old index, 16 b"), 0644); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(base+".ldb", 0755); err != nil { + t.Fatal(err) + } + for _, ext := range []string{".sdx", ".rdb"} { + if err := os.WriteFile(base+ext, []byte("stale"), 0644); err != nil { + t.Fatal(err) + } + } + withVerifyFlags(t, false) + + doRecoverOneVolume(dir, "fix_7", 7) + + if got := indexedKeys(t, base+".idx"); len(got) != 3 { + t.Fatalf("rebuilt index keys = %v, want 3", got) + } + if b, err := os.ReadFile(base + ".idx.bak"); err != nil || string(b) != "old index, 16 b" { + t.Fatalf("old index not kept as .idx.bak: %q %v", b, err) + } + for _, ext := range []string{".ldb", ".sdx", ".rdb"} { + if _, err := os.Stat(base + ext); !os.IsNotExist(err) { + t.Fatalf("stale %s cache was left next to the rebuilt index", ext) + } + } + matches, _ := filepath.Glob(base + ".idx.tmp*") + if len(matches) != 0 { + t.Fatalf("staging files left behind: %v", matches) + } +} + +// With -ignoreError a volume that cannot be verified is reported and the run +// goes on to the next volume, like the plain fix path does. +func TestFixVerifyIgnoreErrorContinues(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "fix_7.dat"), make([]byte, 4096), 0644); err != nil { + t.Fatal(err) + } + withVerifyFlags(t, true) + + doRecoverOneVolume(dir, "fix_7", 7) + + if CommandExitStatus() != 1 { + t.Fatalf("exit status = %d, want 1", CommandExitStatus()) + } + if _, err := os.Stat(filepath.Join(dir, "fix_7.idx")); !os.IsNotExist(err) { + t.Fatalf("an index was written for a volume that could not be verified") + } +} + +// A remote-tiered volume is served from its remote .dat through the existing +// .idx, so a local .dat next to it must not replace that index. +func TestFixVerifyRefusesRemoteTier(t *testing.T) { + dir := t.TempDir() + base, _ := writeFixTestVolume(t, dir, 3, needle.GetCurrentVersion()) + if err := os.WriteFile(base+".idx", []byte("old index, 16 b"), 0644); err != nil { + t.Fatal(err) + } + vi := &volume_server_pb.VolumeInfo{Files: []*volume_server_pb.RemoteFile{{BackendType: "s3", Key: "fix_7.dat"}}} + if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil { + t.Fatal(err) + } + withVerifyFlags(t, false) + + err := recoverOneVolume(dir, "fix_7", 7, base+".idx", recoverOptions{includeDeleted: true, maxNeedleSizeMB: 64}) + if err == nil || !strings.Contains(err.Error(), "remote tier") { + t.Fatalf("error %v, want a remote tier refusal", err) + } + if b, err := os.ReadFile(base + ".idx"); err != nil || string(b) != "old index, 16 b" { + t.Fatalf("index of a remote-tiered volume was replaced: %q %v", b, err) + } +} + +// An unparsable .vif may hide a remote tier, so it is refused the same way. +func TestFixVerifyRefusesUnreadableVolumeInfo(t *testing.T) { + dir := t.TempDir() + base, _ := writeFixTestVolume(t, dir, 3, needle.GetCurrentVersion()) + if err := os.WriteFile(base+".idx", []byte("old index, 16 b"), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(base+".vif", []byte("{not json"), 0644); err != nil { + t.Fatal(err) + } + withVerifyFlags(t, false) + + err := recoverOneVolume(dir, "fix_7", 7, base+".idx", recoverOptions{includeDeleted: true, maxNeedleSizeMB: 64}) + if err == nil || !strings.Contains(err.Error(), "cannot tell") { + t.Fatalf("error %v, want a volume info refusal", err) + } + if b, err := os.ReadFile(base + ".idx"); err != nil || string(b) != "old index, 16 b" { + t.Fatalf("index replaced despite an unreadable .vif: %q %v", b, err) + } +} + +// Volume ids are uint32; a larger number in a file name is rejected while +// parsing instead of being narrowed. +func TestRunFixRejectsVolumeIdBeyondUint32(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "c_4294967296.dat"), nil, 0644); err != nil { + t.Fatal(err) + } + out := captureStdout(t, func() { + if runFix(cmdFix, []string{dir}) { + t.Errorf("runFix accepted an out-of-range volume id") + } + }) + if !strings.Contains(out, "Failed to parse volume id") { + t.Fatalf("output %q, want a parse error", out) + } +} + +// Stray bytes in a zero-filled region can form a header with a small id and +// size 0. Unstamped, and followed by another such header, it used to pass as +// a delete record and delete a live file. +func TestVerifyStrayBytesDoNotDeleteLiveFiles(t *testing.T) { + datName, layout := buildVerifyFixture(t, 9) + start, end := layout[4].offset, layout[7].offset + z := make([]byte, end-start) + z[64+11] = 0x02 + z[96+11] = 0x09 + patchDat(t, datName, start, z) + + if _, _, err := verifyDatFile(datName, 1, datVerifyOptions{window: 64 << 10, zeroWindow: 512}, func(n *needle.Needle, offset int64) { + if !n.Size.IsValid() && offset >= start && offset < end { + t.Errorf("a delete record for key %d was taken from the damaged region at %d", n.Id, offset) + } + }); err != nil { + t.Fatal(err) + } +} + +// A run that found damage exits non-zero, like plain fix and -verifyCrc, so a +// script knows to restore from a replica; a clean volume exits 0. +func TestFixVerifyExitStatusReportsDamage(t *testing.T) { + dir := t.TempDir() + base, offsets := writeFixTestVolume(t, dir, 4, needle.Version3) + withVerifyFlags(t, false) + doRecoverOneVolume(dir, "fix_7", 7) + if CommandExitStatus() != 0 { + t.Fatalf("clean volume: exit status %d, want 0", CommandExitStatus()) + } + patchDat(t, base+".dat", offsets[1], bytes.Repeat([]byte{0xA5}, types.NeedleHeaderSize)) + doRecoverOneVolume(dir, "fix_7", 7) + if CommandExitStatus() != 1 { + t.Fatalf("damaged volume: exit status %d, want 1", CommandExitStatus()) + } +} + +// With -ignoreError a file name whose volume id does not fit uint32 is +// reported and the run goes on with the other volumes. +func TestRunFixIgnoreErrorSkipsBadVolumeId(t *testing.T) { + dir := t.TempDir() + writeFixTestVolume(t, dir, 2, needle.GetCurrentVersion()) + if err := os.WriteFile(filepath.Join(dir, "c_4294967296.dat"), nil, 0644); err != nil { + t.Fatal(err) + } + saved, savedStatus := *fixIgnoreError, commandExitStatus + *fixIgnoreError, commandExitStatus = true, 0 + t.Cleanup(func() { *fixIgnoreError, commandExitStatus = saved, savedStatus }) + captureStdout(t, func() { + if !runFix(cmdFix, []string{dir}) { + t.Errorf("runFix stopped the batch at the bad file name") + } + }) + if CommandExitStatus() != 1 { + t.Fatalf("exit status %d, want 1", CommandExitStatus()) + } + if got := indexedKeys(t, filepath.Join(dir, "fix_7.idx")); len(got) != 2 { + t.Fatalf("the other volume was not fixed: keys %v", got) + } +} + +// The guards that let a delete record found after damage stand on its own: +// a time older than the last verified record, or non-zero padding, rejects it. +func TestVerifyResyncedDeleteRecordGuards(t *testing.T) { + cases := map[string]func(t *testing.T, datName string, tomb int64){ + "older than the last verified record": func(t *testing.T, datName string, tomb int64) { + // a believable time, one hour before the record's own, so older than the needles before it + at := tomb + types.NeedleHeaderSize + needle.NeedleChecksumSize + raw, err := os.ReadFile(datName) + if err != nil { + t.Fatal(err) + } + ts := binary.BigEndian.Uint64(raw[at:]) - uint64(time.Hour) + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, ts) + patchDat(t, datName, at, b) + }, + "non-zero padding": func(t *testing.T, datName string, tomb int64) { + patchDat(t, datName, tomb+types.NeedleHeaderSize+needle.NeedleChecksumSize+types.TimestampSize, []byte{1}) + }, + } + for name, corrupt := range cases { + t.Run(name, func(t *testing.T) { + datName, layout := buildVerifyFixture(t, 5) + tomb := layout[5].offset + patchDat(t, datName, layout[4].offset, bytes.Repeat([]byte{0xA5}, types.NeedleHeaderSize)) + corrupt(t, datName, tomb) + if _, _, err := verifyDatFile(datName, 1, datVerifyOptions{window: 64 << 10, zeroWindow: 512}, func(n *needle.Needle, offset int64) { + if offset == tomb { + t.Errorf("the delete record at %d was accepted", offset) + } + }); err != nil { + t.Fatal(err) + } + }) + } +} + +func TestRunFixVolumeIdFilterSkipsOutOfRangeName(t *testing.T) { + dir := t.TempDir() + writeFixTestVolume(t, dir, 2, needle.GetCurrentVersion()) + if err := os.WriteFile(filepath.Join(dir, "fix_4294967296.dat"), nil, 0644); err != nil { + t.Fatal(err) + } + saved, savedStatus := *fixVolumeId, commandExitStatus + *fixVolumeId, commandExitStatus = 7, 0 + t.Cleanup(func() { *fixVolumeId, commandExitStatus = saved, savedStatus }) + captureStdout(t, func() { + if !runFix(cmdFix, []string{dir}) { + t.Errorf("runFix stopped at a file the -volumeId filter excludes") + } + }) + if got := indexedKeys(t, filepath.Join(dir, "fix_7.idx")); len(got) != 2 { + t.Fatalf("the selected volume was not fixed: keys %v", got) + } +} + +// A damaged size field at a known boundary must be rejected from the data +// length that follows the header, before a body of that size is allocated. +func TestVerifyInflatedSizeRejectedBeforeBodyRead(t *testing.T) { + datName, layout := buildVerifyFixture(t, 5) + raw, err := os.OpenFile(datName, os.O_RDWR, 0644) + if err != nil { + t.Fatal(err) + } + st, _ := raw.Stat() + if err := raw.Truncate(st.Size() + 1<<20); err != nil { + t.Fatal(err) + } + st, _ = raw.Stat() + raw.Close() + inflated := st.Size() - layout[1].offset - 64 + var b [4]byte + binary.BigEndian.PutUint32(b[:], uint32(inflated)) + patchDat(t, datName, layout[1].offset+types.CookieSize+types.NeedleIdSize, b[:]) + + f, err := os.Open(datName) + if err != nil { + t.Fatal(err) + } + defer f.Close() + opts := datVerifyOptions{window: 64 << 10, zeroWindow: 512} + opts.normalize() + s := &datVerifier{f: f, vid: 1, version: needle.Version3, base: 8, size: st.Size(), opts: opts, + win: &datWindow{f: f, size: st.Size(), buf: make([]byte, opts.window)}} + if _, _, err := s.readNeedleAt(layout[1].offset, false); err == nil || !strings.Contains(err.Error(), "does not fit") { + t.Fatalf("readNeedleAt = %v, want a data size rejection", err) + } + if cap(s.body) != 0 { + t.Fatalf("allocated a %d byte body for the damaged record", cap(s.body)) + } + _, _, seen := runVerify(t, datName) + for _, id := range []uint64{1, 3, 4, 5} { + if !seen[id] { + t.Fatalf("needle %d after the damaged size was not recovered: %v", id, seen) + } + } +} + +// A v2 delete chain that reaches the end of the file on its last probe proves +// itself just like a shorter one. +func TestVerifyDeleteChainEndingAtLastProbe(t *testing.T) { + datName := buildVerifyFixtureVersion(t, 1, needle.Version2) + f, err := os.OpenFile(datName, os.O_RDWR, 0644) + if err != nil { + t.Fatal(err) + } + datBackend := backend.NewDiskFile(f) + var first int64 = -1 + for i := 0; i < 17; i++ { + n := &needle.Needle{Id: types.Uint64ToNeedleId(uint64(100 + i))} + offset, _, _, err := n.Append(datBackend, needle.Version2) + if err != nil { + t.Fatal(err) + } + if first < 0 { + first = int64(offset) + } + } + datBackend.Close() + + raw, err := os.Open(datName) + if err != nil { + t.Fatal(err) + } + defer raw.Close() + st, _ := raw.Stat() + opts := datVerifyOptions{window: 64 << 10, zeroWindow: 512} + opts.normalize() + s := &datVerifier{f: raw, vid: 1, version: needle.Version2, base: 8, size: st.Size(), opts: opts, + win: &datWindow{f: raw, size: st.Size(), buf: make([]byte, opts.window)}} + if !s.chainReachesData(first + needle.GetActualSize(0, needle.Version2)) { + t.Fatalf("a delete chain of 16 records ending at the end of the file was rejected") + } +} + +// A live record whose timestamp alone is corrupted still passes its CRC. That +// timestamp must not become the lower bound a later delete record is held to. +func TestVerifyImplausibleTimestampIsNotResyncBaseline(t *testing.T) { + datName, layout := buildVerifyFixture(t, 5) + raw, err := os.ReadFile(datName) + if err != nil { + t.Fatal(err) + } + live := layout[3].offset + size := int64(binary.BigEndian.Uint32(raw[live+types.CookieSize+types.NeedleIdSize:])) + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, ^uint64(0)) + patchDat(t, datName, live+types.NeedleHeaderSize+size+needle.NeedleChecksumSize, b) + patchDat(t, datName, layout[4].offset, bytes.Repeat([]byte{0xA5}, types.NeedleHeaderSize)) + + deleted := false + _, anomalies, err := verifyDatFile(datName, 1, datVerifyOptions{window: 64 << 10, zeroWindow: 512}, func(n *needle.Needle, offset int64) { + if offset == layout[5].offset && !n.Size.IsValid() { + deleted = true + } + }) + if err != nil { + t.Fatal(err) + } + if !deleted { + t.Fatalf("the delete record after damage was rejected; anomalies %+v", anomalies) + } + found := false + for _, a := range anomalies { + found = found || (a.Kind == "timestamp-implausible" && a.Offset == live) + } + if !found { + t.Fatalf("the implausible timestamp was not reported: %+v", anomalies) + } +} + +// A read error at a known record boundary is not damage in the data: it must +// stop the repair instead of resynchronising past the unread record. +func TestVerifyReadErrorAtBoundaryIsReported(t *testing.T) { + datName, layout := buildVerifyFixture(t, 5) + raw, err := os.Open(datName) + if err != nil { + t.Fatal(err) + } + defer raw.Close() + st, _ := raw.Stat() + r := failingReaderAt{r: raw, failAt: layout[2].offset + 4} + opts := datVerifyOptions{window: 64 << 10, zeroWindow: 512} + opts.normalize() + s := &datVerifier{f: r, vid: 1, version: needle.Version3, base: 8, size: st.Size(), opts: opts, + win: &datWindow{f: r, size: st.Size(), buf: make([]byte, opts.window)}} + if _, _, err := s.readNeedleAt(layout[2].offset, false); !errors.Is(err, errDatRead) || !errors.Is(err, syscall.EIO) { + t.Fatalf("readNeedleAt = %v, want the read error", err) + } +} diff --git a/weed/command/fix_verify_test.go b/weed/command/fix_verify_test.go new file mode 100644 index 0000000000..ed6ad703dc --- /dev/null +++ b/weed/command/fix_verify_test.go @@ -0,0 +1,433 @@ +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) + } + } +}