mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-10-07 06:47:51 +02:00
* volume server: ec.decode reads the .ecx from the index dir it was copied to VolumeEcShardsCopy writes the .ecx/.ecj into the receiver's -dir.idx, so with a split data/index dir the decode target has no .ecx beside its shards. VolumeEcShardsToVolume sized the .dat from the right .ecx but built the .idx from the data dir, failing with NotFound after the .dat was already published. It now reads .ecx/.ecj from where the EC volume opened them and writes the .idx beside the .dat, where Go leaves it. The live-entry check and the .dat size also ignored deletions recorded only in the .ecj, which Go folds into the .ecx (RebuildEcxFile) first: a fully deleted volume was decoded instead of reported as having no live entries, and deleted tail needles were copied into the .dat. Both now treat journaled ids as deleted, without rewriting the sealed .ecx. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * volume server: ec.decode keeps the decoded volume writable and reads every .ecj The rebuilt .idx copied a journaled tail needle's .ecx row verbatim after the .dat was cut short before it, so the mount saw a row past EOF and marked the decoded volume read-only. Rows of deleted needles the .dat no longer holds are now dropped, and each journaled needle still in the .dat gets one tombstone instead of one per journal entry. VolumeEcShardsCopy appends journals collected from other holders into the idx dir, but the decode read only the .ecj beside the .ecx, which sits in the data dir when this server generated the shards. It now reads both, once, in bounded chunks via the loader EcVolume uses. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * volume server: test ec.decode drops a sealed .ecx tail tombstone Covers the other half of the rule added in the previous commit: a tail needle tombstoned in the .ecx itself (Go's RebuildEcxFile) is cut from the .dat, and its row must not reach the rebuilt .idx either. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * volume server: ec.decode runs its file I/O off the async runtime VolumeEcShardsToVolume released the store lock before decoding, but read the .ecx/.ecj, rebuilt the .dat and wrote the .idx inside the async handler, parking a runtime worker for the length of a volume-sized copy. The decode now runs in spawn_blocking on inputs snapshotted under the store lock. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * volume server: ec.decode checks the rebuilt .dat is complete Go stats the decoded .dat before writing the .idx (VerifyDecodedDatFile) and fails the decode when it is shorter than the extent the EC index references, since the caller deletes the shards once the call returns. The Rust handler returned success without that check. The rebuild already fails on a short shard read, so this guards the published file itself. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * volume server: ec.decode drops the decoded volume's bitrot sidecars Go removes <base>.ecsum and <base>.ecsum.v<N> beside the .dat and beside the .ecx once the .idx is written, so a stale checksum sidecar cannot pass for the protection of a later re-encode. The Rust handler left them in place. Removal is best effort, as in Go. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * volume server: ec.decode compacts the decoded volume Go ends VolumeEcShardsToVolume with an offline CompactVolumeFiles, so the decoded volume holds only live needles. The Rust decode left every needle deleted through the .ecj in the .dat, tombstoned in the .idx, until a later vacuum reclaimed it. Store::compact_volume_files loads the unmounted volume, checks free space the way the vacuum does (the estimate now lives in one helper), and runs the vacuum's compact-by-index and commit. As in Go a failed compaction is logged and the decode still succeeds, so the uncompacted .idx rules stay: the tests that pin them now make the compaction fail. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * volume server: ec.decode keeps deletes journaled while the .dat is written The decode read the .ecj journals once, before rebuilding the .dat, so a delete that reached the EC volume during the rebuild was left out of the new .idx and the needle came back live. Each journal's read length is now kept, and the bytes appended since are read just before the .idx is written, after waiting out any journal append in flight (appends hold the store write lock), so every delete acknowledged by then is in the .idx. A delete after that point is still lost, as in Go. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * Guard overlapping ec decode requests; serialize journal catch-up volume_ec_shards_to_volume runs its decode in spawn_blocking, so a dropped request leaves the job running and a retry would race it on the temporary and final volume files. Claim the vid in a per-server in-flight set until the blocking job finishes, and return Unavailable to an overlapping request. The Go handler has the same exposure and gets the same guard. Journal appends hold the store write lock through their sync-or-truncate, so holding a read lock across the catch-up read guarantees every record it sees is committed: a rolled-back delete can no longer leave a tombstone in the decoded index. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * Reconcile the swap when offline compaction commit fails A CommitCompact that fails after the .cpc marker may have renamed .dat but not .idx. cleanup_compact refuses while the marker exists, so the mismatched pair survived until a restart reconciled it — and the decode caller treats the failure as non-fatal. Run reconcileCompactState on commit failure so a decided swap rolls forward and orphan temps are removed before the volume can mount. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * Release the decode claim on panic * volume: add ec_decodes_in_flight to the integration-test state literal * volume server: hold the decode tail's lock through compaction The catch_up read released before the rebuilt .idx was written and the volume compacted, so a delete synced to .ecj in that window was durably journaled yet absent from the published index — resurrecting the needle. Rust now holds the store read lock from catch_up through compact, and Go mirrors it by holding the volume's journal lock from the journal- consuming index write through CompactVolumeFiles. * volume server: serialize ec decode's tail per volume, not per store Review follow-ups on the decode path: - Rust: holding the store read lock from journal catch-up through the offline compaction stalled every writer on unrelated volumes for the whole rewrite. The new ec_decode_tail set marks the vid only while its .idx is published and .cpd/.cpx swapped; the two local .ecj append paths (VolumeEcBlobDelete, the distributed delete's local journal) wait on a Notify for that span — Go's per-volume ecjFileAccessLock semantics without the global stall. VolumeMount and the staged-adopt path are also held off while a decode claim is in flight so neither can race the swap. - Rust: the initial journal read ran unlocked, so bytes a rolled-back append later truncated could be folded in as phantom tombstones. The first pass stays unlocked (a slow journal must not stall the store) and a rescan under the quiescing read lock re-reads only committed content; catch_up now rebuilds the id set when a regular journal shrank. - Go: the decode resolved the compaction DiskLocation through FindEcVolume while holding the journal lock, inverting DestroyEcVolume's map->journal order into a deadlock. The lookup now happens first, and DestroyEcVolume/deleteEcVolumeById/DiskLocation.Close destroy outside the map lock. - Go: RebuildEcxFile unlinks .ecj while the volume's ecjFile handle stays open, so later deletes could commit to a detached inode. Both call sites now fold under the journal lock and ReopenDeletionJournal repoints the handle at the live path, working on the volume's resolved .ecx dir (EcIndexBaseFileName) rather than the configured index dir. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * volume server: fence EC remounts behind the destroy tombstone DestroyEcVolume, deleteEcVolumeById, and the collection-delete sweep now remove the EcVolume from ecVolumes before destroying it off-lock, so a concurrent remount could re-open shard files that the in-flight destroy then unlinks — registering a detached fd. Each destroy records a per-vid tombstone channel in a new ecVolumesDestroying map before dropping the map entry and closes it when Destroy returns. The tombstone intentionally survives as the vid's destroy generation: loadEcShardWithIdxDir compares it before and after opening the shard, so a destroy that both started and finished inside the open window is still detected. A mismatch drops the just-opened shard (releasing its fd and mount gauge) and retries after the destroy completes; a successful mount clears the stale tombstone. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * volume server: rescan the .ecj under the store lock only after a rollback The decode's second journal pass ran a full rescan under the store read lock on every decode, stalling unrelated writers for the length of the scan. Bump a process-wide epoch whenever a failed append truncates its uncommitted tail; an unchanged epoch between the unlocked read and the quiesced pass proves every id folded in was committed, so catch_up() suffices. catch_up() also treats a journal that was read but has since disappeared as shrunk to zero, so its earlier ids cannot linger. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * volume server: check the decode tail under the store write lock on delete A blob delete waited for the publishing tail before taking the store write lock, so a decode that claimed the tail while the delete was parked behind the decoder's read lock could still see the journal append land after the rebuilt .idx — an acknowledged delete the mount would miss. Test tail membership under the write lock instead, retrying after the wait; journal_delete_local reports WouldBlock for the same recheck on the distributed path. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * volume server: claim the vid for mount and staged adoption, per volume VolumeMount and the staged .copying adoption held the ec_decodes_in_flight set lock through slow file renames and mounts, stalling every unrelated volume's decode, mount, and adoption. Take the per-volume claim instead — the same exclusion against a racing decode for this vid, released when the call returns. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * volume server: fail the decode when a compaction commit marker survives CompactVolumeFiles' caller logged a compaction error and went on to delete the EC shards. When the commit marker (.cpc) is still on disk the .dat/.idx swap was decided but could not be reconciled, so the mounted pair may be mismatched — report the failure instead so the shards are kept and the caller can retry. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * volume server: gate the parked-delete test on the held write lock The releaser thread and the spawned delete raced for the store write lock; on a slow runner the delete could acquire it first and commit before the tail was ever claimed, failing !delete.is_finished() on the Windows unit-test job. Spawn the delete only after the thread reports the lock held. --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Chris Lu <chris.lu@gmail.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
201 lines
8.1 KiB
Go
201 lines
8.1 KiB
Go
package storage
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/stats"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
|
|
"github.com/seaweedfs/seaweedfs/weed/storage/types"
|
|
)
|
|
|
|
var ErrInsufficientSpace = fmt.Errorf("insufficient free space")
|
|
|
|
func (s *Store) CheckCompactVolume(volumeId needle.VolumeId) (garbageRatio float64, diskSpaceLow bool, err error) {
|
|
if v := s.findVolume(volumeId); v != nil {
|
|
glog.V(3).Infof("volume %d garbage level: %f", volumeId, v.garbageLevel())
|
|
// diskSpaceLow only counts when it is the sole read-only cause — an
|
|
// operator mark or I/O quarantine still shields the volume.
|
|
_, noWriteOrDelete, noWriteCanDelete, isLow := v.ReadOnlyReasons()
|
|
return v.garbageLevel(), isLow && !noWriteOrDelete && !noWriteCanDelete, nil
|
|
}
|
|
return 0, false, fmt.Errorf("volume id %d is not found during check compact: %w", volumeId, ErrVolumeNotFound)
|
|
}
|
|
|
|
func (s *Store) CompactVolume(vid needle.VolumeId, preallocate int64, compactionBytePerSecond int64, progressFn ProgressFunc) error {
|
|
if v := s.findVolume(vid); v != nil {
|
|
if err := ensureCompactVolumeSpace(v, preallocate); err != nil {
|
|
return err
|
|
}
|
|
return v.CompactByIndex(&CompactOptions{
|
|
PreallocateBytes: preallocate,
|
|
MaxBytesPerSecond: compactionBytePerSecond,
|
|
ProgressCallback: progressFn,
|
|
})
|
|
}
|
|
return fmt.Errorf("volume id %d is not found during compact: %w", vid, ErrVolumeNotFound)
|
|
}
|
|
|
|
func (s *Store) CommitCompactVolume(vid needle.VolumeId) (bool, int64, error) {
|
|
if s.isStopping.Load() {
|
|
return false, 0, fmt.Errorf("volume id %d skips compact because volume is stopping", vid)
|
|
}
|
|
if v := s.findVolume(vid); v != nil {
|
|
isReadOnly := v.IsReadOnly()
|
|
err := v.CommitCompact()
|
|
var volumeSize int64 = 0
|
|
if err == nil && v.DataBackend != nil {
|
|
volumeSize, _, _ = v.DataBackend.GetStat()
|
|
}
|
|
return isReadOnly, volumeSize, err
|
|
}
|
|
return false, 0, fmt.Errorf("volume id %d is not found during commit compact: %w", vid, ErrVolumeNotFound)
|
|
}
|
|
|
|
func (s *Store) CommitCleanupVolume(vid needle.VolumeId) error {
|
|
if v := s.findVolume(vid); v != nil {
|
|
return v.cleanupCompact()
|
|
}
|
|
return fmt.Errorf("volume id %d is not found during cleaning up: %w", vid, ErrVolumeNotFound)
|
|
}
|
|
|
|
// compactionDiskFree reports the free bytes on the disk holding dir, and
|
|
// compactionSameFilesystem whether two directories draw on the same pool.
|
|
// Both are variables so a test can stand in for a full or a split disk.
|
|
var (
|
|
compactionDiskFree = func(dir string) uint64 {
|
|
return stats.NewDiskStatus(dir).Free
|
|
}
|
|
compactionSameFilesystem = sameFilesystem
|
|
)
|
|
|
|
// compactionSpaceNeeded estimates what CompactByIndex will write for v: a new
|
|
// .dat holding the live needles with their on-disk framing behind a superblock
|
|
// (or preallocate, when that is larger, since the file is preallocated to it),
|
|
// and a rebuilt index with one entry per live needle. The volume's current size
|
|
// is the wrong yardstick: the more garbage a volume holds, the less its
|
|
// compaction writes, and a store that filled up until its volumes went
|
|
// read-only is exactly where the all-garbage volumes must still compact to
|
|
// give the space back (issue #11516). Neither estimate exceeds the current file.
|
|
func compactionSpaceNeeded(v *Volume, preallocate int64) (dataBytes, indexBytes int64) {
|
|
datSize, idxSize, _ := v.FileStat()
|
|
dataBytes, indexBytes = int64(datSize), int64(idxSize)
|
|
|
|
liveCount := int64(v.FileCount()) - int64(v.DeletedCount())
|
|
liveContent := int64(v.ContentSize()) - int64(v.DeletedSize())
|
|
// A .sdx converted back to .idx carries no deleted sizes (see
|
|
// garbageLevel), and counters that disagree mean the metric is off;
|
|
// either way the whole volume stays the estimate.
|
|
deletedSizeKnown := v.DeletedCount() == 0 || v.DeletedSize() > 0
|
|
if deletedSizeKnown && liveCount >= 0 && liveContent >= 0 {
|
|
// GetActualSize(0) is the framing of an empty needle; another
|
|
// padding unit covers the worst case for any other size.
|
|
perNeedle := needle.GetActualSize(0, v.Version()) + types.NeedlePaddingSize
|
|
// Counters rebuilt from an index file (LevelDB and sorted maps) go
|
|
// through a Bloom filter with a 0.1% false positive rate that can
|
|
// count a live needle as deleted. A few percent of headroom covers
|
|
// that many times over.
|
|
if estimate := withHeadroom(super_block.SuperBlockSize + liveContent + liveCount*perNeedle); estimate < dataBytes {
|
|
dataBytes = estimate
|
|
}
|
|
if estimate := withHeadroom(liveCount * types.NeedleMapEntrySize); estimate < indexBytes {
|
|
indexBytes = estimate
|
|
}
|
|
}
|
|
if preallocate > dataBytes {
|
|
dataBytes = preallocate
|
|
}
|
|
return dataBytes, indexBytes
|
|
}
|
|
|
|
func withHeadroom(estimate int64) int64 {
|
|
return estimate + estimate/16
|
|
}
|
|
|
|
func ensureCompactVolumeSpace(v *Volume, preallocate int64) error {
|
|
dataBytes, indexBytes := compactionSpaceNeeded(v, preallocate)
|
|
volumeSize, indexSize, _ := v.FileStat()
|
|
check := func(dir string, needed int64) error {
|
|
free := compactionDiskFree(dir)
|
|
if int64(free) < needed {
|
|
return fmt.Errorf("insufficient free space for compaction in %s: need %d bytes (data: %d, index: %d, current volume: %d, current index: %d), but only %d bytes available: %w",
|
|
dir, needed, dataBytes, indexBytes, volumeSize, indexSize, free, ErrInsufficientSpace)
|
|
}
|
|
glog.V(1).Infof("volume %d compaction space check in %s: data=%d, index=%d, current volume=%d, space_needed=%d, free_space=%d",
|
|
v.Id, dir, dataBytes, indexBytes, volumeSize, needed, free)
|
|
return nil
|
|
}
|
|
// The new .dat lands next to the old one and the new .idx next to the old
|
|
// index. When the index directory is on another filesystem each disk
|
|
// answers for its own share; two directories on one filesystem draw on
|
|
// the same free space and must cover the sum.
|
|
if v.dirIdx == "" || v.dirIdx == v.dir {
|
|
return check(v.dir, dataBytes+indexBytes)
|
|
}
|
|
if !compactionSameFilesystem(v.dir, v.dirIdx) {
|
|
if err := check(v.dir, dataBytes); err != nil {
|
|
return err
|
|
}
|
|
return check(v.dirIdx, indexBytes)
|
|
}
|
|
// Same filesystem as far as the identity check can tell. The index
|
|
// directory is still asked for its own share, because a mount point the
|
|
// check cannot see (a volume mounted under one drive letter on Windows)
|
|
// would otherwise go unchecked.
|
|
if err := check(v.dir, dataBytes+indexBytes); err != nil {
|
|
return err
|
|
}
|
|
return check(v.dirIdx, indexBytes)
|
|
}
|
|
|
|
func (s *Store) CompactVolumeFiles(vid needle.VolumeId, collection string, location *DiskLocation, needleMapKind NeedleMapKind, ldbTimeout int64, preallocate int64, compactionBytePerSecond int64) (err error) {
|
|
if location == nil {
|
|
return fmt.Errorf("volume %d compaction location is nil", vid)
|
|
}
|
|
|
|
tempVolume, err := loadVolumeWithoutWorker(location.Directory, location.IdxDirectory, collection, vid, needleMapKind, ldbTimeout)
|
|
if err != nil {
|
|
return fmt.Errorf("load volume %d for offline compaction: %w", vid, err)
|
|
}
|
|
tempVolume.location = location
|
|
|
|
defer func() {
|
|
if tempVolume.tmpNm != nil {
|
|
tempVolume.tmpNm.Close()
|
|
tempVolume.tmpNm = nil
|
|
}
|
|
tempVolume.doClose()
|
|
}()
|
|
|
|
if err := ensureCompactVolumeSpace(tempVolume, preallocate); err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := tempVolume.CompactByIndex(&CompactOptions{
|
|
PreallocateBytes: preallocate,
|
|
MaxBytesPerSecond: compactionBytePerSecond,
|
|
}); err != nil {
|
|
if cleanupErr := tempVolume.cleanupCompact(); cleanupErr != nil {
|
|
return fmt.Errorf("compact volume %d: %v (cleanup failed: %v)", vid, err, cleanupErr)
|
|
}
|
|
return fmt.Errorf("compact volume %d: %w", vid, err)
|
|
}
|
|
|
|
if err := tempVolume.CommitCompact(); err != nil {
|
|
// A failed commit may have swapped only one of .dat/.idx; reconcile
|
|
// rolls a decided swap forward or removes orphan temp files before
|
|
// this volume can mount with a mismatched pair.
|
|
if reconcileErr := tempVolume.reconcileCompactState(); reconcileErr != nil {
|
|
return fmt.Errorf("commit compact volume %d: %v (reconcile failed: %v)", vid, err, reconcileErr)
|
|
}
|
|
if cleanupErr := tempVolume.cleanupCompact(); cleanupErr != nil {
|
|
return fmt.Errorf("commit compact volume %d: %v (cleanup failed: %v)", vid, err, cleanupErr)
|
|
}
|
|
return fmt.Errorf("commit compact volume %d: %w", vid, err)
|
|
}
|
|
|
|
return nil
|
|
}
|