mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +01:00
storage: make walstore checkpoint publication fail closed
This commit is contained in:
1 parent
9b69b5b8fd
commit
bc4e6d289e
4 files changed
+869
-123
No files matched your search
@@ -47,6 +47,7 @@ type flusher struct {
|
||||
doneCh chan struct{}
|
||||
notifyCh chan struct{} // wakeup channel; bumped by admission under WAL pressure
|
||||
stopOnce sync.Once
|
||||
stopErr error
|
||||
flushes atomic.Uint64 // diagnostic
|
||||
bytesOut atomic.Uint64 // diagnostic
|
||||
}
|
||||
@@ -97,7 +98,7 @@ func (f *flusher) run() {
|
||||
case <-f.stopCh:
|
||||
// One last best-effort flush so a clean shutdown advances
|
||||
// the checkpoint as far as possible.
|
||||
_ = f.flushOnce()
|
||||
f.stopErr = f.flushOnceAllowClosed()
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := f.flushOnce(); err != nil {
|
||||
@@ -113,11 +114,12 @@ func (f *flusher) run() {
|
||||
|
||||
// Stop signals the flusher to stop and waits for the run loop to
|
||||
// exit. Idempotent.
|
||||
func (f *flusher) Stop() {
|
||||
func (f *flusher) Stop() error {
|
||||
f.stopOnce.Do(func() {
|
||||
close(f.stopCh)
|
||||
<-f.doneCh
|
||||
})
|
||||
return f.stopErr
|
||||
}
|
||||
|
||||
func (f *flusher) FlushCount() uint64 { return f.flushes.Load() }
|
||||
@@ -130,9 +132,17 @@ func (f *flusher) BytesFlushed() uint64 { return f.bytesOut.Load() }
|
||||
// FlushOnce. See type doc for the full sequence and the rationale
|
||||
// for each invariant.
|
||||
func (f *flusher) flushOnce() error {
|
||||
return f.flushOnceInternal(false)
|
||||
}
|
||||
|
||||
func (f *flusher) flushOnceAllowClosed() error {
|
||||
return f.flushOnceInternal(true)
|
||||
}
|
||||
|
||||
func (f *flusher) flushOnceInternal(allowClosed bool) error {
|
||||
store := f.store
|
||||
store.mu.RLock()
|
||||
if store.closed {
|
||||
if store.closed && !allowClosed {
|
||||
store.mu.RUnlock()
|
||||
return nil
|
||||
}
|
||||
@@ -143,64 +153,24 @@ func (f *flusher) flushOnce() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Step 1: read every WAL header. For each entry, validate that
|
||||
// the on-disk LSN at the recorded WAL offset still matches the
|
||||
// snapshot LSN. A mismatch means the WAL slot was recycled
|
||||
// (the dirty map points at a slot whose contents have changed)
|
||||
// — skip such entries; they'll fall out via compare-and-delete
|
||||
// below.
|
||||
type pending struct {
|
||||
idx int
|
||||
dataLen uint32
|
||||
isWrite bool
|
||||
}
|
||||
var pendings []pending
|
||||
// Validate and materialize each complete WAL record before using it for
|
||||
// checkpoint progress. Partial extent writes are safe because checkpoint
|
||||
// publication happens only after the whole snapshot and fsync succeed.
|
||||
var maxLSN uint64
|
||||
var maxLSNPhys uint64
|
||||
var maxLSNEntrySize uint64
|
||||
|
||||
hdrBuf := make([]byte, walEntryHeaderSize)
|
||||
for i, e := range entries {
|
||||
absOff := int64(store.sb.WALOffset + e.WALOffset)
|
||||
if _, err := store.fd.ReadAt(hdrBuf, absOff); err != nil {
|
||||
return fmt.Errorf("flusher: read WAL header at %d: %w", e.WALOffset, err)
|
||||
for _, e := range entries {
|
||||
data, entrySize, err := f.readDirtyRecord(e)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entryLSN := binary.LittleEndian.Uint64(hdrBuf[0:8])
|
||||
entryBlockCount := binary.LittleEndian.Uint64(hdrBuf[8:16])
|
||||
if entryLSN != e.LSN {
|
||||
entryType := hdrBuf[16]
|
||||
if entryType != walEntryWriteBatch {
|
||||
// Stale slot — WAL has been recycled at this offset.
|
||||
// Drop the dirty map entry only if it still matches the
|
||||
// stale snapshot we just observed (compare-and-delete).
|
||||
store.dm.compareAndDelete(e.LBA, e.LSN)
|
||||
continue
|
||||
}
|
||||
if entryBlockCount == 0 || e.DataOffset%store.sb.BlockSize != 0 {
|
||||
store.dm.compareAndDelete(e.LBA, e.LSN)
|
||||
continue
|
||||
}
|
||||
blockIndex := uint64(e.DataOffset / store.sb.BlockSize)
|
||||
if blockIndex >= entryBlockCount || entryLSN+blockIndex != e.LSN {
|
||||
store.dm.compareAndDelete(e.LBA, e.LSN)
|
||||
continue
|
||||
}
|
||||
written, err := store.writeExtentIfCurrent(e.LBA, e.LSN, data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("flusher: write extent LBA %d: %w", e.LBA, err)
|
||||
}
|
||||
entryType := hdrBuf[16]
|
||||
entrySize := uint64(walEntryHeaderSize)
|
||||
switch entryType {
|
||||
case walEntryWrite, walEntryWriteBatch:
|
||||
dataLen := parseLengthFromHeader(hdrBuf)
|
||||
if dataLen == 0 {
|
||||
continue
|
||||
}
|
||||
entrySize += uint64(dataLen)
|
||||
pendings = append(pendings, pending{idx: i, dataLen: dataLen, isWrite: true})
|
||||
case walEntryTrim:
|
||||
pendings = append(pendings, pending{idx: i, isWrite: false})
|
||||
default:
|
||||
// Padding / barrier — nothing to flush.
|
||||
continue
|
||||
if written {
|
||||
f.bytesOut.Add(uint64(len(data)))
|
||||
}
|
||||
if e.LSN > maxLSN {
|
||||
maxLSN = e.LSN
|
||||
@@ -209,34 +179,13 @@ func (f *flusher) flushOnce() error {
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: for each verified entry, read the data section and
|
||||
// pwrite it into the extent at the LBA's natural offset.
|
||||
for _, p := range pendings {
|
||||
e := entries[p.idx]
|
||||
var data []byte
|
||||
if p.isWrite {
|
||||
d, err := store.readFromWAL(e.WALOffset, e.DataOffset)
|
||||
if err != nil {
|
||||
return fmt.Errorf("flusher: read WAL data for LBA %d: %w", e.LBA, err)
|
||||
}
|
||||
data = d
|
||||
} else {
|
||||
// Trim — extent destination is zeros.
|
||||
data = make([]byte, store.sb.BlockSize)
|
||||
}
|
||||
if err := store.writeExtent(uint32(e.LBA), data); err != nil {
|
||||
return fmt.Errorf("flusher: write extent LBA %d: %w", e.LBA, err)
|
||||
}
|
||||
f.bytesOut.Add(uint64(len(data)))
|
||||
}
|
||||
|
||||
// Step 3: one fsync covers all extent writes in this batch
|
||||
// Step 2: one fsync covers all extent writes in this batch
|
||||
// (and any other in-flight WAL writes since they share a file).
|
||||
if err := store.fd.Sync(); err != nil {
|
||||
return fmt.Errorf("flusher: fsync after extent writes: %w", err)
|
||||
}
|
||||
|
||||
// Step 4: advance the on-disk checkpoint to the highest LSN
|
||||
// Step 3: advance the on-disk checkpoint to the highest LSN
|
||||
// that was successfully flushed in this cycle. Because we
|
||||
// processed the ENTIRE snapshot (no batch cutoff), every entry
|
||||
// with LSN <= maxLSN that needed flushing is in extent. Newer
|
||||
@@ -255,13 +204,112 @@ func (f *flusher) flushOnce() error {
|
||||
}
|
||||
}
|
||||
|
||||
// Step 5: remove flushed entries from the dirty map using
|
||||
// Step 4: remove flushed entries from the dirty map using
|
||||
// compare-and-delete. If a concurrent Write() bumped an entry's
|
||||
// LSN after our snapshot, this leaves the newer entry alone.
|
||||
for _, p := range pendings {
|
||||
e := entries[p.idx]
|
||||
for _, e := range entries {
|
||||
store.dm.compareAndDelete(e.LBA, e.LSN)
|
||||
}
|
||||
f.flushes.Add(1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *flusher) readDirtyRecord(e snapshotEntry) ([]byte, uint64, error) {
|
||||
store := f.store
|
||||
header := make([]byte, walEntryHeaderSize)
|
||||
absOff := int64(store.sb.WALOffset + e.WALOffset)
|
||||
if _, err := store.fd.ReadAt(header, absOff); err != nil {
|
||||
return nil, 0, fmt.Errorf("flusher: read WAL header at %d: %w", e.WALOffset, err)
|
||||
}
|
||||
|
||||
entryLSN := binary.LittleEndian.Uint64(header[0:8])
|
||||
entryType := header[16]
|
||||
if entryType != walEntryWriteBatch && entryLSN != e.LSN {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entryLSN)
|
||||
}
|
||||
if entryType != walEntryWrite && entryType != walEntryWriteBatch && entryType != walEntryTrim {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d type %d",
|
||||
e.LBA, e.WALOffset, entryType)
|
||||
}
|
||||
|
||||
payloadLen := uint64(0)
|
||||
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
|
||||
payloadLen = uint64(parseLengthFromHeader(header))
|
||||
if payloadLen == 0 {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d with zero payload",
|
||||
e.LBA, e.WALOffset)
|
||||
}
|
||||
}
|
||||
entrySize := uint64(walEntryHeaderSize) + payloadLen
|
||||
if entrySize > store.sb.WALSize || e.WALOffset+entrySize > store.sb.WALSize {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d size %d WAL size %d",
|
||||
e.LBA, e.WALOffset, entrySize, store.sb.WALSize)
|
||||
}
|
||||
|
||||
full := make([]byte, entrySize)
|
||||
if _, err := store.fd.ReadAt(full, absOff); err != nil {
|
||||
return nil, 0, fmt.Errorf("flusher: read WAL record at %d: %w", e.WALOffset, err)
|
||||
}
|
||||
entry, err := decodeWALEntry(full)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d: %w",
|
||||
e.LBA, e.WALOffset, err)
|
||||
}
|
||||
if entry.Flags != 0 {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d flags %d",
|
||||
e.LBA, e.WALOffset, entry.Flags)
|
||||
}
|
||||
|
||||
blockSize := store.sb.BlockSize
|
||||
switch entry.Type {
|
||||
case walEntryWrite:
|
||||
if entry.LSN != e.LSN || entry.LBA != e.LBA || e.DataOffset != 0 ||
|
||||
entry.Length != blockSize || e.Length != blockSize {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entry.LSN)
|
||||
}
|
||||
return entry.Data, entrySize, nil
|
||||
case walEntryWriteBatch:
|
||||
expectedLength := entry.Reserved * uint64(blockSize)
|
||||
if entry.Reserved == 0 || expectedLength > uint64(^uint32(0)) ||
|
||||
uint64(entry.Length) != expectedLength ||
|
||||
e.DataOffset%blockSize != 0 || e.Length != blockSize {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL batch LBA %d offset %d",
|
||||
e.LBA, e.WALOffset)
|
||||
}
|
||||
blockIndex := uint64(e.DataOffset / blockSize)
|
||||
if blockIndex >= entry.Reserved || entry.LSN+blockIndex != e.LSN ||
|
||||
entry.LBA+blockIndex != e.LBA {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d batch base %d block %d count %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entry.LSN, blockIndex, entry.Reserved)
|
||||
}
|
||||
start := uint64(e.DataOffset)
|
||||
end := start + uint64(blockSize)
|
||||
if end > uint64(len(entry.Data)) {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL batch LBA %d offset %d data range [%d,%d)",
|
||||
e.LBA, e.WALOffset, start, end)
|
||||
}
|
||||
return entry.Data[start:end], entrySize, nil
|
||||
case walEntryTrim:
|
||||
if entry.LSN != e.LSN || entry.LBA != e.LBA || e.DataOffset != 0 ||
|
||||
e.Length != blockSize {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch trim LBA %d offset %d dirty LSN %d record LSN %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entry.LSN)
|
||||
}
|
||||
return make([]byte, blockSize), entrySize, nil
|
||||
default:
|
||||
panic("validated dirty WAL type became unsupported")
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,8 @@ type WALStore struct {
|
||||
committer *GroupCommitter
|
||||
syncCache func() error
|
||||
syncDirectFrontierMetadata func([]byte) error
|
||||
writeSuperblockMetadata func([]byte) error
|
||||
syncSuperblockMetadata func() error
|
||||
flusher *flusher // background WAL→extent applier; nil if disabled
|
||||
admission *walAdmission // backpressure on WAL pressure; nil if disabled
|
||||
|
||||
@@ -59,12 +61,14 @@ type WALStore struct {
|
||||
// the Write returns errWALFull. Defaults to 30s.
|
||||
admissionTimeout time.Duration
|
||||
|
||||
mu sync.RWMutex
|
||||
closed bool
|
||||
nextLSN uint64 // next LSN to assign to a write
|
||||
syncedLSN uint64 // highest LSN durably present in extent OR WAL after fsync
|
||||
walTail uint64 // exposed S boundary (oldest retained LSN)
|
||||
walHead uint64 // exposed H boundary (newest written LSN)
|
||||
lifecycleMu sync.RWMutex
|
||||
mu sync.RWMutex
|
||||
extentMu [64]sync.RWMutex
|
||||
closed bool
|
||||
nextLSN uint64 // next LSN to assign to a write
|
||||
syncedLSN uint64 // highest LSN durably present in extent OR WAL after fsync
|
||||
walTail uint64 // exposed S boundary (oldest retained LSN)
|
||||
walHead uint64 // exposed H boundary (newest written LSN)
|
||||
|
||||
// extentBase is the absolute file offset where the extent region
|
||||
// begins; cached for fast read/write.
|
||||
@@ -227,6 +231,13 @@ func openInitialized(path string, f *os.File, sb *superblock) (*WALStore, error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
s.writeSuperblockMetadata = func(data []byte) error {
|
||||
if _, err := f.WriteAt(data, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
s.syncSuperblockMetadata = f.Sync
|
||||
|
||||
// Background flusher: drains dirty map → extent, advances
|
||||
// checkpoint, allows WAL recycling. Defaults are conservative
|
||||
@@ -273,11 +284,21 @@ func retainedLSNFromCheckpoint(checkpointLSN uint64) uint64 {
|
||||
return checkpointLSN + 1
|
||||
}
|
||||
|
||||
// writeExtent pwrites one block into the extent at lba's natural
|
||||
// offset. Used by the flusher to drain WAL records into the extent.
|
||||
// Caller is responsible for fsync (the flusher batches one fsync per
|
||||
// flush cycle covering all writeExtent calls in that cycle).
|
||||
func (s *WALStore) writeExtent(lba uint32, data []byte) error {
|
||||
func (s *WALStore) writeExtentIfCurrent(lba, expectedLSN uint64, data []byte) (bool, error) {
|
||||
lock := &s.extentMu[lba%uint64(len(s.extentMu))]
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
_, _, currentLSN, _, ok := s.dm.get(lba)
|
||||
if !ok || currentLSN != expectedLSN {
|
||||
return false, nil
|
||||
}
|
||||
if err := s.writeExtentUnlocked(uint32(lba), data); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *WALStore) writeExtentUnlocked(lba uint32, data []byte) error {
|
||||
off := int64(s.extentBase + uint64(lba)*uint64(s.sb.BlockSize))
|
||||
if _, err := s.fd.WriteAt(data, off); err != nil {
|
||||
return fmt.Errorf("storage: write extent LBA %d: %w", lba, err)
|
||||
@@ -288,14 +309,12 @@ func (s *WALStore) writeExtent(lba uint32, data []byte) error {
|
||||
// persistCheckpoint advances the on-disk checkpoint LSN to highestLSN
|
||||
// (after the flusher has confirmed the extent writes are fsync'd).
|
||||
// Updates both the in-memory checkpointLSN and the on-disk
|
||||
// superblock.WALCheckpointLSN. The superblock pwrite is itself
|
||||
// unsynced — the next fsync (or close) flushes it.
|
||||
//
|
||||
// If we crash between the extent fsync and the superblock fsync,
|
||||
// recovery sees the OLD checkpoint, replays the WAL records, and
|
||||
// over-writes the extent with identical bytes. Wasteful but correct.
|
||||
// superblock.WALCheckpointLSN. The metadata write is fsynced before
|
||||
// the in-memory checkpoint advances, because the caller may recycle
|
||||
// the corresponding WAL bytes immediately after this method returns.
|
||||
func (s *WALStore) persistCheckpoint(highestLSN uint64) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
// Clamp the proposed checkpoint to the recycle floor reported
|
||||
// by an external coordinator (e.g., the recovery package's
|
||||
// PeerShipCoordinator). When a replica is in an active rebuild
|
||||
@@ -310,27 +329,23 @@ func (s *WALStore) persistCheckpoint(highestLSN uint64) error {
|
||||
}
|
||||
}
|
||||
if highestLSN <= s.checkpointLSN {
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
sbCopy := *s.sb
|
||||
sbCopy.WALCheckpointLSN = highestLSN
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sbCopy.writeTo(buf); err != nil {
|
||||
return fmt.Errorf("storage: encode superblock: %w", err)
|
||||
}
|
||||
if err := s.writeSuperblockMetadata(buf.bytes()); err != nil {
|
||||
return fmt.Errorf("storage: pwrite superblock: %w", err)
|
||||
}
|
||||
if err := s.syncSuperblockMetadata(); err != nil {
|
||||
return fmt.Errorf("storage: fsync checkpoint superblock: %w", err)
|
||||
}
|
||||
s.checkpointLSN = highestLSN
|
||||
s.sb.WALCheckpointLSN = highestLSN
|
||||
s.mu.Unlock()
|
||||
|
||||
hdrBuf := make([]byte, superblockSize)
|
||||
if _, err := s.fd.ReadAt(hdrBuf, 0); err != nil {
|
||||
return fmt.Errorf("storage: read superblock for checkpoint: %w", err)
|
||||
}
|
||||
// Re-encode in place via writeTo onto a buffer, then pwrite at 0.
|
||||
// We use a small in-memory writer to avoid mucking with file
|
||||
// offset state under the WAL writer's nose.
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := s.sb.writeTo(buf); err != nil {
|
||||
return fmt.Errorf("storage: encode superblock: %w", err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
return fmt.Errorf("storage: pwrite superblock: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -358,6 +373,8 @@ func (s *WALStore) FlushCount() uint64 {
|
||||
// Idempotent: calling Recover twice on the same on-disk state yields
|
||||
// identical results.
|
||||
func (s *WALStore) Recover() (uint64, error) {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
@@ -392,6 +409,8 @@ func (s *WALStore) Recover() (uint64, error) {
|
||||
// covers this LSN). Reads after this Write see the new bytes
|
||||
// immediately.
|
||||
func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
if uint64(lba) >= uint64(s.sb.VolumeSize/uint64(s.sb.BlockSize)) {
|
||||
return 0, fmt.Errorf("storage: LBA %d out of range", lba)
|
||||
}
|
||||
@@ -447,6 +466,8 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) {
|
||||
}
|
||||
|
||||
func (s *WALStore) WriteBatch(startLBA uint32, blocks [][]byte) ([]uint64, error) {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
if len(blocks) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -653,6 +674,9 @@ func (s *WALStore) DisableAutoFlushForRecoveryTest() {
|
||||
}
|
||||
|
||||
func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) {
|
||||
lock := &s.extentMu[uint64(lba)%uint64(len(s.extentMu))]
|
||||
lock.RLock()
|
||||
defer lock.RUnlock()
|
||||
data := make([]byte, s.sb.BlockSize)
|
||||
off := int64(s.extentBase + uint64(lba)*uint64(s.sb.BlockSize))
|
||||
if _, err := s.fd.ReadAt(data, off); err != nil {
|
||||
@@ -669,6 +693,8 @@ func (s *WALStore) readFromExtent(lba uint32) ([]byte, error) {
|
||||
// returns nil. Group commit batches concurrent Sync callers into one
|
||||
// fsync.
|
||||
func (s *WALStore) Sync() (uint64, error) {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
s.mu.RLock()
|
||||
if s.closed {
|
||||
s.mu.RUnlock()
|
||||
@@ -780,8 +806,13 @@ func (s *WALStore) RecoveryRetentionLSNs() uint64 {
|
||||
// Used by the rebuild server to declare the replica's frontier
|
||||
// matches the primary's head once base blocks are installed.
|
||||
func (s *WALStore) AdvanceFrontier(lsn uint64) {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
if lsn >= s.nextLSN {
|
||||
s.nextLSN = lsn + 1
|
||||
}
|
||||
@@ -797,8 +828,13 @@ func (s *WALStore) AdvanceFrontier(lsn uint64) {
|
||||
// recovery cases where the requested LSN is below newTail must
|
||||
// escalate to rebuild.
|
||||
func (s *WALStore) AdvanceWALTail(newTail uint64) {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed {
|
||||
return
|
||||
}
|
||||
if newTail > s.walTail {
|
||||
s.walTail = newTail
|
||||
}
|
||||
@@ -817,6 +853,8 @@ func (s *WALStore) AdvanceWALTail(newTail uint64) {
|
||||
// Durability follows the same rule as Write: bytes become durable
|
||||
// only on the next successful Sync (the extent fsync covers them).
|
||||
func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
maxLBA := uint32(s.sb.VolumeSize / uint64(s.sb.BlockSize))
|
||||
if lba >= maxLBA {
|
||||
return fmt.Errorf("storage: WriteExtentDirect LBA %d out of range", lba)
|
||||
@@ -824,13 +862,31 @@ func (s *WALStore) WriteExtentDirect(lba uint32, data []byte) error {
|
||||
if len(data) != int(s.sb.BlockSize) {
|
||||
return fmt.Errorf("storage: WriteExtentDirect data size %d != block size %d", len(data), s.sb.BlockSize)
|
||||
}
|
||||
return s.writeExtent(lba, data)
|
||||
s.mu.RLock()
|
||||
closed := s.closed
|
||||
s.mu.RUnlock()
|
||||
if closed {
|
||||
return errors.New("storage: WriteExtentDirect after Close")
|
||||
}
|
||||
lock := &s.extentMu[uint64(lba)%uint64(len(s.extentMu))]
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
_, _, previousLSN, _, hadDirty := s.dm.get(uint64(lba))
|
||||
if err := s.writeExtentUnlocked(lba, data); err != nil {
|
||||
return err
|
||||
}
|
||||
if hadDirty {
|
||||
s.dm.compareAndDelete(uint64(lba), previousLSN)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApplyEntry writes a replicated block with the source's LSN rather
|
||||
// than allocating a fresh one. Same durability semantics as Write
|
||||
// (becomes durable on next Sync).
|
||||
func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
maxLBA := uint32(s.sb.VolumeSize / uint64(s.sb.BlockSize))
|
||||
if lba >= maxLBA {
|
||||
return fmt.Errorf("storage: apply LBA %d out of range", lba)
|
||||
@@ -838,6 +894,12 @@ func (s *WALStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error {
|
||||
if len(data) != int(s.sb.BlockSize) {
|
||||
return fmt.Errorf("storage: apply data size %d != block size %d", len(data), s.sb.BlockSize)
|
||||
}
|
||||
s.mu.RLock()
|
||||
closed := s.closed
|
||||
s.mu.RUnlock()
|
||||
if closed {
|
||||
return errors.New("storage: ApplyEntry after Close")
|
||||
}
|
||||
dataCopy := make([]byte, len(data))
|
||||
copy(dataCopy, data)
|
||||
entry := &walEntry{
|
||||
@@ -952,6 +1014,8 @@ func bytesAllZero(data, zero []byte) bool {
|
||||
// fsyncs the file, stops the group committer, and releases the
|
||||
// underlying file. Idempotent.
|
||||
func (s *WALStore) Close() error {
|
||||
s.lifecycleMu.Lock()
|
||||
defer s.lifecycleMu.Unlock()
|
||||
s.mu.Lock()
|
||||
if s.closed {
|
||||
s.mu.Unlock()
|
||||
@@ -966,27 +1030,41 @@ func (s *WALStore) Close() error {
|
||||
// file. Test gates may have already stopped it via
|
||||
// DisableAutoFlushForRecoveryTest; in that case Stop is idempotent and does
|
||||
// not checkpoint later writes.
|
||||
var flushErr error
|
||||
if s.flusher != nil {
|
||||
s.flusher.Stop()
|
||||
flushErr = s.flusher.Stop()
|
||||
}
|
||||
if s.committer != nil {
|
||||
s.committer.Stop()
|
||||
}
|
||||
var closeErrors []error
|
||||
if flushErr != nil {
|
||||
closeErrors = append(closeErrors, fmt.Errorf("storage: final flush: %w", flushErr))
|
||||
}
|
||||
if s.fd != nil {
|
||||
// Persist current head/tail back into the superblock so a
|
||||
// subsequent OpenWALStore can find the WAL bounds without
|
||||
// relying solely on the defensive scan.
|
||||
s.sb.WALHead = s.wal.logicalHeadValue()
|
||||
s.sb.WALTail = s.wal.logicalTailValue()
|
||||
if _, err := s.fd.Seek(0, 0); err == nil {
|
||||
_, _ = s.sb.writeTo(s.fd)
|
||||
_ = s.fd.Sync()
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := s.sb.writeTo(buf); err != nil {
|
||||
closeErrors = append(closeErrors, fmt.Errorf("storage: encode final superblock: %w", err))
|
||||
} else {
|
||||
if err := s.writeSuperblockMetadata(buf.bytes()); err != nil {
|
||||
closeErrors = append(closeErrors, fmt.Errorf("storage: write final superblock: %w", err))
|
||||
}
|
||||
if err := s.syncSuperblockMetadata(); err != nil {
|
||||
closeErrors = append(closeErrors, fmt.Errorf("storage: fsync final superblock: %w", err))
|
||||
}
|
||||
}
|
||||
err := s.fd.Close()
|
||||
closeErr := s.fd.Close()
|
||||
s.fd = nil
|
||||
return err
|
||||
if closeErr != nil {
|
||||
closeErrors = append(closeErrors, closeErr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return errors.Join(closeErrors...)
|
||||
}
|
||||
|
||||
// Compile-time assertion: WALStore satisfies LogicalStorage.
|
||||
|
||||
@@ -0,0 +1,618 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inject func(*WALStore)
|
||||
}{
|
||||
{
|
||||
name: "write",
|
||||
inject: func(s *WALStore) {
|
||||
s.writeSuperblockMetadata = func([]byte) error {
|
||||
return errors.New("injected checkpoint write failure")
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sync",
|
||||
inject: func(s *WALStore) {
|
||||
s.syncSuperblockMetadata = func() error {
|
||||
return errors.New("injected checkpoint sync failure")
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
want := makeBlock(4096, 0x71)
|
||||
lsn, err := s.Write(3, want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tailBefore := s.wal.logicalTailValue()
|
||||
savedWrite := s.writeSuperblockMetadata
|
||||
savedSync := s.syncSuperblockMetadata
|
||||
tt.inject(s)
|
||||
|
||||
if err := s.flusher.flushOnce(); err == nil {
|
||||
t.Fatal("flush with injected checkpoint failure succeeded")
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint after failed metadata publication=%d want 0", got)
|
||||
}
|
||||
if got := s.sb.WALCheckpointLSN; got != 0 {
|
||||
t.Fatalf("superblock checkpoint after failed metadata publication=%d want 0", got)
|
||||
}
|
||||
if got := s.wal.logicalTailValue(); got != tailBefore {
|
||||
t.Fatalf("WAL tail after failed metadata publication=%d want %d", got, tailBefore)
|
||||
}
|
||||
if got := s.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries after failed metadata publication=%d want 1", got)
|
||||
}
|
||||
|
||||
s.writeSuperblockMetadata = savedWrite
|
||||
s.syncSuperblockMetadata = savedSync
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatalf("retry flush: %v", err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != lsn {
|
||||
t.Fatalf("checkpoint after retry=%d want %d", got, lsn)
|
||||
}
|
||||
if got := s.dm.len(); got != 0 {
|
||||
t.Fatalf("dirty entries after retry=%d want 0", got)
|
||||
}
|
||||
got, err := s.Read(3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("extent bytes changed across checkpoint retry")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointPublicationCrashWindowsRemainRecoverable(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inject func(*WALStore)
|
||||
wantFlushError bool
|
||||
wantCheckpointMin uint64
|
||||
wantCheckpointMax uint64
|
||||
}{
|
||||
{
|
||||
name: "checkpoint_write_failed",
|
||||
inject: func(s *WALStore) {
|
||||
s.writeSuperblockMetadata = func([]byte) error {
|
||||
return errors.New("injected checkpoint write failure")
|
||||
}
|
||||
},
|
||||
wantFlushError: true,
|
||||
wantCheckpointMin: 0,
|
||||
wantCheckpointMax: 0,
|
||||
},
|
||||
{
|
||||
name: "checkpoint_sync_failed",
|
||||
inject: func(s *WALStore) {
|
||||
s.syncSuperblockMetadata = func() error {
|
||||
return errors.New("injected checkpoint sync failure")
|
||||
}
|
||||
},
|
||||
wantFlushError: true,
|
||||
wantCheckpointMin: 0,
|
||||
wantCheckpointMax: 1,
|
||||
},
|
||||
{
|
||||
name: "checkpoint_synced",
|
||||
inject: func(*WALStore) {},
|
||||
wantCheckpointMin: 1,
|
||||
wantCheckpointMax: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := CreateWALStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Stop()
|
||||
want := makeBlock(4096, 0x73)
|
||||
if _, err := s.Write(3, want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tt.inject(s)
|
||||
flushErr := s.flusher.flushOnce()
|
||||
if tt.wantFlushError && flushErr == nil {
|
||||
t.Fatal("flush succeeded despite injected checkpoint failure")
|
||||
}
|
||||
if !tt.wantFlushError && flushErr != nil {
|
||||
t.Fatal(flushErr)
|
||||
}
|
||||
|
||||
// Simulate process loss without the WALStore Close metadata path.
|
||||
s.committer.Stop()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.fd = nil
|
||||
|
||||
reopened, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
checkpoint := reopened.CheckpointLSN()
|
||||
if checkpoint < tt.wantCheckpointMin || checkpoint > tt.wantCheckpointMax {
|
||||
t.Fatalf("reopened checkpoint=%d want in [%d,%d]",
|
||||
checkpoint, tt.wantCheckpointMin, tt.wantCheckpointMax)
|
||||
}
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := reopened.Read(3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("checkpoint crash window lost the acknowledged block")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherWALSlotMismatchFailsClosed(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(4, makeBlock(4096, 0x44)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walOffset, _, lsn, _, ok := s.dm.get(4)
|
||||
if !ok {
|
||||
t.Fatal("dirty entry missing")
|
||||
}
|
||||
|
||||
header := make([]byte, walEntryHeaderSize)
|
||||
absoluteOffset := int64(s.sb.WALOffset + walOffset)
|
||||
if _, err := s.fd.ReadAt(header, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mutated := append([]byte(nil), header...)
|
||||
mutated[0] ^= 0x7f
|
||||
if _, err := s.fd.WriteAt(mutated, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = s.flusher.flushOnce()
|
||||
if err == nil || !strings.Contains(err.Error(), "WAL slot mismatch") {
|
||||
t.Fatalf("flush error=%v want WAL slot mismatch", err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint after WAL slot mismatch=%d want 0", got)
|
||||
}
|
||||
if got := s.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries after WAL slot mismatch=%d want 1", got)
|
||||
}
|
||||
_, _, currentLSN, _, ok := s.dm.get(4)
|
||||
if !ok || currentLSN != lsn {
|
||||
t.Fatalf("dirty entry after mismatch ok=%t lsn=%d want true/%d", ok, currentLSN, lsn)
|
||||
}
|
||||
|
||||
if _, err := s.fd.WriteAt(header, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatalf("flush after restoring WAL header: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherRejectsCorruptOrUnsupportedDirtyRecord(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func([]byte)
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "crc",
|
||||
mutate: func(record []byte) {
|
||||
record[walEntryPrefixSize] ^= 0x7f
|
||||
},
|
||||
wantErr: "CRC mismatch",
|
||||
},
|
||||
{
|
||||
name: "unsupported_type",
|
||||
mutate: func(record []byte) {
|
||||
record[16] = walEntryBarrier
|
||||
},
|
||||
wantErr: "invalid dirty WAL record",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(2, makeBlock(4096, 0x22)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walOffset, _, _, length, ok := s.dm.get(2)
|
||||
if !ok {
|
||||
t.Fatal("dirty entry missing")
|
||||
}
|
||||
record := make([]byte, walEntryHeaderSize+length)
|
||||
absoluteOffset := int64(s.sb.WALOffset + walOffset)
|
||||
if _, err := s.fd.ReadAt(record, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := append([]byte(nil), record...)
|
||||
tt.mutate(record)
|
||||
if _, err := s.fd.WriteAt(record, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = s.flusher.flushOnce()
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("flush error=%v want substring %q", err, tt.wantErr)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint after invalid record=%d want 0", got)
|
||||
}
|
||||
if got := s.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries after invalid record=%d want 1", got)
|
||||
}
|
||||
|
||||
if _, err := s.fd.WriteAt(original, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatalf("flush after restoring record: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreClosePerformsFinalFlush(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := CreateWALStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replaceFlusherForTest(s, time.Hour)
|
||||
|
||||
want := makeBlock(4096, 0xa5)
|
||||
lsn, err := s.Write(7, want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reopened, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
if got := reopened.CheckpointLSN(); got != lsn {
|
||||
t.Fatalf("checkpoint after close=%d want final-flushed LSN %d", got, lsn)
|
||||
}
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := reopened.Read(7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("final-flushed bytes did not survive reopen")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreCloseWaitsForInflightSync(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replaceFlusherForTest(s, time.Hour)
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x61)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
syncStarted := make(chan struct{})
|
||||
releaseSync := make(chan struct{})
|
||||
s.syncCache = func() error {
|
||||
close(syncStarted)
|
||||
<-releaseSync
|
||||
return nil
|
||||
}
|
||||
syncDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := s.Sync()
|
||||
syncDone <- err
|
||||
}()
|
||||
<-syncStarted
|
||||
|
||||
closeDone := make(chan error, 1)
|
||||
go func() { closeDone <- s.Close() }()
|
||||
select {
|
||||
case err := <-closeDone:
|
||||
t.Fatalf("Close returned before in-flight Sync completed: %v", err)
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
|
||||
close(releaseSync)
|
||||
if err := <-syncDone; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-closeDone; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreMutationAPIsRejectAfterClose(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ApplyEntry(1, makeBlock(4096, 0x11), 1); err == nil {
|
||||
t.Fatal("ApplyEntry after Close succeeded")
|
||||
}
|
||||
if err := s.WriteExtentDirect(1, makeBlock(4096, 0x22)); err == nil {
|
||||
t.Fatal("WriteExtentDirect after Close succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreCloseReturnsFinalMetadataFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inject func(*WALStore)
|
||||
}{
|
||||
{
|
||||
name: "write",
|
||||
inject: func(s *WALStore) {
|
||||
s.writeSuperblockMetadata = func([]byte) error {
|
||||
return errors.New("injected final metadata write failure")
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sync",
|
||||
inject: func(s *WALStore) {
|
||||
s.syncSuperblockMetadata = func() error {
|
||||
return errors.New("injected final metadata sync failure")
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replaceFlusherForTest(s, time.Hour)
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x51)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tt.inject(s)
|
||||
err = s.Close()
|
||||
if err == nil || !strings.Contains(err.Error(), "injected final metadata") {
|
||||
t.Fatalf("Close error=%v want injected final metadata failure", err)
|
||||
}
|
||||
if s.fd != nil {
|
||||
t.Fatal("Close metadata failure left file open")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteExtentDirectSupersedesPriorDirtyWAL(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(5, makeBlock(4096, 0x55)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := makeBlock(4096, 0xb5)
|
||||
if err := s.WriteExtentDirect(5, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, _, _, ok := s.dm.get(5); ok {
|
||||
t.Fatal("direct BASE install left the superseded dirty WAL mapping visible")
|
||||
}
|
||||
got, err := s.Read(5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, base) {
|
||||
t.Fatal("read after direct BASE install returned superseded WAL bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteExtentDirectSupersededWALDoesNotReappearAfterRestart(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := CreateWALStore(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(9, makeBlock(4096, 0x39)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := makeBlock(4096, 0xb9)
|
||||
if err := s.WriteExtentDirect(9, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.AdvanceFrontier(10)
|
||||
if frontier, err := s.Sync(); err != nil || frontier != 10 {
|
||||
t.Fatalf("Sync frontier=%d err=%v want 10/nil", frontier, err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reopened, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := reopened.Read(9)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, base) {
|
||||
t.Fatal("superseded WAL bytes reappeared after direct BASE restart")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunningFlusherCannotOverwriteDirectBase(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
for iteration := 0; iteration < 50; iteration++ {
|
||||
if _, err := s.Write(10, makeBlock(4096, byte(iteration))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Notify()
|
||||
base := makeBlock(4096, byte(0x80+iteration))
|
||||
if err := s.WriteExtentDirect(10, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
got, err := s.Read(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, base) {
|
||||
t.Fatalf("iteration %d: running flusher overwrote direct BASE", iteration)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherSnapshotCannotOverwriteLaterDirectBase(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
old := makeBlock(4096, 0x31)
|
||||
if _, err := s.Write(6, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snapshot := s.dm.snapshot()
|
||||
if len(snapshot) != 1 {
|
||||
t.Fatalf("dirty snapshot entries=%d want 1", len(snapshot))
|
||||
}
|
||||
|
||||
base := makeBlock(4096, 0xb6)
|
||||
if err := s.WriteExtentDirect(6, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
written, err := s.writeExtentIfCurrent(snapshot[0].LBA, snapshot[0].LSN, old)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if written {
|
||||
t.Fatal("stale flusher snapshot overwrote a later direct BASE block")
|
||||
}
|
||||
got, err := s.readFromExtent(6)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, base) {
|
||||
t.Fatal("extent does not contain the direct BASE bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteExtentDirectFailureRetainsDirtyWAL(t *testing.T) {
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(8, makeBlock(4096, 0x48)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.committer.Stop()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := s.WriteExtentDirect(8, makeBlock(4096, 0xb8)); err == nil {
|
||||
t.Fatal("direct BASE write on closed file succeeded")
|
||||
}
|
||||
if _, _, _, _, ok := s.dm.get(8); !ok {
|
||||
t.Fatal("failed direct BASE write removed the recoverable dirty WAL mapping")
|
||||
}
|
||||
}
|
||||
|
||||
func replaceFlusherForTest(s *WALStore, interval time.Duration) {
|
||||
s.flusher.Stop()
|
||||
s.flusher = newFlusher(s, flusherConfig{Interval: interval})
|
||||
go s.flusher.run()
|
||||
}
|
||||
@@ -32,6 +32,8 @@ import (
|
||||
// references to fn or to RecoveryEntry.Data past the callback
|
||||
// return.
|
||||
func (s *WALStore) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error {
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
if fn == nil {
|
||||
return errors.New("storage: walstore ScanLBAs: nil callback")
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user