Files
seaweedfs/weed/command/fix_test.go
dcce121d95 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 <noreply@anthropic.com>

* fix: apply -volumeId before rejecting an out-of-range volume file name

With -volumeId set, an unrelated file such as 4294967296.dat aborted the
run before the filter could skip it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: check the data length before reading a record body in fix -verify

A damaged size field at a known record boundary made the scan allocate and
read a body of that size before rejecting it. Check that the data length
after the header fits the record first, as the resync probe already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: accept a v1/v2 delete chain that reaches the end of the file on its last probe

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep an implausible needle timestamp out of the fix -verify resync baseline

The data CRC does not cover the v3 timestamp, so a corrupted one passed and
then rejected every genuine delete record found after later damage. Report
it as a warning instead of using it as the lower bound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: stop fix -verify on a read error at a known record boundary

An EIO while reading a record was treated like damaged bytes: the scan
resynchronised past the unread record and the rebuilt index dropped it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: sync the fix -verify tail backup before truncating the .dat

A crash right after the truncate could persist it before the backup's data
or directory entry, losing the cut bytes from both files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: let fix -verify -truncateTail retry when a tail backup already exists

After a backup succeeded and the truncate failed, the next run hit the
existing backup and could not get past O_EXCL. Keep the first backup and
save the tail under a new name, as the index backup does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: drop stale index caches before fix -verify swaps in the new index

Removing them after the rename left a window where a crash paired the new
.idx with the old .ldb, whose newer LOG skips the replay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: pin fix -verify fixtures to needle version 3

-verify reads v1 to v3 records, so its fixtures should not follow the
build's current needle version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: refuse fix -verify on remote-tiered volumes

A remote-tiered volume is read from its remote .dat through the existing
.idx, so rebuilding that index from a local .dat would point it at the
wrong bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: pick a free backup name when fix -verify retries within one second

backupName fell back to path.bak.<unix time> without checking it, so a
second retry in the same second reused that name and the exclusive
create (or the .idx hard link) failed. Add a .<n> suffix until the name
is free.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: refuse fix -verify when the volume info cannot be read

An unreadable or unparsable .vif may name a remote tier, so treat it like one
and keep the existing index.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: pass weed fix -verify options explicitly

* feat: move weed fix -verify into a weed fix.recover command

* docs: weed fix.recover help, point weed fix at it

* fix: keep the volume file helpers below runFix

Leaves the region between VisitNeedle and runFix as on master.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: build fix.recover fixtures at needle version 3

fix.recover reads needle versions 1 to 3, so its tests must not follow
GetCurrentVersion; writeFixTestVolume now takes the version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: whitefox <whitefox@mayflower.work>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 08:24:05 -08:00

445 lines
15 KiB
Go

