Files
seaweedfs/weed/storage/volume_vacuum_crash_safe_test.go
T
Chris LuandDevin cc04c805a4 volume.copy: drop the needle-map index a failed copy leaves behind (#12252)
* volume.copy: drop the needle-map index a failed copy leaves behind

A VolumeCopy that mounts and then fails validation is only unloaded, not
deleted, so a leveldb (.ldb) or sorted-file (.sdx) index built by the
mount outlives the copy. The next copy of the same volume to this server
then trusts the stale index (generateLevelDbFile replays only past its
watermark), which is wrong once the source has compacted in between.
Mirrors the Rust server's remove_partial_files.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: clear a stale index before a copy writes

A crashed copy, or one whose cleanup failed, leaves a stale .ldb/.sdx/.rdb
next to the .idx that this copy's mount would trust (generateLevelDbFile
replays only past the stored watermark, and a same-size .idx keeps every
un-replayed offset). Abort on a removal error rather than risk a mount
reusing a poisoned index. Mirrors the Rust server's pre-write
remove_partial_files call.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: keep a mounted replica when the final response send fails

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: discard a mounted replica the caller abandoned

A send failure after MountVolume means the caller is gone, but the
replica was already announced to the master. Deleting its files under
the live mount breaks the loaded index; leaving it mounted keeps an
orphan the master routes to. Mirror the Rust copy cleanup: track the
mount, and on error delete through the store (unmount + withdraw the
announcement + remove files, keeping remote data), and check the stream
context before mounting.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: serialize copies of a volume on one server

A second VolumeCopy of the same volume could pass the existing-volume
check before the first copy mounts, then clear or overwrite the files
the first copy still owns. Mirror ecDecodesInFlight: the claim covers
the whole copy, and a duplicate fails fast so the caller can retry.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: remove only files the copy owns, and every stale index

Three cleanup gaps around which files a copy may remove:

- The failure cleanup ran on any error, so an abort before the first
  write (a failed stale-index clear or a failed .note write) could
  delete a previous replica's files the copy had not touched. File
  removal is now gated on the copy having started writing.
- A mount that finds an .idx beside the .dat builds the needle-map
  index under the data base, so leftovers there poison the next copy
  the same way the idx-dir ones do. Clear and clean up .idx/.ldb/
  .sdx/.rdb under both bases when the dirs differ.
- A regular volume and an EC volume for the same id share <base>.vif.
  Keep it while the EC index is on the disk, as the destroy path does.
- When the discard of a mounted copy is refused (e.g. it is compacting)
  the volume stays registered; unlinking its files would strand a live
  replica.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: do not unlink a previous replica on an early abort

An abort before the first write now leaves the destination files alone,
but three removal paths still leaked past that gate: a partially-written
.note, and the post-copy defer's .idx/.vif at the data base. Remove the
.note unconditionally (it only ever marks an in-flight copy) and gate the
data-file removals in the outer defer on copyOwnsFiles too.

* volume.copy: refuse a mount or configure while a copy is in flight

A copy claims the volume id, then waits on the source before it clears or
overwrites the destination files. A mount or configure landing in that
window loads the replica whose index files the copy is about to remove.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: abort when a replica registers during the source RPCs

The existing-volume snapshot runs before the copy calls the source, so a
mount that lands in between escapes it. Recheck registration just before
the destructive clear, which can share the index directory with the
mounted replica's bases.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: keep files whenever a replica of the volume stays registered

The cleanup already kept files after a refused delete; a replica a racing
mount registered during the copy needs the same protection, since its
index directory can coincide with the bases being cleaned.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: skip the index cleanup when the copy never picked bases

An early failure leaves the base names empty, so the removals would
otherwise run against ".ldb"/".sdx"/".rdb" in the process directory.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: serialize mount and configure registration under a per-volume guard

The in-flight flag check in VolumeMount and VolumeConfigure was not
atomic with volume registration, and the copy's registration recheck was
not atomic with its stale-index clearing. A mount that passed the check
just before the copy claimed the volume could register after the recheck
and then lose its index files to the clearing.

Replace the bare flag with a per-volume guard: the copy claims it for
the copy's life, mounts and configures hold it across check plus
registration, and the copy holds it across the recheck plus clearing.
Whichever side takes the guard first wins, so a mount either registers
before the recheck (and aborts the copy) or sees the claim and refuses.
Guards persist in the map so a mutex handed to a waiter is never
replaced mid-wait.

* volume.copy: refuse allocation and staged adoption under the copy guard

AllocateVolume and adoptStagedVolume still registered a volume while a
copy of it held the destination: NewVolume loads the index before
registration, and the copy then truncates or replaces files the live
replica already opened, leaving it mounted on a stale index.

