Files
seaweedfs/weed/storage/erasure_coding/ec_volume_delete.go
T
Chris LuandDevin 2c510cc30e ec.rebuild: remount shards the rebuild replaced, keep regenerated copies (#12193)
* volume: remount ec shards the rebuild replaced under a mounted handle

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

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

* ec.rebuild: keep copied shards the rebuild regenerated in place

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

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

* volume: reopen regenerated ec shards in place instead of remounting

UnmountEcShards and MountEcShards send deltas through separate buffered
channels, so a remount can reach the master as add-then-delete and drop
the repaired shard from lookups until the next full EC heartbeat.
ReopenEcShard swaps the mounted shard's descriptor under the volume lock
instead: registration, disk type, and heartbeat state never flip, and
readers holding the old shard degrade to a clean error the parity path
already recovers from.

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

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

* rust volume: reopen rebuilt ec shards in place, mirroring Go

volume_ec_shards_rebuild recreates a shard file under a mounted handle
whose descriptor still serves the detached inode (a mounted shard whose
file was deleted under it). DiskLocation::reopen_ec_shard swaps the
mounted descriptor for a fresh open, matching Go's ReopenEcShard — the
registration and heartbeat view never flip.

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

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

* volume: fail ec rebuild when a regenerated shard cannot be reopened

* rust volume: fail ec shards rebuild when a rebuilt shard cannot be reopened

* volume: repoint mounted ec shards after rebuild across disks

A mounted shard whose file was deleted under the mount is "missing" to
the rebuild: the regenerated file lands on the rebuild location while
the handle keeps serving the detached inode on another disk. Reopening
the mounted disk then failed the whole RPC, so the caller never saw the
rebuilt ids and its deferred cleanup deleted the regenerated copies.

Repoint every mounted handle of the rebuilt volume instead of only this
run's outputs: reopen in place when the rebuilt file is on the mounted
disk, otherwise drop the stale handle and remount the shard from
whichever local disk holds the file via a delta-free load split out of
MountEcShards — a same-server move, so the master's registration never
flips. A shard that can be neither reopened nor remounted is left
unmounted rather than serving replaced bytes, and the repoint step no
longer fails the RPC, so RebuiltShardIds always reaches the caller.

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

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

* rust volume: repoint mounted ec shards after rebuild across disks

Mirror the Go repoint loop: iterate every mounted shard of the rebuilt
volume, reopen in place when the rebuilt file is on the mounted disk,
and otherwise drop the stale handle and remount the shard from
whichever local disk holds it. The repoint no longer fails the RPC, so
rebuilt_shard_ids still reaches the caller and its copy cleanup keeps
the regenerated shards.

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

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

* rust volume: still rebuild ecx and repoint mounts when no shard is missing

* master: keep a node in an ec shard's lookup while a disk still holds it

A rebuild that relocates a mounted shard between a node's disks reports
the move as a delete on the source disk plus an add on the destination.
Registering first is a no-op because shard lookups key on the node, then
the unregister dropped the node outright — and steady-state heartbeats
never restore it, so readers and later rebuilds lose the repaired copy.
Skip the delete while another disk on the node still holds the shard.

UnregisterDataNode now clears the node's own ec records before dropping
its registrations, so the retained-shard check cannot skip the teardown,
and each unregister gets a ShardsInfo copy since DeleteEcShard drains
the shared one.

* rust volume: fold the journal on a mounted index instead of rewriting it

The rebuild handler regenerated .ecx through File::create even while the
volume was mounted, truncating the index under readers that search the
open descriptor with its old size — a live lookup could hit EOF mid-scan.
Go folds the deletion journal in place on a mounted volume; do the same
through rebuild_ecx_from_journal and reserve the full regen for the
unmounted path, where nothing holds the file open to interrupt.

* volume, rust volume: report rebuilt shards on late failures, fix rust corrupt discovery

Two review findings the repoint rework left open:

- A RebuildEcxFile failure still returns a plain error after shards were
  regenerated, so the caller discards the response holding the rebuilt
  ids and the deferred cleanup deletes copies the rebuild regenerated
  in place. The Go handler now packs the ids into the gRPC status
  details and the shell pulls them back out on error; the Rust handler
  carries them in grpc-status-details-bin the same way.
- The Rust rebuild still counted a sidecar-corrupt shard as present, so
  it fed bad bytes into reconstruction and never regenerated the shard.
  Discovery now loads the generation-0 .ecsum the way Go does, verifies
  every present shard, and reclassifies mismatches (and zero-size
  residue) as rebuild targets written to a .rebuilding temp file,
  verified, and atomically renamed over the original only after every
  output passes the sidecar check. Honors unsafe_ignore_sidecar, added
  to VolumeEcShardsRebuildRequest to match the Go proto.

* volume: repoint sibling journals sharing a folded .ecj after rebuild

RebuildEcxFile unlinks the deletion journal and the mounted path only
reopens its own handle — a sibling mount journaling into the same file
keeps appending to the detached inode, and those deletes never reach a
path-based reader again. Reopen every mounted volume sharing the index
base before leaving the rebuild.

* rust volume: repoint sibling journals sharing a folded .ecj after rebuild

rebuild_ecx_from_journal replaces the journal and reopens only its own
handle; mounts on sibling disks sharing that .ecj keep the detached
handle, so their next appends are lost at restart. Adopt the folded
journal on every mounted runtime sharing the path before releasing the
store lock, clearing their in-memory set — every journaled id is now an
.ecx tombstone.

* ec: swap the deletion journal handle only after the new file opens

A failed reopen left ecjFile nil, so every later delete returned
"ec volume closed". Open first, then close and swap — mirroring the
Rust adopt_folded_journal ordering.

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

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

* ec.rebuild: fail the rebuild when a sibling journal cannot be repointed

A warning left the sibling mount journaling to a detached inode while
the RPC reported success. Propagate the error like the Rust handler's
adopt_folded_journal map_err.

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

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

* ec: keep deletes loud when the journal reopen cannot open the replacement

Reverts the swap-on-success ordering: a detached handle kept on failure
lets deletes append and sync to the removed inode, then vanish at
restart. Closing first also frees the descriptor before the open.

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

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

* rust volume: drop the folded journal handle before reopening it

adopt_folded_journal and the post-fold recreate now clear ecj_file
before opening the replacement, so a failed reopen leaves deletes
erroring instead of appending to the detached inode. Mirrors Go's
ReopenDeletionJournal.

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

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

* ec: drop the cached journal size when its reopen fails

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

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

---------

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

214 lines
6.9 KiB
Go

package erasure_coding
import (
"fmt"
"io"
"os"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/storage/backend"
"github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util"
)
var (
MarkNeedleDeleted = func(file *os.File, offset int64) error {
b := make([]byte, types.SizeSize)
types.SizeToBytes(b, types.TombstoneFileSize)
n, err := file.WriteAt(b, offset+types.NeedleIdSize+types.OffsetSize)
if err != nil {
return fmt.Errorf("sorted needle write error: %w", err)
}
if n != types.SizeSize {
return fmt.Errorf("sorted needle written %d bytes, expecting %d", n, types.SizeSize)
}
return nil
}
)
// DeleteNeedleFromEcx marks the given needle as deleted. .ecx is treated
// as an immutable sealed sorted index; runtime deletes are recorded by
// appending the needle id to the .ecj deletion journal and inserting it
// into the in-memory deletedNeedles set. A subsequent FindNeedleFromEcx
// masks the id out by returning TombstoneFileSize.
//
// The .ecj append is the durable commit point — only after it syncs do
// we publish the id into the in-memory set. A partial write is truncated
// back to the known-good size so the on-disk journal and the set cannot
// drift.
func (ev *EcVolume) DeleteNeedleFromEcx(needleId types.NeedleId) (err error) {
// Look the needle up read-only. A missing needle is not an error
// (already gone, e.g. from a race against encode); a pre-existing
// .ecx tombstone means a prior decode/rebuild folded it in, in
// which case there is nothing to journal but we still mirror it
// into the in-memory set so delete_count stays consistent.
_, oldSize, err := SearchNeedleFromSortedIndex(ev.ecxFile, ev.ecxFileSize, needleId, nil)
if err != nil {
if err == NotFoundError {
return nil
}
return err
}
if oldSize.IsDeleted() {
ev.markNeedleDeletedInMemory(needleId)
return nil
}
// Serialise runtime deletes on ecjFileAccessLock so the idempotence
// check, the journal append and the set insertion happen atomically
// with respect to one another.
ev.ecjFileAccessLock.Lock()
defer ev.ecjFileAccessLock.Unlock()
if ev.IsNeedleDeleted(needleId) {
return nil
}
// Close nils ecjFile under this same lock, so a delete that resolved its
// .ecx lookup before an eviction (e.g. the generate-time UnloadEcVolume)
// can reach here with no journal fd. Bail with a clear error rather than
// operating on the closed/nil handle.
if ev.ecjFile == nil {
return fmt.Errorf("ec volume %d closed", ev.VolumeId)
}
b := make([]byte, types.NeedleIdSize)
types.NeedleIdToBytes(b, needleId)
if err := ev.appendJournalLocked(b); err != nil {
return err
}
// Publish into the in-memory set only after the journal is durable.
ev.markNeedleDeletedInMemory(needleId)
return nil
}
// appendJournalLocked appends whole records to .ecj and syncs them. A partial
// write is truncated back to the known-good size so the on-disk journal and
// deletedNeedles cannot drift. Callers hold ecjFileAccessLock and have checked
// that ecjFile is open.
func (ev *EcVolume) appendJournalLocked(b []byte) error {
prevEcjSize := ev.ecjFileSize
if _, seekErr := ev.ecjFile.Seek(0, io.SeekEnd); seekErr != nil {
return fmt.Errorf("seek ecj: %w", seekErr)
}
n, writeErr := ev.ecjFile.Write(b)
if writeErr != nil {
if truncErr := ev.ecjFile.Truncate(prevEcjSize); truncErr != nil {
glog.Errorf("ec volume %d: failed to truncate ecj after write error: %v", ev.VolumeId, truncErr)
}
return fmt.Errorf("write ecj: %w", writeErr)
}
if syncErr := ev.ecjFile.Sync(); syncErr != nil {
if truncErr := ev.ecjFile.Truncate(prevEcjSize); truncErr != nil {
glog.Errorf("ec volume %d: failed to truncate ecj after sync error: %v", ev.VolumeId, truncErr)
}
return fmt.Errorf("sync ecj: %w", syncErr)
}
ev.ecjFileSize += int64(n)
return nil
}
// LockDeletionJournal serializes the caller against runtime .ecj appends
// (DeleteNeedleFromEcx) until the returned func is called. Decode holds it
// while consuming the journal into the rebuilt index so a committed delete
// cannot slip past the publish.
func (ev *EcVolume) LockDeletionJournal() func() {
ev.ecjFileAccessLock.Lock()
return ev.ecjFileAccessLock.Unlock
}
// ReopenDeletionJournal repoints ecjFile at the live .ecj path after
// RebuildEcxFile unlinked it. Without this, later DeleteNeedleFromEcx
// appends keep landing on the detached inode — synced, successful, and
// invisible to every path-based reader. Caller must hold the journal lock
// (see LockDeletionJournal).
func (ev *EcVolume) ReopenDeletionJournal() error {
if ev.ecjFile != nil {
_ = ev.ecjFile.Close()
ev.ecjFile = nil
}
ecjFile, err := backend.OpenVolumeFile(ev.FileName(".ecj"), os.O_RDWR|os.O_CREATE)
if err != nil {
ev.ecjFileSize = 0
return fmt.Errorf("reopen ec volume journal %s: %w", ev.FileName(".ecj"), err)
}
ev.ecjFile = ecjFile
// A successful RebuildEcxFile leaves the path unlinked, so this is a
// fresh empty file — but track whatever is actually there so the
// rollback truncate in DeleteNeedleFromEcx can never wipe real records.
if fi, statErr := ecjFile.Stat(); statErr == nil {
ev.ecjFileSize = fi.Size()
} else {
ev.ecjFileSize = 0
}
return nil
}
func RebuildEcxFile(baseFileName string) error {
if !util.FileExists(baseFileName + ".ecj") {
return nil
}
ecxFile, err := os.OpenFile(baseFileName+".ecx", os.O_RDWR, 0644)
if err != nil {
return fmt.Errorf("rebuild: failed to open ecx file: %w", err)
}
defer ecxFile.Close()
fstat, err := ecxFile.Stat()
if err != nil {
return err
}
ecxFileSize := fstat.Size()
ecjFile, err := os.OpenFile(baseFileName+".ecj", os.O_RDWR, 0644)
if err != nil {
return fmt.Errorf("rebuild: failed to open ecj file: %w", err)
}
defer ecjFile.Close()
buf := make([]byte, types.NeedleIdSize)
for {
// io.ReadFull distinguishes a clean end (io.EOF) from a torn tail
// (io.ErrUnexpectedEOF) and a transient short read; a bare n!=size
// break would silently drop the rest of the journal and then unlink it.
_, readErr := io.ReadFull(ecjFile, buf)
if readErr == io.EOF {
break
}
if readErr != nil {
// Torn or unreadable journal: abort and leave .ecj in place so a
// retry can re-apply the deletions rather than resurrect them.
return fmt.Errorf("rebuild: read ecj: %w", readErr)
}
needleId := types.BytesToNeedleId(buf)
_, _, err = SearchNeedleFromSortedIndex(ecxFile, ecxFileSize, needleId, MarkNeedleDeleted)
if err != nil && err != NotFoundError {
return err
}
}
// Flush the in-place tombstones before removing the journal; otherwise a
// crash can persist the .ecj unlink ahead of the .ecx writes and resurrect
// the deleted needles on the next load.
if err = ecxFile.Sync(); err != nil {
return fmt.Errorf("rebuild: sync ecx: %w", err)
}
// Close the journal before unlinking it (Windows cannot delete an open
// file); the deferred Close becomes a harmless no-op.
ecjFile.Close()
os.Remove(baseFileName + ".ecj")
return nil
}