package command
import (
"bytes"
"errors"
"os"
"path/filepath"
"slices"
"syscall"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage"
"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/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"
)
// TestSaveToIdxWritesOffsetOrder guards that weed fix rebuilds the .idx as an
// append-ordered log (sorted by .dat offset), not sorted by key. A key-sorted
// .idx puts the highest-key needle last instead of the .dat-tail needle, which
// flipped volumes read-only on load (issue #9688). It must also carry every
// tombstone — including one whose live needle is gone — so the last entry is
// the real .dat tail.
func TestSaveToIdxWritesOffsetOrder(t *testing.T) {
nm := needle_map.NewMemDb()
defer nm.Close()
nmDeleted := needle_map.NewMemDb()
defer nmDeleted.Close()
// Live needles with high keys at low offsets (as if written first).
for _, e := range []struct {
key uint64
offset int64
}{{30, 8}, {20, 128}, {10, 256}} {
if err := nm.Set(types.Uint64ToNeedleId(e.key), types.ToOffset(e.offset), types.Size(100)); err != nil {
t.Fatalf("nm.Set: %v", err)
}
}
// A tombstone at the .dat tail whose live needle is gone; the old SaveToIdx
// dropped these because the key was absent from the live map.
if err := nmDeleted.Set(types.Uint64ToNeedleId(5), types.ToOffset(384), types.TombstoneFileSize); err != nil {
t.Fatalf("nmDeleted.Set: %v", err)
}
scanner := &VolumeFileScanner4Fix{nm: nm, nmDeleted: nmDeleted, includeDeleted: true}
idxPath := filepath.Join(t.TempDir(), "v.idx")
if err := SaveToIdx(scanner, idxPath); err != nil {
t.Fatalf("SaveToIdx: %v", err)
}
f, err := os.Open(idxPath)
if err != nil {
t.Fatalf("open idx: %v", err)
}
defer f.Close()
var offsets []int64
var lastKey types.NeedleId
if err := idx.WalkIndexFile(f, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
offsets = append(offsets, offset.ToActualOffset())
lastKey = key
return nil
}); err != nil {
t.Fatalf("walk idx: %v", err)
}
if len(offsets) != 4 {
t.Fatalf("expected 4 entries (3 live + 1 tombstone), got %d", len(offsets))
}
for i := 1; i < len(offsets); i++ {
if offsets[i] < offsets[i-1] {
t.Fatalf("entries not in offset order: %v", offsets)
}
}
// The .dat-tail needle (the orphan tombstone at the highest offset) must be last.
if lastKey != types.Uint64ToNeedleId(5) {
t.Errorf("last entry should be the .dat-tail tombstone (key 5), got key %v", lastKey)
}
}
// 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, version needle.Version) (string, []int64) {
t.Helper()
base := filepath.Join(dir, "fix_7")
f, err := os.OpenFile(base+".dat", 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)
}
var offsets []int64
for i := 1; i <= count; i++ {
n := &needle.Needle{Id: types.Uint64ToNeedleId(uint64(i)), Data: bytes.Repeat([]byte{byte(i)}, 1000*i)}
n.Checksum = needle.NewCRC(n.Data)
offset, _, _, err := n.Append(datBackend, version)
if err != nil {
t.Fatalf("append needle %d: %v", i, err)
}
offsets = append(offsets, int64(offset))
}
return base, offsets
}
func indexedKeys(t *testing.T, idxPath string) []uint64 {
t.Helper()
f, err := os.Open(idxPath)
if err != nil {
t.Fatalf("open idx: %v", err)
}
defer f.Close()
var keys []uint64
if err := idx.WalkIndexFile(f, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
keys = append(keys, uint64(key))
return nil
}); err != nil {
t.Fatalf("walk idx: %v", err)
}
return keys
}
func overwriteAt(t *testing.T, path string, offset int64, b []byte) {
t.Helper()
f, err := os.OpenFile(path, os.O_WRONLY, 0644)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if _, err := f.WriteAt(b, offset); err != nil {
t.Fatal(err)
}
}
func TestFixSkipsRecordPastEndOfDat(t *testing.T) {
savedStatus := commandExitStatus
defer func() { commandExitStatus = savedStatus }()
sizeAt := types.NeedleIdSize + types.CookieSize
for _, tc := range []struct {
name string
corrupt func(t *testing.T, dat string, off int64)
}{
{"truncated", func(t *testing.T, dat string, off int64) {
if err := os.Truncate(dat, off+100); err != nil {
t.Fatal(err)
}
}},
{"huge size", func(t *testing.T, dat string, off int64) {
overwriteAt(t, dat, off+int64(sizeAt), []byte{0x7f, 0xff, 0xff, 0xf0})
}},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
base, offsets := writeFixTestVolume(t, dir, 5, needle.GetCurrentVersion())
tc.corrupt(t, base+".dat", offsets[4])
commandExitStatus = 0
doFixOneVolume(dir, "fix_7", "fix", 7, true)
if CommandExitStatus() == 0 {
t.Error("expected a non-zero exit status")
}
if got := indexedKeys(t, base+".idx"); !slices.Equal(got, []uint64{1, 2, 3, 4}) {
t.Errorf("indexed keys %v, want [1 2 3 4]", got)
}
})
}
}
func TestFixIgnoreErrorReportsIncompleteScan(t *testing.T) {
savedIgnore, savedStatus := *fixIgnoreError, commandExitStatus
*fixIgnoreError = true
defer func() { *fixIgnoreError, commandExitStatus = savedIgnore, savedStatus }()
t.Run("bad header", func(t *testing.T) {
dir := t.TempDir()
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)
if CommandExitStatus() == 0 {
t.Error("expected a non-zero exit status for a scan that stopped before the end of the .dat")
}
if got := indexedKeys(t, base+".idx"); !slices.Equal(got, []uint64{1, 2}) {
t.Errorf("indexed keys %v, want [1 2]", got)
}
})
t.Run("bad super block keeps the existing index", func(t *testing.T) {
dir := t.TempDir()
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)
}
commandExitStatus = 0
doFixOneVolume(dir, "fix_7", "fix", 7, true)
if CommandExitStatus() == 0 {
t.Error("expected a non-zero exit status for an unreadable super block")
}
if b, err := os.ReadFile(base + ".idx"); err != nil || string(b) != "previous index" {
t.Errorf("existing .idx changed: %q, %v", b, err)
}
})
}
// liveKeys applies the .idx entries in order and returns the keys left live.
func liveKeys(t *testing.T, idxPath string) []uint64 {
t.Helper()
f, err := os.Open(idxPath)
if err != nil {
t.Fatalf("open idx: %v", err)
}
defer f.Close()
live := map[uint64]bool{}
if err := idx.WalkIndexFile(f, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
live[uint64(key)] = !offset.IsZero() && size.IsValid()
return nil
}); err != nil {
t.Fatalf("walk idx: %v", err)
}
var keys []uint64
for key, ok := range live {
if ok {
keys = append(keys, key)
}
}
slices.Sort(keys)
return keys
}
// Damaged needles, and a damaged newer copy of a key, are indexed unless
// -verifyCrc reads the data; then they are indexed as deleted and the older
// copy of the key does not come back. Needle 5's data size is zeroed, which
// skips the CRC.
func TestFixVerifyCrcIndexesDamagedNeedlesAsDeleted(t *testing.T) {
savedVerify, savedStatus := *fixVerifyCrc, commandExitStatus
defer func() { *fixVerifyCrc, commandExitStatus = savedVerify, savedStatus }()
dir := t.TempDir()
base, offsets := writeFixTestVolume(t, dir, 5, needle.GetCurrentVersion())
f, err := os.OpenFile(base+".dat", os.O_RDWR, 0644)
if err != nil {
t.Fatal(err)
}
datBackend := backend.NewDiskFile(f)
rewrite := &needle.Needle{Id: types.Uint64ToNeedleId(2), Data: bytes.Repeat([]byte{0x22}, 500)}
rewrite.Checksum = needle.NewCRC(rewrite.Data)
offset, _, _, err := rewrite.Append(datBackend, needle.GetCurrentVersion())
datBackend.Close()
if err != nil {
t.Fatal(err)
}
dataAt := int64(types.NeedleHeaderSize + types.DataSizeSize)
overwriteAt(t, base+".dat", offsets[3]+dataAt, []byte{0xee})
overwriteAt(t, base+".dat", int64(offset)+dataAt, []byte{0xee})
overwriteAt(t, base+".dat", offsets[4]+types.NeedleHeaderSize, make([]byte, types.DataSizeSize))
for _, tc := range []struct {
verify bool
want []uint64
status int
}{
{false, []uint64{1, 2, 3, 4, 5}, 0},
{true, []uint64{1, 3}, 1},
} {
for _, includeDeleted := range []bool{false, true} {
*fixVerifyCrc, commandExitStatus = tc.verify, 0
doFixOneVolume(dir, "fix_7", "fix", 7, includeDeleted)
if got := liveKeys(t, base+".idx"); !slices.Equal(got, tc.want) {
t.Errorf("verifyCrc=%v includeDeleted=%v: live keys %v, want %v", tc.verify, includeDeleted, got, tc.want)
}
if CommandExitStatus() != tc.status {
t.Errorf("verifyCrc=%v includeDeleted=%v: exit status %d, want %d", tc.verify, includeDeleted, CommandExitStatus(), tc.status)
}
}
}
}
// Loading a volume repaired with -verifyCrc must not bring back the older
// copy of a key whose newer copy, the last record, was damaged.
func TestFixVerifyCrcDamagedTailStaysDeletedOnLoad(t *testing.T) {
savedVerify, savedStatus := *fixVerifyCrc, commandExitStatus
defer func() { *fixVerifyCrc, commandExitStatus = savedVerify, savedStatus }()
dir := t.TempDir()
base := filepath.Join(dir, "fix_7")
f, err := os.OpenFile(base+".dat", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
t.Fatal(err)
}
datBackend := backend.NewDiskFile(f)
sb := super_block.SuperBlock{Version: needle.GetCurrentVersion(), ReplicaPlacement: &super_block.ReplicaPlacement{}, Ttl: &needle.TTL{}}
if _, err := datBackend.WriteAt(sb.Bytes(), 0); err != nil {
t.Fatal(err)
}
var offset uint64
for i, key := range []uint64{1, 2, 2} {
n := &needle.Needle{Id: types.Uint64ToNeedleId(key), Data: bytes.Repeat([]byte{byte(i + 1)}, 500), AppendAtNs: uint64(i + 1)}
n.Checksum = needle.NewCRC(n.Data)
if offset, _, _, err = n.Append(datBackend, needle.GetCurrentVersion()); err != nil {
t.Fatal(err)
}
}
datBackend.Close()
overwriteAt(t, base+".dat", int64(offset)+types.NeedleHeaderSize+types.DataSizeSize, []byte{0xee})
datBefore, err := os.Stat(base + ".dat")
if err != nil {
t.Fatal(err)
}
*fixVerifyCrc, commandExitStatus = true, 0
doFixOneVolume(dir, "fix_7", "fix", 7, true)
v, err := storage.NewVolume(dir, dir, "fix", 7, storage.NeedleMapInMemory, nil, nil, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatal(err)
}
defer v.Close()
if _, found, _ := v.LookupNeedle(types.Uint64ToNeedleId(2)); found {
t.Error("key 2 is live after loading the repaired volume")
}
if _, found, _ := v.LookupNeedle(types.Uint64ToNeedleId(1)); !found {
t.Error("key 1 is missing after loading the repaired volume")
}
datAfter, err := os.Stat(base + ".dat")
if err != nil {
t.Fatal(err)
}
if datAfter.Size() != datBefore.Size() {
t.Errorf(".dat changed on load: %d bytes before, %d after", datBefore.Size(), datAfter.Size())
}
}
type failingReadAt struct {
backend.BackendStorageFile
at int64
}
func (f failingReadAt) ReadAt(p []byte, off int64) (int, error) {
if off == f.at {
return 0, syscall.EIO
}
return f.BackendStorageFile.ReadAt(p, off)
}
// 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, needle.GetCurrentVersion())
f, err := os.Open(base + ".dat")
if err != nil {
t.Fatal(err)
}
dat := backend.NewDiskFile(f)
defer dat.Close()
nm, nmDeleted := needle_map.NewMemDb(), needle_map.NewMemDb()
defer nm.Close()
defer nmDeleted.Close()
scanner := &VolumeFileScanner4Fix{nm: nm, nmDeleted: nmDeleted, verifyDat: failingReadAt{dat, offsets[1]}}
if err := storage.ScanVolumeFile(dir, "fix", 7, storage.NeedleMapInMemory, scanner); !errors.Is(err, syscall.EIO) {
t.Fatalf("scan error %v, want EIO", err)
}
}
func TestLocalDatSizeIgnoresRemoteTier(t *testing.T) {
dir := t.TempDir()
base, _ := writeFixTestVolume(t, dir, 2, needle.GetCurrentVersion())
info, err := os.Stat(base + ".dat")
if err != nil {
t.Fatal(err)
}
if got := localDatSize(dir, "fix_7"); got != info.Size() {
t.Fatalf("localDatSize = %d, want %d", got, info.Size())
}
vi := &volume_server_pb.VolumeInfo{Files: []*volume_server_pb.RemoteFile{{BackendType: "s3", Key: "fix_7.dat", FileSize: uint64(info.Size()) * 2}}}
if err := volume_info.SaveVolumeInfo(base+".vif", vi); err != nil {
t.Fatal(err)
}
if got := localDatSize(dir, "fix_7"); got != 0 {
t.Errorf("localDatSize with a remote .dat = %d, want 0", got)
}
}
func TestFixTruncatedDeleteKeepsKeyDeleted(t *testing.T) {
savedStatus := commandExitStatus
defer func() { commandExitStatus = savedStatus }()
dir := t.TempDir()
base, _ := writeFixTestVolume(t, dir, 3, needle.GetCurrentVersion())
f, err := os.OpenFile(base+".dat", os.O_RDWR, 0644)
if err != nil {
t.Fatal(err)
}
datBackend := backend.NewDiskFile(f)
deletion := &needle.Needle{Id: types.Uint64ToNeedleId(2)}
offset, _, _, err := deletion.Append(datBackend, needle.GetCurrentVersion())
datBackend.Close()
if err != nil {
t.Fatal(err)
}
if err := os.Truncate(base+".dat", int64(offset)+types.NeedleHeaderSize+2); err != nil {
t.Fatal(err)
}
for _, includeDeleted := range []bool{true, false} {
doFixOneVolume(dir, "fix_7", "fix", 7, includeDeleted)
f, err := os.Open(base + ".idx")
if err != nil {
t.Fatal(err)
}
live := map[uint64]bool{}
err = idx.WalkIndexFile(f, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
live[uint64(key)] = !offset.IsZero() && size.IsValid()
return nil
})
f.Close()
if err != nil {
t.Fatal(err)
}
if live[2] || !live[1] || !live[3] {
t.Errorf("includeDeleted=%v: live keys %v, want 1 and 3 only", includeDeleted, live)
}
}
}
func TestSaveToIdxReportsOpenError(t *testing.T) {
nm := needle_map.NewMemDb()
defer nm.Close()
idxPath := filepath.Join(t.TempDir(), "fix_7.idx")
if err := os.Mkdir(idxPath, 0755); err != nil {
t.Fatal(err)
}
if err := SaveToIdx(&VolumeFileScanner4Fix{nm: nm}, idxPath); err == nil {
t.Error("expected an error when the .idx path cannot be opened")
}
if _, err := os.Stat(idxPath); err != nil {
t.Errorf("a failed open must leave the existing .idx path alone: %v", err)
}
}