Both paths now take the per-volume guard through their registration, so
they either register before the copy's recheck (and make it abort) or
see the claim and refuse with Unavailable.

* volume.copy: serialize reload loads with the per-volume guard

A SIGHUP reload ran loadExistingVolume outside the copy's guard: its
.note branch could unlink a copy's files mid-write, and its
NewVolume+SetVolume could register a replica between the copy's recheck
and its file clearing, leaving a live volume on a stale index.

loadExistingVolume now consults a per-location hook the server installs:
a vid with a copy in flight (or whose guard the copy currently holds) is
skipped for the next pass; otherwise the returned release keeps the
guard held through registration, so the copy's recheck either sees the
volume and aborts or clears first.

* volume.copy: skip compaction-state reconcile while a copy owns the volume

* volume.copy: let a guarded operation's own mount past the load guard

VolumeMount, VolumeConfigure, adoptStagedVolume hold the volume guard
locked, and VolumeCopy holds copying=true, while calling store.MountVolume.
The mount reaches loadExistingVolume where the new load guard saw the
caller's own hold (TryLock fails, or copying set) and skipped the disk:
every guarded mount failed 'volume not found on disk' — a completed copy
deleted its copied files, configure left the volume unmounted, staged
adoption failed after renaming.

Plumb ownLoad through MountVolume -> LoadVolume -> loadExistingVolume via
the new MountVolumeClaimed entry point so the owner's own load proceeds
while unrelated loads are still skipped.

* volume.copy: fix own-load test call, assert unguarded mounts still skip

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* volume.copy: refuse unmount and delete while a copy owns the volume

---------

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-30 09:20:55 -07:00

380 lines
12 KiB
Go

