mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 19:17:28 +01:00
* volume: report the commit-start status while a compaction commit holds the volume CommitCompact holds dataFileAccessLock across makeupDiff and the reload, which on a large volume takes longer than the master's heartbeat timeout. The heartbeat reads every volume of the server through collectStatus, so it waited out the commit and the master unregistered the whole server. The commit now pins the status it starts from, and status reads answer with it until the commit is done, instead of queueing behind its exclusive lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): report the commit-start status while a compaction commit holds the volume The Rust commit closes the needle map and .dat and reloads the compacted files under the io write lock. The heartbeat read each volume's counts through that lock, so it waited out the reload, and between the close and the reload it reported the volume as empty. Mirror the Go change: the commit pins the status it starts from, and collect_status answers with it until the commit is done. The heartbeat reads all of a volume's counts through one collect_status call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: report the compaction revision with the commit-start status The commit reloads the superblock before it lets status reads see the live volume again, so a heartbeat in between paired the new compaction revision with the pinned counts, and the changed hash sent that mixed report. The revision is now part of the status the commit pins, in Go and in Rust. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: size auto-sized disks from the commit-start footprint MaybeAdjustVolumeMax runs just before every heartbeat and, for a disk without a fixed -max, reads each writable volume's .dat and .idx sizes through the data lock, so it still waited out a compaction commit. UnUsedSpace now reads the footprint the commit pinned while one holds the volume, in Go and in Rust. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): recheck expiry from the commit-start status The heartbeat's expiry recheck runs under the store write lock and read the .dat size through the io lock, so a TTL volume that came due while a compaction commit reloaded it held the heartbeat until the reload ended. It now reads the size from collect_status, and delete_volume keeps refusing the committing volume until a later pulse. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: refuse to delete a committing volume without waiting for it Destroy takes the data locks a compaction commit holds across its reload, and the heartbeat deletes expired TTL volumes under the location's volumes lock, so a volume that came due mid-commit stalled the heartbeat. deleteVolumeById now refuses a compacting volume up front, as the Rust volume server's delete_volume does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: claim the volume before Destroy takes its data locks deleteVolumeById checked the compaction flag and only then let Destroy take the data locks, so a commit that claimed the volume in between still made the delete wait out its reload under the volumes lock. CommitCompact claims before it locks, so Destroy now does the same and refuses a claimed volume without waiting; the separate check in deleteVolumeById is no longer needed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): refuse to destroy a volume whose sync lock is held Every destroy runs under the store write guard, and the vacuum-commit RPC takes the sync lock and waits out leased readers before it marks the volume compacting, so an expiry deletion in that window passed the compacting check and then stalled the heartbeat behind the commit. destroy now try-locks the sync lock, as commit_compact does, and a refused deletion keeps the volume mounted for a later pulse. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): keep the CompactionClaim doc on CompactionClaim Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): report a volume a collection delete could not destroy The collection delete logged a refused destroy, kept the volume mounted and still answered success, so the caller never retried. Return the first error after the loop, as the Go store does, while the other volumes of the collection are still deleted. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): claim a volume before the commit and destroy take its locks destroy try-locked the sync lock so a delete under the store write guard would not wait out a commit's reader drain, but every write holds that lock across its fsync, so a volume or collection delete racing an upload was refused. Claim the volume first, as Go's CommitCompact and Destroy do: the commit RPC claims before it takes the sync lock and waits for readers, and destroy claims, waits for the locks only behind writes, and refuses a claimed volume without waiting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: skip the missing-.dat check while a volume is compacting A status read no longer waits out a commit, and on Windows the commit removes the .dat before it renames the compacted one in, so a heartbeat in that gap took the volume for one whose .dat was unlinked and left it out of the report. The commit-start status already stands in for the volume until the commit ends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): skip the missing-.dat check while a volume is compacting Mirrors the Go change: the heartbeat reads the commit-start status without waiting for the commit, and a Windows commit removes the .dat before it renames the compacted one in, so the check dropped the volume from a heartbeat taken in that gap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): keep the new delete and heartbeat tests beside related ones Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: report a compacting volume a collection delete left mounted Destroy refuses a volume a commit has claimed, so the collection delete no longer filters compacting volumes out silently; the refusal is returned and the master keeps the collection to retry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): report a compacting volume a collection delete left mounted Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: confirm a missing .dat under the compaction claim The compaction flag was read before the stat, so a commit starting in between could have its Windows swap taken for a phantom. Stat first and recheck a missing .dat while holding the claim; a held claim defers the verdict to a later heartbeat. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): confirm a missing .dat under the compaction claim Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): expect a collection delete to refuse an in-flight compaction Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1537 lines
51 KiB
Go
1537 lines
51 KiB
Go
package storage
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"math/rand"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"slices"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/testutil"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/stats"
|
|
"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"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
/*
|
|
makediff test steps
|
|
1. launch weed server at your local/dev environment, (option
|
|
"garbageThreshold" for master and option "max" for volume should be set with specific value which would let
|
|
preparing test prerequisite easier )
|
|
a) ./weed master -garbageThreshold=0.99 -mdir=./m
|
|
b) ./weed volume -dir=./data -max=1 -master=localhost:9333 -port=8080
|
|
2. upload 4 different files, you could call dir/assign to get 4 different fids
|
|
a) upload file A with fid a
|
|
b) upload file B with fid b
|
|
c) upload file C with fid c
|
|
d) upload file D with fid d
|
|
3. update file A and C
|
|
a) modify file A and upload file A with fid a
|
|
b) modify file C and upload file C with fid c
|
|
c) record the current 1.idx's file size(lastCompactIndexOffset value)
|
|
4. Compacting the data file
|
|
a) run curl http://localhost:8080/admin/vacuum/compact?volumeId=1
|
|
b) verify the 1.cpd and 1.cpx is created under volume directory
|
|
5. update file B and delete file D
|
|
a) modify file B and upload file B with fid b
|
|
d) delete file B with fid b
|
|
6. Now you could run the following UT case, the case should be run successfully
|
|
7. Compact commit manually
|
|
a) mv 1.cpd 1.dat
|
|
b) mv 1.cpx 1.idx
|
|
8. Restart Volume Server
|
|
9. Now you should get updated file A,B,C
|
|
*/
|
|
|
|
func TestMakeDiff(t *testing.T) {
|
|
|
|
v := new(Volume)
|
|
// lastCompactIndexOffset value is the index file size before step 4
|
|
v.lastCompactIndexOffset = 96
|
|
v.SuperBlock.Version = 0x2
|
|
/*
|
|
err := v.makeupDiff(
|
|
"/yourpath/1.cpd",
|
|
"/yourpath/1.cpx",
|
|
"/yourpath/1.dat",
|
|
"/yourpath/1.idx")
|
|
if err != nil {
|
|
t.Errorf("makeupDiff err is %v", err)
|
|
} else {
|
|
t.Log("makeupDiff Succeeded")
|
|
}
|
|
*/
|
|
}
|
|
|
|
func TestMemIndexCompaction(t *testing.T) {
|
|
testCompactionByIndex(t, NeedleMapInMemory)
|
|
}
|
|
|
|
func TestLDBIndexCompaction(t *testing.T) {
|
|
testCompactionByIndex(t, NeedleMapLevelDb)
|
|
}
|
|
|
|
func testCompactionByIndex(t *testing.T, needleMapKind NeedleMapKind) {
|
|
dir := t.TempDir()
|
|
|
|
v, err := NewVolume(dir, dir, "", 1, needleMapKind, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("volume creation: %v", err)
|
|
}
|
|
|
|
beforeCommitFileCount := 10000
|
|
afterCommitFileCount := 10000
|
|
|
|
infos := make([]*needleInfo, beforeCommitFileCount+afterCommitFileCount)
|
|
|
|
for i := 1; i <= beforeCommitFileCount; i++ {
|
|
doSomeWritesDeletes(i, v, t, infos)
|
|
}
|
|
|
|
startTime := time.Now()
|
|
v.CompactByIndex(nil)
|
|
speed := float64(v.ContentSize()) / time.Now().Sub(startTime).Seconds()
|
|
t.Logf("compaction speed: %.2f bytes/s", speed)
|
|
|
|
// update & delete original objects, upload & delete new objects
|
|
for i := 1; i <= afterCommitFileCount+beforeCommitFileCount; i++ {
|
|
doSomeWritesDeletes(i, v, t, infos)
|
|
}
|
|
v.CommitCompact()
|
|
realRecordCount := v.nm.IndexFileSize() / types.NeedleMapEntrySize
|
|
liveRowCount := uint64(countLiveIndexRows(t, v.FileName(".idx")))
|
|
if needleMapKind == NeedleMapLevelDb {
|
|
nm := reflect.ValueOf(v.nm).Interface().(*LevelDbNeedleMap)
|
|
mm := nm.mapMetric
|
|
watermark := getWatermark(nm.db)
|
|
realWatermark := (nm.recordCount / watermarkBatchSize) * watermarkBatchSize
|
|
t.Logf("watermark from levelDB: %d, realWatermark: %d, nm.recordCount: %d, realRecordCount:%d, fileCount=%d, deletedcount:%d", watermark, realWatermark, nm.recordCount, realRecordCount, mm.FileCount(), v.DeletedCount())
|
|
if realWatermark != watermark {
|
|
t.Fatalf("testing watermark failed")
|
|
}
|
|
} else {
|
|
t.Logf("realRecordCount:%d, liveRowCount:%d, v.FileCount():%d mm.DeletedCount():%d", realRecordCount, liveRowCount, v.FileCount(), v.DeletedCount())
|
|
}
|
|
if liveRowCount != v.FileCount() {
|
|
t.Fatalf("testing file count failed: live idx rows %d, FileCount %d", liveRowCount, v.FileCount())
|
|
}
|
|
|
|
v.Close()
|
|
|
|
v, err = NewVolume(dir, dir, "", 1, needleMapKind, nil, nil, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("volume reloading: %v", err)
|
|
}
|
|
defer v.Close()
|
|
|
|
for i := 1; i <= beforeCommitFileCount+afterCommitFileCount; i++ {
|
|
|
|
if infos[i-1] == nil {
|
|
t.Fatal("not found file", i)
|
|
}
|
|
|
|
if infos[i-1].size == 0 {
|
|
continue
|
|
}
|
|
|
|
n := newEmptyNeedle(uint64(i))
|
|
size, err := v.readNeedle(n, nil, nil)
|
|
if err != nil {
|
|
t.Fatalf("read file %d: %v", i, err)
|
|
}
|
|
if infos[i-1].size != types.Size(size) {
|
|
t.Fatalf("read file %d size mismatch expected %d found %d", i, infos[i-1].size, size)
|
|
}
|
|
if infos[i-1].crc != n.Checksum {
|
|
t.Fatalf("read file %d checksum mismatch expected %d found %d", i, infos[i-1].crc, n.Checksum)
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// A deletion replayed by makeupDiff appends a tombstone to the compacted .dat.
|
|
// When that tombstone is the .dat tail, its .idx entry must carry the real
|
|
// offset, not 0, or the post-commit integrity check can't see the trailing
|
|
// tombstone and wrongly flips the volume read-only — loading a
|
|
// SortedFileNeedleMap instead of the writable LevelDb map.
|
|
func TestCommitCompactDeletionTailKeepsWritable(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)
|
|
}
|
|
|
|
for i := uint64(1); i <= 5; i++ {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
|
|
t.Fatalf("write %d: %v", i, err)
|
|
}
|
|
}
|
|
|
|
v.CompactByIndex(nil)
|
|
|
|
// The sole change in the commit window is a deletion, so makeupDiff appends
|
|
// its tombstone last, putting it at the .dat tail.
|
|
if _, err := v.deleteNeedle2(newEmptyNeedle(3), false); err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("commit compact: %v", err)
|
|
}
|
|
|
|
if _, ok := v.nm.(*LevelDbNeedleMap); !ok {
|
|
t.Fatalf("after compaction v.nm is %T, want *LevelDbNeedleMap (volume wrongly marked read-only)", v.nm)
|
|
}
|
|
v.Close()
|
|
|
|
// Reload from disk to confirm the integrity check passes and the volume
|
|
// stays writable.
|
|
v, err = NewVolume(dir, dir, "", 1, NeedleMapLevelDb, nil, nil, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("reload: %v", err)
|
|
}
|
|
defer v.Close()
|
|
if v.noWriteOrDelete {
|
|
t.Fatal("volume reloaded read-only after a deletion-tail compaction")
|
|
}
|
|
}
|
|
|
|
func TestCommitCompactKeepsEmptyNeedleWrittenDuringCompaction(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)
|
|
}
|
|
defer v.Close()
|
|
|
|
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)
|
|
}
|
|
}
|
|
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
|
|
empty := newEmptyNeedle(10)
|
|
empty.Cookie = 0x0abcdef0
|
|
if _, _, _, err := v.writeNeedle2(empty, true, false, false); err != nil {
|
|
t.Fatalf("write empty needle: %v", err)
|
|
}
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(11), true, false, false); err != nil {
|
|
t.Fatalf("write needle 11: %v", err)
|
|
}
|
|
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("commit compact: %v", err)
|
|
}
|
|
|
|
nv, ok := v.nm.Get(empty.Id)
|
|
if !ok || nv.Size != 0 {
|
|
t.Fatalf("empty needle index entry after commit: %+v found=%v, want size 0", nv, ok)
|
|
}
|
|
record, _, _, err := needle.ReadNeedleHeader(v.DataBackend, v.Version(), nv.Offset.ToActualOffset())
|
|
if err != nil {
|
|
t.Fatalf("read compacted record header: %v", err)
|
|
}
|
|
if record.Id != empty.Id || record.Cookie != empty.Cookie {
|
|
t.Fatalf("compacted record is id %d cookie %x, want the written id %d cookie %x", record.Id, record.Cookie, empty.Id, empty.Cookie)
|
|
}
|
|
|
|
read := newEmptyNeedle(10)
|
|
read.Cookie = empty.Cookie
|
|
if _, err := v.readNeedle(read, nil, nil); err != nil {
|
|
t.Fatalf("read empty needle after commit: %v", err)
|
|
}
|
|
}
|
|
|
|
// A second vacuum must not take a running compaction as its own: reporting
|
|
// success would let it commit or delete the other run's .cpd/.cpx.
|
|
func TestCompactionInProgressRefusesOtherVacuumSteps(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)
|
|
}
|
|
defer v.Close()
|
|
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)
|
|
}
|
|
}
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
|
|
v.isCompactionInProgress.Store(true)
|
|
defer v.isCompactionInProgress.Store(false)
|
|
if err := v.CompactByIndex(nil); err == nil {
|
|
t.Fatal("CompactByIndex succeeded while another compaction is running")
|
|
}
|
|
if err := v.CompactByVolumeData(nil); err == nil {
|
|
t.Fatal("CompactByVolumeData succeeded while another compaction is running")
|
|
}
|
|
if err := v.CommitCompact(); err == nil {
|
|
t.Fatal("CommitCompact succeeded while another compaction is running")
|
|
}
|
|
if err := v.cleanupCompact(); err == nil {
|
|
t.Fatal("cleanupCompact succeeded while another compaction is running")
|
|
}
|
|
for _, ext := range []string{".cpd", ".cpx"} {
|
|
if _, err := os.Stat(v.FileName(ext)); err != nil {
|
|
t.Fatalf("%s of the running compaction: %v", ext, err)
|
|
}
|
|
}
|
|
v.isCompactionInProgress.Store(false)
|
|
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("commit after the compaction finished: %v", err)
|
|
}
|
|
if v.SuperBlock.CompactionRevision != 1 {
|
|
t.Fatalf("compaction revision %d, want 1", v.SuperBlock.CompactionRevision)
|
|
}
|
|
}
|
|
|
|
// A commit that finds no .cpd/.cpx (another vacuum already committed them)
|
|
// must leave the volume loaded, or it drops out of the heartbeat until restart.
|
|
func TestCommitCompactWithoutTempFilesKeepsVolumeLoaded(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)
|
|
}
|
|
defer v.Close()
|
|
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)
|
|
}
|
|
}
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("first commit: %v", err)
|
|
}
|
|
|
|
if err := v.CommitCompact(); err == nil {
|
|
t.Fatal("second commit succeeded without .cpd/.cpx")
|
|
}
|
|
if _, ok := v.collectStatus(); !ok {
|
|
t.Fatal("volume dropped out of the heartbeat after the refused commit")
|
|
}
|
|
if _, err := os.Stat(v.FileName(".cpc")); !os.IsNotExist(err) {
|
|
t.Fatalf("refused commit left a commit marker: %v", err)
|
|
}
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(4), true, false, false); err != nil {
|
|
t.Fatalf("write after the refused commit: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestCommitCompactMakeupDiffFailureKeepsVolumeLoaded(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)
|
|
}
|
|
defer v.Close()
|
|
written := map[uint64]*needle.Needle{}
|
|
for i := uint64(1); i <= 3; i++ {
|
|
written[i] = newRandomNeedle(i)
|
|
if _, _, _, err := v.writeNeedle2(written[i], true, false, false); err != nil {
|
|
t.Fatalf("write %d: %v", i, err)
|
|
}
|
|
}
|
|
// Moves needle 3 in the compacted copy, so reads through its map would miss.
|
|
if _, err := v.deleteNeedle2(newEmptyNeedle(1), false); err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
delete(written, 1)
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
written[4] = newRandomNeedle(4)
|
|
if _, _, _, err := v.writeNeedle2(written[4], true, false, false); err != nil {
|
|
t.Fatalf("write during compaction: %v", err)
|
|
}
|
|
v.lastCompactRevision++
|
|
|
|
if err := v.CommitCompact(); err == nil {
|
|
t.Fatal("commit succeeded with a mismatched compaction revision")
|
|
}
|
|
if _, ok := v.collectStatus(); !ok {
|
|
t.Fatal("volume dropped out of the heartbeat after a failed makeupDiff")
|
|
}
|
|
for i, want := range written {
|
|
got := &needle.Needle{Id: types.NeedleId(i)}
|
|
if _, err := v.readNeedle(got, nil, nil); err != nil {
|
|
t.Fatalf("read %d after the failed commit: %v", i, err)
|
|
}
|
|
if !bytes.Equal(got.Data, want.Data) {
|
|
t.Fatalf("needle %d data changed after the failed commit", i)
|
|
}
|
|
}
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(5), true, false, false); err != nil {
|
|
t.Fatalf("write after the failed commit: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestCompactVolumeFilesOffline(t *testing.T) {
|
|
dir := t.TempDir()
|
|
location := NewDiskLocation(dir, 10, util.MinFreeSpace{}, dir, "", nil, stats.DefaultDiskIOProbeConfig())
|
|
defer location.Close()
|
|
|
|
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)
|
|
}
|
|
|
|
infos := make([]*needleInfo, 32)
|
|
for i := 1; i <= 32; i++ {
|
|
doSomeWritesDeletes(i, v, t, infos)
|
|
}
|
|
v.Close()
|
|
|
|
store := &Store{}
|
|
if err := store.CompactVolumeFiles(needle.VolumeId(1), "", location, NeedleMapInMemory, 0, 0, 0); err != nil {
|
|
t.Fatalf("CompactVolumeFiles: %v", err)
|
|
}
|
|
|
|
reloaded, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, nil, nil, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("volume reload: %v", err)
|
|
}
|
|
defer reloaded.Close()
|
|
|
|
if _, err := os.Stat(filepath.Join(dir, "1.cpd")); !os.IsNotExist(err) {
|
|
t.Fatalf("expected no .cpd after successful offline compaction, got err=%v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "1.cpx")); !os.IsNotExist(err) {
|
|
t.Fatalf("expected no .cpx after successful offline compaction, got err=%v", err)
|
|
}
|
|
}
|
|
|
|
func TestCleanupCompactRemovesTempFiles(t *testing.T) {
|
|
dir := t.TempDir()
|
|
location := NewDiskLocation(dir, 10, util.MinFreeSpace{}, dir, "", nil, stats.DefaultDiskIOProbeConfig())
|
|
defer location.Close()
|
|
|
|
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)
|
|
}
|
|
|
|
infos := make([]*needleInfo, 16)
|
|
for i := 1; i <= 16; i++ {
|
|
doSomeWritesDeletes(i, v, t, infos)
|
|
}
|
|
v.Close()
|
|
|
|
if err := os.WriteFile(filepath.Join(dir, "1.cpx"), []byte("broken"), 0o644); err != nil {
|
|
t.Fatalf("write broken cpx: %v", err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(dir, "1.cpd"), []byte("temp"), 0o644); err != nil {
|
|
t.Fatalf("write cpd: %v", err)
|
|
}
|
|
if err := os.Mkdir(filepath.Join(dir, "1.cpldb"), 0o755); err != nil {
|
|
t.Fatalf("mkdir cpldb: %v", err)
|
|
}
|
|
|
|
tempVolume, err := loadVolumeWithoutWorker(dir, dir, "", needle.VolumeId(1), NeedleMapInMemory, 0)
|
|
if err != nil {
|
|
t.Fatalf("loadVolumeWithoutWorker: %v", err)
|
|
}
|
|
tempVolume.location = location
|
|
defer tempVolume.doClose()
|
|
|
|
if err := tempVolume.cleanupCompact(); err != nil {
|
|
t.Fatalf("cleanupCompact: %v", err)
|
|
}
|
|
if tempVolume.isCompactionInProgress.Load() {
|
|
t.Fatal("cleanupCompact kept the volume claimed")
|
|
}
|
|
|
|
if _, err := os.Stat(filepath.Join(dir, "1.cpd")); !os.IsNotExist(err) {
|
|
t.Fatalf("expected cleanup to remove .cpd, got err=%v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "1.cpx")); !os.IsNotExist(err) {
|
|
t.Fatalf("expected cleanup to remove .cpx, got err=%v", err)
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "1.cpldb")); !os.IsNotExist(err) {
|
|
t.Fatalf("expected cleanup to remove .cpldb, got err=%v", err)
|
|
}
|
|
}
|
|
|
|
// TestCompactByIndex_DropsDanglingNeedle verifies that vacuum compaction
|
|
// tolerates an .idx entry whose offset points past the end of the .dat file
|
|
// (the failure mode reported in issue #8928). The bad entry should be silently
|
|
// dropped from the resulting .cpx, while every healthy needle is preserved.
|
|
func TestCompactByIndex_DropsDanglingNeedle(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)
|
|
}
|
|
|
|
const goodNeedleCount = 8
|
|
infos := make([]*needleInfo, goodNeedleCount)
|
|
for i := 1; i <= goodNeedleCount; i++ {
|
|
n := newRandomNeedle(uint64(i))
|
|
_, size, _, err := v.writeNeedle2(n, true, false, false)
|
|
if err != nil {
|
|
t.Fatalf("write needle %d: %v", i, err)
|
|
}
|
|
infos[i-1] = &needleInfo{size: size, crc: n.Checksum}
|
|
}
|
|
|
|
if err := v.DataBackend.Sync(); err != nil {
|
|
t.Fatalf("sync .dat: %v", err)
|
|
}
|
|
if err := v.nm.Sync(); err != nil {
|
|
t.Fatalf("sync .idx: %v", err)
|
|
}
|
|
|
|
datSize, _, err := v.DataBackend.GetStat()
|
|
if err != nil {
|
|
t.Fatalf("stat .dat: %v", err)
|
|
}
|
|
|
|
// Inject an .idx entry that points 1 MB past the end of the .dat. The
|
|
// bad entry must go through nm.Put so it ends up in both the in-memory
|
|
// map and the on-disk .idx — exactly the corruption pattern in #8928.
|
|
badKey := types.Uint64ToNeedleId(uint64(goodNeedleCount + 100))
|
|
badOffset := types.ToOffset(datSize + 1024*1024)
|
|
badSize := types.Size(2048)
|
|
if err := v.nm.Put(badKey, badOffset, badSize); err != nil {
|
|
t.Fatalf("inject bad idx entry: %v", err)
|
|
}
|
|
if err := v.nm.Sync(); err != nil {
|
|
t.Fatalf("sync .idx after inject: %v", err)
|
|
}
|
|
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("CompactByIndex should tolerate dangling entries, got: %v", err)
|
|
}
|
|
|
|
// Walk the new index and confirm the dangling entry was dropped while
|
|
// all of the original keys made it through.
|
|
cpx, err := os.Open(filepath.Join(dir, "1.cpx"))
|
|
if err != nil {
|
|
t.Fatalf("open .cpx: %v", err)
|
|
}
|
|
defer cpx.Close()
|
|
keptKeys := map[types.NeedleId]bool{}
|
|
if err := idx.WalkIndexFile(cpx, 0, func(key types.NeedleId, _ types.Offset, size types.Size) error {
|
|
if !size.IsDeleted() {
|
|
keptKeys[key] = true
|
|
}
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("walk .cpx: %v", err)
|
|
}
|
|
if keptKeys[badKey] {
|
|
t.Fatalf("dangling key %d should have been dropped from .cpx", badKey)
|
|
}
|
|
for i := 1; i <= goodNeedleCount; i++ {
|
|
if infos[i-1].size == 0 {
|
|
continue
|
|
}
|
|
k := types.Uint64ToNeedleId(uint64(i))
|
|
if !keptKeys[k] {
|
|
t.Fatalf("healthy key %d missing from compacted .cpx", k)
|
|
}
|
|
}
|
|
|
|
v.Close()
|
|
}
|
|
|
|
// A needle whose body fails its CRC is dropped from the compacted index, and
|
|
// the drop is counted per collection.
|
|
func TestCompactByIndex_CountsDroppedCrcDamagedNeedle(t *testing.T) {
|
|
dir := t.TempDir()
|
|
const collection = "vacuum_crc_drop"
|
|
|
|
v, err := NewVolume(dir, dir, collection, 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("volume creation: %v", err)
|
|
}
|
|
defer v.Close()
|
|
|
|
for i := uint64(1); i <= 3; i++ {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
|
|
t.Fatalf("write needle %d: %v", i, err)
|
|
}
|
|
}
|
|
damagedKey := types.Uint64ToNeedleId(2)
|
|
nv, ok := v.nm.Get(damagedKey)
|
|
if !ok {
|
|
t.Fatalf("needle %d not in index", damagedKey)
|
|
}
|
|
// The first body byte follows the header and the 4-byte DataSize field.
|
|
at := nv.Offset.ToActualOffset() + types.NeedleHeaderSize + 4
|
|
b := make([]byte, 1)
|
|
if _, err := v.DataBackend.ReadAt(b, at); err != nil {
|
|
t.Fatalf("read body byte: %v", err)
|
|
}
|
|
b[0] ^= 0xff
|
|
if _, err := v.DataBackend.WriteAt(b, at); err != nil {
|
|
t.Fatalf("damage body byte: %v", err)
|
|
}
|
|
if err := v.DataBackend.Sync(); err != nil {
|
|
t.Fatalf("sync .dat: %v", err)
|
|
}
|
|
if err := v.nm.Sync(); err != nil {
|
|
t.Fatalf("sync .idx: %v", err)
|
|
}
|
|
|
|
dropped := stats.VolumeServerVacuumingDroppedNeedlesCounter.WithLabelValues(collection)
|
|
before := testutil.ToFloat64(dropped)
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("CompactByIndex: %v", err)
|
|
}
|
|
if got := testutil.ToFloat64(dropped) - before; got != 1 {
|
|
t.Fatalf("dropped needle counter moved by %v, want 1", got)
|
|
}
|
|
|
|
cpx, err := os.Open(filepath.Join(dir, collection+"_1.cpx"))
|
|
if err != nil {
|
|
t.Fatalf("open .cpx: %v", err)
|
|
}
|
|
defer cpx.Close()
|
|
kept := map[types.NeedleId]bool{}
|
|
if err := idx.WalkIndexFile(cpx, 0, func(key types.NeedleId, _ types.Offset, size types.Size) error {
|
|
if !size.IsDeleted() {
|
|
kept[key] = true
|
|
}
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("walk .cpx: %v", err)
|
|
}
|
|
if kept[damagedKey] || !kept[types.Uint64ToNeedleId(1)] || !kept[types.Uint64ToNeedleId(3)] {
|
|
t.Fatalf("compacted keys = %v, want 1 and 3 only", kept)
|
|
}
|
|
}
|
|
|
|
// TestCompactByIndex_ConcurrentWriteDoesNotFailIntegrityCheck reproduces the
|
|
// vacuum-vs-live-traffic race: a needle written to the volume after
|
|
// CompactByIndex has already loaded its point-in-time index snapshot must not
|
|
// trip the post-copy integrity check. CommitCompact's makeupDiff is what
|
|
// reconciles a write landing mid-copy (see TestCommitCompactDeletionTailKeepsWritable);
|
|
// the copy-phase check must not treat that expected case as corruption.
|
|
func TestCompactByIndex_ConcurrentWriteDoesNotFailIntegrityCheck(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)
|
|
}
|
|
defer v.Close()
|
|
|
|
for i := 1; i <= 8; i++ {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false, false); err != nil {
|
|
t.Fatalf("write needle %d: %v", i, err)
|
|
}
|
|
}
|
|
|
|
wroteConcurrently := false
|
|
opts := &CompactOptions{
|
|
ProgressCallback: func(processed int64) bool {
|
|
if !wroteConcurrently {
|
|
wroteConcurrently = true
|
|
// Simulate a client write landing on the live volume while
|
|
// CompactByIndex is still copying the pre-write snapshot.
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(100)), true, false, false); err != nil {
|
|
t.Fatalf("concurrent write: %v", err)
|
|
}
|
|
}
|
|
return true
|
|
},
|
|
}
|
|
|
|
if err := v.CompactByIndex(opts); err != nil {
|
|
t.Fatalf("CompactByIndex should tolerate a write that lands mid-copy, got: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestCompactByVolumeData_SkipsNegativeSizeHeader covers issue #6763: a .dat
|
|
// record whose header carries size -1 made compaction panic with "slice bounds
|
|
// out of range [:-1]". The corrupt record must be skipped and the needles on
|
|
// both sides of it kept.
|
|
func TestCompactByVolumeData_SkipsNegativeSizeHeader(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)
|
|
}
|
|
defer v.Close()
|
|
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false, false); err != nil {
|
|
t.Fatalf("write needle 1: %v", err)
|
|
}
|
|
|
|
// Size -1 still yields a positive body length, so the scan reads a body
|
|
// for this record and parses it.
|
|
datSize, _, err := v.DataBackend.GetStat()
|
|
if err != nil {
|
|
t.Fatalf("stat .dat: %v", err)
|
|
}
|
|
corrupt := make([]byte, needle.GetActualSize(-1, v.Version()))
|
|
types.NeedleIdToBytes(corrupt[types.CookieSize:types.CookieSize+types.NeedleIdSize], types.Uint64ToNeedleId(99))
|
|
types.SizeToBytes(corrupt[types.CookieSize+types.NeedleIdSize:types.NeedleHeaderSize], -1)
|
|
if _, err := v.DataBackend.WriteAt(corrupt, datSize); err != nil {
|
|
t.Fatalf("append corrupt record: %v", err)
|
|
}
|
|
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(2), true, false, false); err != nil {
|
|
t.Fatalf("write needle 2: %v", err)
|
|
}
|
|
|
|
if err := v.CompactByVolumeData(nil); err != nil {
|
|
t.Fatalf("CompactByVolumeData: %v", err)
|
|
}
|
|
|
|
cpx, err := os.Open(filepath.Join(dir, "1.cpx"))
|
|
if err != nil {
|
|
t.Fatalf("open .cpx: %v", err)
|
|
}
|
|
defer cpx.Close()
|
|
kept := map[types.NeedleId]bool{}
|
|
if err := idx.WalkIndexFile(cpx, 0, func(key types.NeedleId, _ types.Offset, size types.Size) error {
|
|
if size.IsValid() {
|
|
kept[key] = true
|
|
}
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("walk .cpx: %v", err)
|
|
}
|
|
for _, id := range []uint64{1, 2} {
|
|
if !kept[types.Uint64ToNeedleId(id)] {
|
|
t.Errorf("needle %d missing from the compacted index", id)
|
|
}
|
|
}
|
|
if kept[types.Uint64ToNeedleId(99)] {
|
|
t.Errorf("corrupt record 99 should not be in the compacted index")
|
|
}
|
|
}
|
|
|
|
// A corrupt header the scan cannot advance past is skipped: compaction resumes
|
|
// at the next live record and leaves the original volume untouched.
|
|
func TestCompactByVolumeData_SkipsHeaderThatCannotAdvance(t *testing.T) {
|
|
for _, size := range []types.Size{-36, -100} {
|
|
t.Run(fmt.Sprintf("size%d", size), func(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)
|
|
}
|
|
stuck := false
|
|
defer func() {
|
|
if !stuck {
|
|
v.Close() // blocks until a running compaction ends
|
|
}
|
|
}()
|
|
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false, false); err != nil {
|
|
t.Fatalf("write needle 1: %v", err)
|
|
}
|
|
datSize, _, err := v.DataBackend.GetStat()
|
|
if err != nil {
|
|
t.Fatalf("stat .dat: %v", err)
|
|
}
|
|
corrupt := make([]byte, types.NeedleHeaderSize)
|
|
types.NeedleIdToBytes(corrupt[types.CookieSize:types.CookieSize+types.NeedleIdSize], types.Uint64ToNeedleId(99))
|
|
types.SizeToBytes(corrupt[types.CookieSize+types.NeedleIdSize:], size)
|
|
if _, err := v.DataBackend.WriteAt(corrupt, datSize); err != nil {
|
|
t.Fatalf("append corrupt header: %v", err)
|
|
}
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(2), true, false, false); err != nil {
|
|
t.Fatalf("write needle 2: %v", err)
|
|
}
|
|
datBefore, err := os.ReadFile(v.FileName(".dat"))
|
|
if err != nil {
|
|
t.Fatalf("read .dat: %v", err)
|
|
}
|
|
|
|
err = runWithTimeout(10*time.Second, func() error { return v.CompactByVolumeData(nil) })
|
|
if errors.Is(err, errDidNotReturn) {
|
|
stuck = true
|
|
t.Fatalf("CompactByVolumeData: %v", err)
|
|
}
|
|
if err != nil {
|
|
t.Fatalf("CompactByVolumeData: %v", err)
|
|
}
|
|
|
|
cpx, err := os.Open(v.FileName(".cpx"))
|
|
if err != nil {
|
|
t.Fatalf("open .cpx: %v", err)
|
|
}
|
|
var kept []types.NeedleId
|
|
if err := idx.WalkIndexFile(cpx, 0, func(key types.NeedleId, _ types.Offset, size types.Size) error {
|
|
if size.IsValid() {
|
|
kept = append(kept, key)
|
|
}
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("walk .cpx: %v", err)
|
|
}
|
|
cpx.Close()
|
|
if want := []types.NeedleId{1, 2}; !slices.Equal(kept, want) {
|
|
t.Errorf("compacted index holds %v, want %v", kept, want)
|
|
}
|
|
datAfter, err := os.ReadFile(v.FileName(".dat"))
|
|
if err != nil {
|
|
t.Fatalf("read .dat: %v", err)
|
|
}
|
|
if !bytes.Equal(datBefore, datAfter) {
|
|
t.Errorf(".dat changed: %d bytes before, %d after", len(datBefore), len(datAfter))
|
|
}
|
|
for _, id := range []uint64{1, 2} {
|
|
n := &needle.Needle{Id: types.Uint64ToNeedleId(id)}
|
|
if _, err := v.readNeedle(n, &ReadOption{}, nil); err != nil {
|
|
t.Errorf("read needle %d from the original volume: %v", id, err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestExceedsExpectedCompactedSize guards the copy-phase integrity check
|
|
// against regressing into double-subtracting skipped bytes: expectedLiveBytes
|
|
// already excludes needles dropped as unreadable (they return before being
|
|
// added to the tally), so the check must compare it directly against the
|
|
// compacted .dat size, with no further adjustment for skipped bytes.
|
|
func TestExceedsExpectedCompactedSize(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
expectedLiveBytes uint64
|
|
dstDatSize int64
|
|
wantExceeds bool
|
|
}{
|
|
{"destination matches expected size exactly", 100, 100, false},
|
|
{"destination larger than expected is fine", 100, 150, false},
|
|
{"destination short of expected signals data loss", 100, 90, true},
|
|
}
|
|
for _, c := range cases {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
if got := exceedsExpectedCompactedSize(c.expectedLiveBytes, c.dstDatSize); got != c.wantExceeds {
|
|
t.Fatalf("exceedsExpectedCompactedSize(%d, %d) = %v, want %v", c.expectedLiveBytes, c.dstDatSize, got, c.wantExceeds)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func countLiveIndexRows(t *testing.T, indexFileName string) int {
|
|
t.Helper()
|
|
f, err := os.Open(indexFileName)
|
|
if err != nil {
|
|
t.Fatalf("open index file %s: %v", indexFileName, err)
|
|
}
|
|
defer f.Close()
|
|
count := 0
|
|
if err := idx.WalkIndexFile(f, 0, func(key types.NeedleId, offset types.Offset, size types.Size) error {
|
|
if !offset.IsZero() && !size.IsDeleted() {
|
|
count++
|
|
}
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("walk index file %s: %v", indexFileName, err)
|
|
}
|
|
return count
|
|
}
|
|
|
|
func doSomeWritesDeletes(i int, v *Volume, t *testing.T, infos []*needleInfo) {
|
|
n := newRandomNeedle(uint64(i))
|
|
_, size, _, err := v.writeNeedle2(n, true, false, false)
|
|
if err != nil {
|
|
t.Fatalf("write file %d: %v", i, err)
|
|
}
|
|
infos[i-1] = &needleInfo{
|
|
size: size,
|
|
crc: n.Checksum,
|
|
}
|
|
// println("written file", i, "checksum", n.Checksum.Value(), "size", size)
|
|
if rand.Float64() < 0.03 {
|
|
toBeDeleted := rand.Intn(i) + 1
|
|
oldNeedle := newEmptyNeedle(uint64(toBeDeleted))
|
|
v.deleteNeedle2(oldNeedle, false)
|
|
// println("deleted file", toBeDeleted)
|
|
infos[toBeDeleted-1] = &needleInfo{
|
|
size: 0,
|
|
crc: n.Checksum,
|
|
}
|
|
}
|
|
}
|
|
|
|
type needleInfo struct {
|
|
size types.Size
|
|
crc needle.CRC
|
|
}
|
|
|
|
func newRandomNeedle(id uint64) *needle.Needle {
|
|
n := new(needle.Needle)
|
|
// never zero bytes: an empty needle writes a size-0 .dat record, indistinguishable from a delete marker
|
|
n.Data = make([]byte, 1+rand.Intn(1023))
|
|
rand.Read(n.Data)
|
|
|
|
n.Checksum = needle.NewCRC(n.Data)
|
|
n.Id = types.Uint64ToNeedleId(id)
|
|
return n
|
|
}
|
|
|
|
func newEmptyNeedle(id uint64) *needle.Needle {
|
|
n := new(needle.Needle)
|
|
n.Id = types.Uint64ToNeedleId(id)
|
|
return n
|
|
}
|
|
|
|
// A run of records whose header ids are damaged but whose sizes are intact:
|
|
// data compaction keeps the records around it, and resuming at each damaged
|
|
// record does not walk the rest of the run again, so the resumed scans read
|
|
// each header once instead of once per later resume.
|
|
func TestCompactByVolumeData_SkipsRunOfDamagedIds(t *testing.T) {
|
|
const run = 32
|
|
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)
|
|
}
|
|
defer v.Close()
|
|
var offsets []int64
|
|
for i := 1; i <= run+2; i++ {
|
|
offset, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false, false)
|
|
if err != nil {
|
|
t.Fatalf("write needle %d: %v", i, err)
|
|
}
|
|
offsets = append(offsets, int64(offset))
|
|
}
|
|
damagedId := bytes.Repeat([]byte{0xa5}, types.NeedleIdSize)
|
|
for _, offset := range offsets[1 : run+1] {
|
|
if _, err := v.DataBackend.WriteAt(damagedId, offset+types.CookieSize); err != nil {
|
|
t.Fatalf("damage id at %d: %v", offset, err)
|
|
}
|
|
}
|
|
reads := &countingBackend{BackendStorageFile: v.DataBackend}
|
|
v.DataBackend = reads
|
|
|
|
if err := v.CompactByVolumeData(nil); err != nil {
|
|
t.Fatalf("CompactByVolumeData: %v", err)
|
|
}
|
|
|
|
cpx, err := os.Open(v.FileName(".cpx"))
|
|
if err != nil {
|
|
t.Fatalf("open .cpx: %v", err)
|
|
}
|
|
defer cpx.Close()
|
|
var kept []types.NeedleId
|
|
if err := idx.WalkIndexFile(cpx, 0, func(key types.NeedleId, _ types.Offset, _ types.Size) error {
|
|
kept = append(kept, key)
|
|
return nil
|
|
}); err != nil {
|
|
t.Fatalf("walk .cpx: %v", err)
|
|
}
|
|
if want := []types.NeedleId{1, run + 2}; !slices.Equal(kept, want) {
|
|
t.Errorf("compacted index holds %v, want %v", kept, want)
|
|
}
|
|
// The main scan reads through its own handle; the copies of the two kept
|
|
// records and the resumed scans read through v.DataBackend.
|
|
if reads.readCount > 2*run {
|
|
t.Errorf("resumed scans made %d reads for a run of %d damaged headers", reads.readCount, run)
|
|
}
|
|
}
|
|
|
|
func TestVacuumKeepsUnexpiredNeedleTtlOnPlainVolume(t *testing.T) {
|
|
for _, method := range []string{"index", "data"} {
|
|
t.Run(method, func(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)
|
|
}
|
|
defer v.Close()
|
|
for i := 1; i <= 8; i++ {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false, false); err != nil {
|
|
t.Fatalf("write needle %d: %v", i, err)
|
|
}
|
|
}
|
|
n := newRandomNeedle(100)
|
|
n.Ttl, _ = needle.ReadTTL("7d")
|
|
n.SetHasTtl()
|
|
n.LastModified = uint64(time.Now().Unix())
|
|
n.SetHasLastModifiedDate()
|
|
if _, _, _, err := v.writeNeedle2(n, true, false, false); err != nil {
|
|
t.Fatalf("write ttl needle: %v", err)
|
|
}
|
|
compact := v.CompactByIndex
|
|
if method == "data" {
|
|
compact = v.CompactByVolumeData
|
|
}
|
|
if err := compact(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("commit: %v", err)
|
|
}
|
|
if _, err := v.readNeedle(&needle.Needle{Id: 100}, nil, nil); err != nil {
|
|
t.Fatalf("needle with an unexpired 7d TTL was removed by vacuum: %v", err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestIsVacuumTtlExpired(t *testing.T) {
|
|
now := time.Now()
|
|
ttl7d, _ := needle.ReadTTL("7d")
|
|
ttl1h, _ := needle.ReadTTL("1h")
|
|
newTtlNeedle := func(ttl *needle.TTL, age time.Duration) *needle.Needle {
|
|
n := &needle.Needle{Ttl: ttl}
|
|
n.SetHasTtl()
|
|
n.SetHasLastModifiedDate()
|
|
n.LastModified = uint64(now.Add(-age).Unix())
|
|
n.AppendAtNs = uint64(now.Add(-age).UnixNano())
|
|
return n
|
|
}
|
|
noTtl := &needle.TTL{}
|
|
tests := []struct {
|
|
name string
|
|
n *needle.Needle
|
|
volumeTtl *needle.TTL
|
|
want bool
|
|
}{
|
|
{"no ttl flag", &needle.Needle{}, ttl1h, false},
|
|
{"own ttl not expired on plain volume", newTtlNeedle(ttl7d, time.Hour), noTtl, false},
|
|
{"own ttl expired on plain volume", newTtlNeedle(ttl1h, 2*time.Hour), noTtl, true},
|
|
{"own ttl zero on plain volume", newTtlNeedle(noTtl, 48*time.Hour), noTtl, false},
|
|
{"ttl flag without ttl bytes", newTtlNeedle(nil, 48*time.Hour), noTtl, false},
|
|
{"nil volume ttl uses own ttl", newTtlNeedle(ttl1h, 2*time.Hour), nil, true},
|
|
{"volume ttl not expired", newTtlNeedle(ttl1h, 30*time.Minute), ttl1h, false},
|
|
{"volume ttl expired", newTtlNeedle(ttl7d, 2*time.Hour), ttl1h, true},
|
|
}
|
|
for _, tt := range tests {
|
|
if got := isVacuumTtlExpired(tt.n, tt.volumeTtl, now); got != tt.want {
|
|
t.Errorf("%s: isVacuumTtlExpired = %v, want %v", tt.name, got, tt.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLoadIdxSnapshotTalliesLiveEntries(t *testing.T) {
|
|
idxPath := filepath.Join(t.TempDir(), "1.idx")
|
|
var rows []byte
|
|
appendRow := func(key uint64, offset int64, size types.Size) {
|
|
rows = append(rows, needle_map.ToBytes(types.Uint64ToNeedleId(key), types.ToOffset(offset), size)...)
|
|
}
|
|
appendRow(1, 8, 100)
|
|
appendRow(2, 200, 50)
|
|
appendRow(1, 400, 120) // overwrite
|
|
appendRow(2, 0, types.TombstoneFileSize)
|
|
appendRow(3, 600, 0) // empty needle stays live
|
|
appendRow(4, 800, 70)
|
|
appendRow(4, 800, -70)
|
|
appendRow(4, 900, 30) // re-put after delete
|
|
if err := os.WriteFile(idxPath, rows, 0644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
nm := needle_map.NewMemDb()
|
|
defer nm.Close()
|
|
live, err := loadIdxSnapshot(nm, idxPath)
|
|
if err != nil {
|
|
t.Fatalf("loadIdxSnapshot: %v", err)
|
|
}
|
|
if live.count != 3 || live.bytes != 150 {
|
|
t.Fatalf("tally = %+v, want 3 entries, 150 bytes", live)
|
|
}
|
|
visited := 0
|
|
if err := nm.AscendingVisit(func(needle_map.NeedleValue) error { visited++; return nil }); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if visited != live.count {
|
|
t.Fatalf("map holds %d entries, tally %d", visited, live.count)
|
|
}
|
|
}
|
|
|
|
func TestCheckCompactedAgainstSnapshot(t *testing.T) {
|
|
snapshot := liveTally{count: 4, bytes: 400}
|
|
tests := []struct {
|
|
name string
|
|
copied, expired, unreadable liveTally
|
|
dstDatSize int64
|
|
wantErr bool
|
|
}{
|
|
{"all copied", liveTally{4, 400}, liveTally{}, liveTally{}, 500, false},
|
|
{"expired and unreadable accounted", liveTally{2, 200}, liveTally{1, 100}, liveTally{1, 100}, 260, false},
|
|
{"traversal skipped entries", liveTally{2, 200}, liveTally{}, liveTally{}, 260, true},
|
|
{"short write", liveTally{4, 400}, liveTally{}, liveTally{}, 300, true},
|
|
{"drops exceed snapshot bytes", liveTally{0, 0}, liveTally{2, 300}, liveTally{2, 300}, 8, true},
|
|
}
|
|
for _, tt := range tests {
|
|
err := checkCompactedAgainstSnapshot(1, snapshot, tt.copied, tt.expired, tt.unreadable, tt.dstDatSize)
|
|
if (err != nil) != tt.wantErr {
|
|
t.Errorf("%s: err = %v, wantErr %v", tt.name, err, tt.wantErr)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCompactByIndexChecksTtlVolume(t *testing.T) {
|
|
dir := t.TempDir()
|
|
ttl, _ := needle.ReadTTL("1h")
|
|
v, err := NewVolume(dir, dir, "", 1, NeedleMapInMemory, &super_block.ReplicaPlacement{}, ttl, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("volume creation: %v", err)
|
|
}
|
|
defer v.Close()
|
|
for i := 1; i <= 8; i++ {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(uint64(i)), true, false, false); err != nil {
|
|
t.Fatalf("write needle %d: %v", i, err)
|
|
}
|
|
}
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("CompactByIndex: %v", err)
|
|
}
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("commit: %v", err)
|
|
}
|
|
for i := 1; i <= 8; i++ {
|
|
if _, err := v.readNeedle(&needle.Needle{Id: types.Uint64ToNeedleId(uint64(i))}, nil, nil); err != nil {
|
|
t.Fatalf("read needle %d after compaction: %v", i, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A read-only volume reloads into a sorted map after its compaction, so the
|
|
// compacted map goes unused: it must not stay in memory, and its .cpldb must
|
|
// not seed the leveldb map of a later compaction with needles deleted since.
|
|
func TestCommitCompactReadOnlyDropsTmpNeedleMap(t *testing.T) {
|
|
for _, kind := range []NeedleMapKind{NeedleMapInMemory, NeedleMapLevelDb} {
|
|
t.Run(fmt.Sprint(kind), func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
store := newSingleDirStore(t, dir)
|
|
defer store.Close()
|
|
const vid = needle.VolumeId(5)
|
|
v, err := NewVolume(dir, dir, "", vid, kind, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("volume creation: %v", err)
|
|
}
|
|
store.Locations[0].SetVolume(vid, v)
|
|
var needles []*needle.Needle
|
|
for i := uint64(1); i <= 6; i++ {
|
|
n := newRandomNeedle(i)
|
|
if _, err := store.WriteVolumeNeedle(vid, n, true, false); err != nil {
|
|
t.Fatalf("write needle %d: %v", i, err)
|
|
}
|
|
needles = append(needles, n)
|
|
}
|
|
compact := func() {
|
|
t.Helper()
|
|
if err := store.CompactVolume(vid, 0, 0, nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
if _, _, err := store.CommitCompactVolume(vid); err != nil {
|
|
t.Fatalf("commit: %v", err)
|
|
}
|
|
}
|
|
deleteNeedle := func(n *needle.Needle) {
|
|
t.Helper()
|
|
if _, err := store.DeleteVolumeNeedle(vid, n, false); err != nil {
|
|
t.Fatalf("delete needle %d: %v", n.Id, err)
|
|
}
|
|
}
|
|
|
|
if err := store.MarkVolumeReadonly(vid, true, false); err != nil {
|
|
t.Fatalf("mark readonly: %v", err)
|
|
}
|
|
deleteNeedle(needles[0])
|
|
compact()
|
|
if v.tmpNm != nil {
|
|
t.Fatalf("the compacted map of a read-only volume is still held: %T", v.tmpNm)
|
|
}
|
|
if _, err := os.Stat(v.FileName(".cpldb")); !os.IsNotExist(err) {
|
|
t.Fatalf(".cpldb left after a read-only commit: %v", err)
|
|
}
|
|
|
|
deleteNeedle(needles[1])
|
|
if err := store.MarkVolumeWritable(vid); err != nil {
|
|
t.Fatalf("mark writable: %v", err)
|
|
}
|
|
deleteNeedle(needles[2])
|
|
compact()
|
|
for i, n := range needles {
|
|
_, err := store.ReadVolumeNeedle(vid, newEmptyNeedle(uint64(n.Id)), nil, nil)
|
|
if i < 3 && !errors.Is(err, ErrorNotFound) {
|
|
t.Fatalf("deleted needle %d: got %v, want not found", n.Id, err)
|
|
}
|
|
if i >= 3 && err != nil {
|
|
t.Fatalf("read needle %d: %v", n.Id, err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// A vacuum erases deleted needles and their delete markers. What it records is
|
|
// the largest id among everything the index held, the erased ones included:
|
|
// volume.check.disk takes a needle with a larger id that the volume lacks for
|
|
// one never written to it.
|
|
func TestVacuumRecordsLargestNeedleIdItCouldHaveErased(t *testing.T) {
|
|
for _, kind := range []NeedleMapKind{NeedleMapInMemory, NeedleMapLevelDb} {
|
|
t.Run(fmt.Sprint(kind), func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
v, err := NewVolume(dir, dir, "", 1, kind, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("volume creation: %v", err)
|
|
}
|
|
write := func(ids ...uint64) {
|
|
t.Helper()
|
|
for _, id := range ids {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false, false); err != nil {
|
|
t.Fatalf("write %d: %v", id, err)
|
|
}
|
|
}
|
|
}
|
|
remove := func(ids ...uint64) {
|
|
t.Helper()
|
|
for _, id := range ids {
|
|
if _, err := v.deleteNeedle2(newEmptyNeedle(id), false); err != nil {
|
|
t.Fatalf("delete %d: %v", id, err)
|
|
}
|
|
}
|
|
}
|
|
vacuum := func() {
|
|
t.Helper()
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("commit compact: %v", err)
|
|
}
|
|
}
|
|
recorded := func(want uint64, when string) {
|
|
t.Helper()
|
|
revision := uint32(v.SuperBlock.CompactionRevision)
|
|
if got := v.volumeInfo.VacuumedMaxFileKey; got != want {
|
|
t.Fatalf("%s: recorded id %d, want %d", when, got, want)
|
|
}
|
|
if got := v.volumeInfo.VacuumedCompactionRevision; got != revision {
|
|
t.Fatalf("%s: recorded for revision %d, the volume is at %d", when, got, revision)
|
|
}
|
|
onDisk, _, _, err := volume_info.MaybeLoadVolumeInfo(v.FileName(".vif"))
|
|
if err != nil {
|
|
t.Fatalf("%s: read .vif: %v", when, err)
|
|
}
|
|
if onDisk.VacuumedMaxFileKey != want || onDisk.VacuumedCompactionRevision != revision {
|
|
t.Fatalf("%s: the .vif records id %d at revision %d, want %d at %d", when, onDisk.VacuumedMaxFileKey, onDisk.VacuumedCompactionRevision, want, revision)
|
|
}
|
|
}
|
|
|
|
recorded(0, "before any vacuum")
|
|
|
|
// the three largest ids are deleted: the vacuum erases every trace
|
|
// of them, and the largest id left in the index is 7
|
|
write(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
|
|
remove(8, 9, 10)
|
|
vacuum()
|
|
for id := uint64(8); id <= 10; id++ {
|
|
if nv, found := v.nm.Get(types.Uint64ToNeedleId(id)); found {
|
|
t.Fatalf("id %d still has an index entry after the vacuum: %+v", id, nv)
|
|
}
|
|
}
|
|
recorded(10, "after the first vacuum")
|
|
|
|
write(11, 12)
|
|
remove(12)
|
|
vacuum()
|
|
recorded(12, "after the second vacuum")
|
|
|
|
// a vacuum that finds only smaller ids keeps the record
|
|
remove(11)
|
|
vacuum()
|
|
recorded(12, "after a vacuum of smaller ids")
|
|
|
|
v.Close()
|
|
v, err = NewVolume(dir, dir, "", 1, kind, nil, nil, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("reload: %v", err)
|
|
}
|
|
defer v.Close()
|
|
recorded(12, "after a reload")
|
|
})
|
|
}
|
|
}
|
|
|
|
// A vacuum by a volume server that does not keep the record (an older one, or
|
|
// one that lacks it) may erase larger ids than the record names, and leaves the
|
|
// .vif as it was. The record names the revision it was written for, so it is
|
|
// no longer trusted, and no later vacuum takes it up again.
|
|
func TestVacuumOfVolumeWithUnrecordedVacuumsRecordsNothing(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)
|
|
}
|
|
defer func() { v.Close() }()
|
|
vacuum := func() {
|
|
t.Helper()
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("commit compact: %v", err)
|
|
}
|
|
}
|
|
for id := uint64(1); id <= 9; id++ {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false, false); err != nil {
|
|
t.Fatalf("write %d: %v", id, err)
|
|
}
|
|
}
|
|
vacuum()
|
|
if v.volumeInfo.VacuumedMaxFileKey != 9 || v.volumeInfo.VacuumedCompactionRevision != 1 {
|
|
t.Fatalf("first vacuum recorded id %d at revision %d, want 9 at 1", v.volumeInfo.VacuumedMaxFileKey, v.volumeInfo.VacuumedCompactionRevision)
|
|
}
|
|
staleVif, err := os.ReadFile(v.FileName(".vif"))
|
|
if err != nil {
|
|
t.Fatalf("read .vif: %v", err)
|
|
}
|
|
|
|
// id 10 is written and deleted, and a vacuum that keeps no record erases it
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(10), true, false, false); err != nil {
|
|
t.Fatalf("write: %v", err)
|
|
}
|
|
if _, err := v.deleteNeedle2(newEmptyNeedle(10), false); err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
vacuum()
|
|
if err := os.WriteFile(v.FileName(".vif"), staleVif, 0644); err != nil {
|
|
t.Fatalf("restore .vif: %v", err)
|
|
}
|
|
v.Close()
|
|
if v, err = NewVolume(dir, dir, "", 1, NeedleMapInMemory, nil, nil, 0, needle.GetCurrentVersion(), 0, 0); err != nil {
|
|
t.Fatalf("reload: %v", err)
|
|
}
|
|
if got := v.SuperBlock.CompactionRevision; got != 2 {
|
|
t.Fatalf("revision %d after two vacuums", got)
|
|
}
|
|
if _, ok := v.vacuumedMaxFileKey(); ok {
|
|
t.Fatalf("the record of revision 1 is trusted at revision 2: id 10 could come back")
|
|
}
|
|
|
|
if _, err := v.deleteNeedle2(newEmptyNeedle(8), false); err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
vacuum()
|
|
if got := v.volumeInfo.VacuumedCompactionRevision; got == uint32(v.SuperBlock.CompactionRevision) {
|
|
t.Fatalf("a vacuum took up a record broken by an unrecorded vacuum: revision %d", got)
|
|
}
|
|
}
|
|
|
|
// The volume server reports the largest needle id it holds to the master, which
|
|
// keeps its id sequence above it. A vacuum must not make a volume forget the
|
|
// ids it still holds, whatever its index is kept in.
|
|
func TestVacuumKeepsLargestNeedleId(t *testing.T) {
|
|
for _, kind := range []NeedleMapKind{NeedleMapInMemory, NeedleMapLevelDb} {
|
|
// 0 writes nothing while the vacuum copies; 9 is replayed by the commit
|
|
for _, duringCopy := range []uint64{0, 9} {
|
|
t.Run(fmt.Sprintf("kind%d/write%d", kind, duringCopy), func(t *testing.T) {
|
|
dir := t.TempDir()
|
|
v, err := NewVolume(dir, dir, "", 1, kind, &super_block.ReplicaPlacement{}, &needle.TTL{}, 0, needle.GetCurrentVersion(), 0, 0)
|
|
if err != nil {
|
|
t.Fatalf("volume creation: %v", err)
|
|
}
|
|
defer v.Close()
|
|
for id := uint64(1); id <= 7; id++ {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(id), true, false, false); err != nil {
|
|
t.Fatalf("write %d: %v", id, err)
|
|
}
|
|
}
|
|
if _, err := v.deleteNeedle2(newEmptyNeedle(2), false); err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
if duringCopy != 0 {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(duringCopy), true, false, false); err != nil {
|
|
t.Fatalf("write %d: %v", duringCopy, err)
|
|
}
|
|
}
|
|
if err := v.CommitCompact(); err != nil {
|
|
t.Fatalf("commit compact: %v", err)
|
|
}
|
|
if got, want := v.MaxFileKey(), types.NeedleId(max(7, duringCopy)); got != want {
|
|
t.Fatalf("largest needle id after the vacuum: %d, want %d", got, want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
// The heartbeat reads every volume of the server in turn, so one that waits
|
|
// out a long commit stalls the whole heartbeat until the master drops the
|
|
// server.
|
|
func TestCommitCompactDoesNotBlockStatus(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)
|
|
}
|
|
defer v.Close()
|
|
v.location = &DiskLocation{}
|
|
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)
|
|
}
|
|
}
|
|
if _, err := v.deleteNeedle2(newEmptyNeedle(1), false); err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
|
|
footprint := v.diskFootprint()
|
|
|
|
// A reader the commit has to wait out keeps its exclusive lock pending,
|
|
// which queues every later RLock behind it.
|
|
v.dataFileAccessLock.RLock()
|
|
committed := make(chan error, 1)
|
|
go func() { committed <- v.CommitCompact() }()
|
|
for v.dataFileAccessLock.TryRLock() {
|
|
v.dataFileAccessLock.RUnlock()
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
|
|
type status struct {
|
|
message *master_pb.VolumeInformationMessage
|
|
footprint uint64
|
|
}
|
|
reported := make(chan status, 1)
|
|
go func() {
|
|
// MaybeAdjustVolumeMax reads the footprint just before each heartbeat.
|
|
f := v.diskFootprint()
|
|
_, m := v.ToVolumeInformationMessage(nil)
|
|
reported <- status{m, f}
|
|
}()
|
|
var during status
|
|
select {
|
|
case during = <-reported:
|
|
case <-time.After(5 * time.Second):
|
|
v.dataFileAccessLock.RUnlock()
|
|
<-committed
|
|
t.Fatal("status read waited for the commit")
|
|
}
|
|
v.dataFileAccessLock.RUnlock()
|
|
if err := <-committed; err != nil {
|
|
t.Fatalf("commit: %v", err)
|
|
}
|
|
if m := during.message; m == nil || m.FileCount != 3 || m.DeleteCount != 1 || m.CompactRevision != 0 {
|
|
t.Fatalf("status during the commit = %+v, want the volume as the commit started", m)
|
|
}
|
|
if during.footprint != footprint {
|
|
t.Fatalf("footprint during the commit = %d, want %d", during.footprint, footprint)
|
|
}
|
|
_, m := v.ToVolumeInformationMessage(nil)
|
|
if m == nil || m.FileCount != 2 || m.DeleteCount != 0 || m.CompactRevision != 1 {
|
|
t.Fatalf("status after the commit = %+v, want the compacted volume", m)
|
|
}
|
|
}
|
|
|
|
// The heartbeat deletes an expired TTL volume under the location's volumes
|
|
// lock, so a delete that waits out a commit stalls the heartbeat with it.
|
|
func TestDeleteVolumeDoesNotWaitForCommit(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)
|
|
}
|
|
defer v.Close()
|
|
loc := &DiskLocation{volumes: map[needle.VolumeId]*Volume{v.Id: v}}
|
|
v.location = loc
|
|
for i := uint64(1); i <= 2; i++ {
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(i), true, false, false); err != nil {
|
|
t.Fatalf("write %d: %v", i, err)
|
|
}
|
|
}
|
|
if _, err := v.deleteNeedle2(newEmptyNeedle(1), false); err != nil {
|
|
t.Fatalf("delete: %v", err)
|
|
}
|
|
if err := v.CompactByIndex(nil); err != nil {
|
|
t.Fatalf("compact: %v", err)
|
|
}
|
|
|
|
v.dataFileAccessLock.RLock()
|
|
committed := make(chan error, 1)
|
|
go func() { committed <- v.CommitCompact() }()
|
|
for v.dataFileAccessLock.TryRLock() {
|
|
v.dataFileAccessLock.RUnlock()
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
|
|
deleted := make(chan error, 1)
|
|
go func() {
|
|
_, err := loc.deleteVolumeById(v.Id, false, false, false)
|
|
deleted <- err
|
|
}()
|
|
var deleteErr error
|
|
select {
|
|
case deleteErr = <-deleted:
|
|
case <-time.After(5 * time.Second):
|
|
v.dataFileAccessLock.RUnlock()
|
|
<-committed
|
|
t.Fatal("delete waited for the commit")
|
|
}
|
|
v.dataFileAccessLock.RUnlock()
|
|
if err := <-committed; err != nil {
|
|
t.Fatalf("commit: %v", err)
|
|
}
|
|
if deleteErr == nil {
|
|
t.Fatal("deleted a volume mid-commit")
|
|
}
|
|
if _, ok := loc.volumes[v.Id]; !ok {
|
|
t.Fatal("the refused delete dropped the volume")
|
|
}
|
|
}
|
|
|
|
// The status a commit pins keeps the volume reported while the commit runs,
|
|
// so the missing-.dat check must not drop it in the gap of a Windows swap.
|
|
func TestCompactingVolumeIsNotTakenForPhantom(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)
|
|
}
|
|
defer v.Close()
|
|
v.location = &DiskLocation{}
|
|
if _, _, _, err := v.writeNeedle2(newRandomNeedle(1), true, false, false); err != nil {
|
|
t.Fatalf("write: %v", err)
|
|
}
|
|
dat := v.FileName(".dat")
|
|
if err := os.Rename(dat, dat+".swapping"); err != nil {
|
|
t.Fatalf("rename: %v", err)
|
|
}
|
|
defer os.Rename(dat+".swapping", dat)
|
|
|
|
v.isCompactionInProgress.Store(true)
|
|
_, during := v.ToVolumeInformationMessage(nil)
|
|
v.isCompactionInProgress.Store(false)
|
|
if during == nil {
|
|
t.Fatal("a compacting volume was dropped from the report")
|
|
}
|
|
if _, m := v.ToVolumeInformationMessage(nil); m != nil {
|
|
t.Fatal("a volume whose .dat is missing was reported")
|
|
}
|
|
}
|