package storage
import (
"os"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// fileExists is a tiny test helper for asserting file presence.
func mustNotExist(t *testing.T, path string) {
t.Helper()
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("expected %s to be absent, got err=%v", path, err)
}
}
func mustExist(t *testing.T, path string) {
t.Helper()
if _, err := os.Stat(path); err != nil {
t.Fatalf("expected %s to exist: %v", path, err)
}
}
// A crash after the .idx was already renamed away but before the .cpx->.idx
// rename committed leaves only .cpd + .cpx + .cpc on disk. The directory
// pre-pass must roll the swap FORWARD: finish the renames and produce a
// loadable, writable volume holding the compacted needle count. Before the
// fix there was no marker and the loader simply discarded the orphan temp
// files, losing the entire compacted generation.
func TestReconcileRollForwardMarkerOnly(t *testing.T) {
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapLevelDb, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
const liveCount = 6
for i := uint64(1); i <= liveCount; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
// Delete two so the compacted generation is strictly smaller than the source.
for _, id := range []uint64{2, 5} {
if _, err := v.deleteNeedle2(newEmptyNeedle(id)); err != nil {
t.Fatalf("delete %d: %v", id, err)
}
}
expectedLive := uint64(liveCount - 2)
// Generate a valid .cpd/.cpx pair, then close the volume.
if err := v.CompactByIndex(nil); err != nil {
t.Fatalf("compact by index: %v", err)
}
v.Close()
cpd := filepath.Join(dir, "1.cpd")
cpx := filepath.Join(dir, "1.cpx")
cpc := filepath.Join(dir, "1.cpc")
datPath := filepath.Join(dir, "1.dat")
idxPath := filepath.Join(dir, "1.idx")
mustExist(t, cpd)
mustExist(t, cpx)
// Simulate the mid-commit crash: the original .dat/.idx are gone and only
// the compacted temp files plus the commit marker survive.
if err := os.Remove(datPath); err != nil {
t.Fatalf("remove dat: %v", err)
}
if err := os.Remove(idxPath); err != nil {
t.Fatalf("remove idx: %v", err)
}
os.RemoveAll(filepath.Join(dir, "1.ldb"))
if err := os.WriteFile(cpc, nil, 0644); err != nil {
t.Fatalf("write marker: %v", err)
}
// The directory pre-pass should roll the commit forward.
location := NewDiskLocation(dir, 10, util.MinFreeSpace{}, dir, "", nil, stats.DefaultDiskIOProbeConfig())
defer location.Close()
location.loadExistingVolumes(NeedleMapLevelDb, 0)
mustNotExist(t, cpd)
mustNotExist(t, cpx)
mustNotExist(t, cpc)
mustExist(t, datPath)
mustExist(t, idxPath)
reloaded, found := location.FindVolume(needle.VolumeId(1))
if !found {
t.Fatalf("volume not loaded after roll-forward")
}
if reloaded.IsReadOnly() {
t.Fatalf("rolled-forward volume is read-only")
}
if got := reloaded.FileCount(); got != expectedLive {
t.Fatalf("rolled-forward volume has %d needles, want compacted count %d", got, expectedLive)
}
}
// A crash AFTER .cpd->.dat but BEFORE .cpx->.idx leaves a compacted .dat, a
// stale .idx, and only .cpx + .cpc. The roll-forward must finish the pending
// .cpx->.idx rename, not abandon it -- abandoning pairs the fresh .dat with the
// stale .idx, which is index corruption.
func TestReconcileRollForwardPartialRename(t *testing.T) {
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapLevelDb, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
const liveCount = 6
for i := uint64(1); i <= liveCount; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
for _, id := range []uint64{2, 5} {
if _, err := v.deleteNeedle2(newEmptyNeedle(id)); err != nil {
t.Fatalf("delete %d: %v", id, err)
}
}
expectedLive := uint64(liveCount - 2)
if err := v.CompactByIndex(nil); err != nil {
t.Fatalf("compact by index: %v", err)
}
v.Close()
cpd := filepath.Join(dir, "1.cpd")
cpx := filepath.Join(dir, "1.cpx")
cpc := filepath.Join(dir, "1.cpc")
datPath := filepath.Join(dir, "1.dat")
idxPath := filepath.Join(dir, "1.idx")
// Crash after the .dat rename committed but before the .idx one: .cpd has
// become .dat, the stale pre-compact .idx survives, .cpx and the marker remain.
os.RemoveAll(filepath.Join(dir, "1.ldb"))
if err := os.Remove(datPath); err != nil {
t.Fatalf("remove stale dat: %v", err)
}
if err := os.Rename(cpd, datPath); err != nil {
t.Fatalf("rename cpd->dat: %v", err)
}
if err := os.WriteFile(cpc, nil, 0644); err != nil {
t.Fatalf("write marker: %v", err)
}
mustNotExist(t, cpd)
mustExist(t, cpx)
mustExist(t, idxPath)
location := NewDiskLocation(dir, 10, util.MinFreeSpace{}, dir, "", nil, stats.DefaultDiskIOProbeConfig())
defer location.Close()
location.loadExistingVolumes(NeedleMapLevelDb, 0)
mustNotExist(t, cpx)
mustNotExist(t, cpc)
mustExist(t, datPath)
mustExist(t, idxPath)
reloaded, found := location.FindVolume(needle.VolumeId(1))
if !found {
t.Fatalf("volume not loaded after partial roll-forward")
}
if got := reloaded.FileCount(); got != expectedLive {
t.Fatalf("volume has %d needles, want compacted count %d (pending .cpx->.idx was not rolled forward)", got, expectedLive)
}
}
// With no .cpc marker, leftover .cpd/.cpx are an abandoned generation. The
// pre-pass must roll BACK by deleting them, leaving the live .dat/.idx intact.
func TestReconcileRollBackNoMarker(t *testing.T) {
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
for i := uint64(1); i <= 4; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
if err := v.CompactByIndex(nil); err != nil {
t.Fatalf("compact by index: %v", err)
}
v.Close()
cpd := filepath.Join(dir, "1.cpd")
cpx := filepath.Join(dir, "1.cpx")
datPath := filepath.Join(dir, "1.dat")
idxPath := filepath.Join(dir, "1.idx")
mustExist(t, cpd)
mustExist(t, cpx)
// No .cpc marker exists.
location := NewDiskLocation(dir, 10, util.MinFreeSpace{}, dir, "", nil, stats.DefaultDiskIOProbeConfig())
defer location.Close()
location.loadExistingVolumes(NeedleMapInMemory, 0)
mustNotExist(t, cpd)
mustNotExist(t, cpx)
mustExist(t, datPath)
mustExist(t, idxPath)
reloaded, found := location.FindVolume(needle.VolumeId(1))
if !found {
t.Fatalf("volume not loaded after roll-back")
}
if got := reloaded.FileCount(); got != 4 {
t.Fatalf("rolled-back volume has %d needles, want original 4", got)
}
}
// A runtime reload (SIGHUP -> LoadNewVolumes -> reconcileCompactStates) must
// NOT roll back an in-flight vacuum of an already-loaded volume: its .cpd/.cpx
// are live, not crash leftovers. The pre-pass only reconciles vids not loaded.
func TestReconcileSkipsLoadedVolumeMidVacuum(t *testing.T) {
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
for i := uint64(1); i <= 4; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
v.Close()
// Load the volume as a running server would (populates l.volumes).
location := NewDiskLocation(dir, 10, util.MinFreeSpace{}, dir, "", nil, stats.DefaultDiskIOProbeConfig())
defer location.Close()
location.loadExistingVolumes(NeedleMapInMemory, 0)
loaded, found := location.FindVolume(needle.VolumeId(1))
if !found {
t.Fatalf("volume not loaded")
}
// In-flight vacuum: .cpd/.cpx written, commit (.cpc) not yet reached.
if err := loaded.CompactByIndex(nil); err != nil {
t.Fatalf("compact by index: %v", err)
}
cpd := filepath.Join(dir, "1.cpd")
cpx := filepath.Join(dir, "1.cpx")
mustExist(t, cpd)
mustExist(t, cpx)
// The reload pre-pass must leave the loaded volume's in-flight temp files alone.
location.reconcileCompactStates()
mustExist(t, cpd)
mustExist(t, cpx)
}
// applyCompactSwap must abort without touching the live .dat/.idx when the
// .cpd/.cpx temp files are missing (a stale or duplicate commit). Before the
// fix a late commit on Windows would RemoveAll the .dat/.idx first and then
// fail the rename, destroying the volume.
func TestApplyCompactSwapMissingTempFilesPreservesLive(t *testing.T) {
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
for i := uint64(1); i <= 3; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
v.Close()
datPath := filepath.Join(dir, "1.dat")
idxPath := filepath.Join(dir, "1.idx")
mustExist(t, datPath)
mustExist(t, idxPath)
datBefore, _ := os.Stat(datPath)
// No .cpd/.cpx present: the swap must refuse.
if err := v.applyCompactSwap(); err == nil {
t.Fatalf("applyCompactSwap should error when .cpd/.cpx are missing")
}
mustExist(t, datPath)
mustExist(t, idxPath)
if datAfter, _ := os.Stat(datPath); datAfter.Size() != datBefore.Size() {
t.Fatalf("live .dat changed size: before=%d after=%d", datBefore.Size(), datAfter.Size())
}
}
// Deleting a volume and recreating the same id must not leave a stale .cpc
// behind for the next load to roll forward against. removeVolumeFiles must
// sweep the marker along with the rest.
func TestDestroyRemovesCommitMarker(t *testing.T) {
dir := t.TempDir()
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("volume creation: %v", err)
}
for i := uint64(1); i <= 3; i++ {
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
t.Fatalf("write %d: %v", i, err)
}
}
// Strand a commit marker and its temp files as a crashed commit would.
cpc := filepath.Join(dir, "1.cpc")
cpd := filepath.Join(dir, "1.cpd")
cpx := filepath.Join(dir, "1.cpx")
for _, p := range []string{cpc, cpd, cpx} {
if err := os.WriteFile(p, []byte("x"), 0644); err != nil {
t.Fatalf("write %s: %v", p, err)
}
}
if err := v.Destroy(false, false, false); err != nil {
t.Fatalf("destroy: %v", err)
}
mustNotExist(t, cpc)
mustNotExist(t, cpd)
mustNotExist(t, cpx)
// Recreate the same id and load: there must be no marker to roll forward.
v2, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
if err != nil {
t.Fatalf("recreate volume: %v", err)
}
defer v2.Close()
location := NewDiskLocation(dir, 10, util.MinFreeSpace{}, dir, "", nil, stats.DefaultDiskIOProbeConfig())
defer location.Close()
location.reconcileCompactStates()
mustNotExist(t, cpc)
}
// A VolumeCopy mid-flight writes the same basenames an interrupted commit
// would swap: reconcileCompactStates must skip the vid while the load guard
// reports a copy, and roll the leftover forward once it clears.
func TestReconcileSkipsVidWithCopyInFlight(t *testing.T) {
dir := t.TempDir()
location := NewDiskLocation(dir, 10, util.MinFreeSpace{}, dir, "", nil, stats.DefaultDiskIOProbeConfig())
defer location.Close()
base := filepath.Join(dir, "7")
for _, ext := range []string{".cpc", ".cpd", ".cpx"} {
if err := os.WriteFile(base+ext, []byte("x"), 0644); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(base+".dat", []byte("copy"), 0644); err != nil {
t.Fatal(err)
}
vid := needle.VolumeId(7)
inFlight := true
location.loadGuard = func(v needle.VolumeId) (func(), bool) {
return func() {}, v == vid && inFlight
}
location.reconcileCompactStates()
mustExist(t, base+".cpd")
if got, err := os.ReadFile(base + ".dat"); err != nil || string(got) != "copy" {
t.Fatalf("reconcile rolled a swap over a copy's .dat: %q %v", got, err)
}
inFlight = false
location.reconcileCompactStates()
mustNotExist(t, base+".cpd")
mustExist(t, base+".dat")
}