Compare commits

...
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 fc1db38fab erasure_coding: describe the orphan cleanup's needle check as a record match
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 00:53:40 -08:00
Chris LuandClaude Opus 5.5 52f6347766 erasure_coding: age an orphan source sighting against the shard count that made it complete
The prune compared every sighting with the default 14 shards, so a volume
whose collection uses another EC ratio lost its sighting at the start of
every detection pass and its orphan source was never cleaned. Record the
expected shard count with the sighting and prune against that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-06 00:53:04 -08:00
Chris Lu 68b595d7ca erasure_coding: bound the orphan cleanup's index reads
Detection runs with a background context, so a server that stalled while
streaming an .idx or .ecx held up the whole scan. Give each read a
deadline; a timed-out .ecx read moves on to the next shard holder, and the
replica is kept when none answers.
2026-12-06 00:48:11 -08:00
Chris Lu 3b07ea7145 erasure_coding: keep a source replica whose needle record differs from the EC volume's
A replica that was writable again after the encode can rewrite a needle
under a key the .ecx already lists. Checking only the key let cleanup
delete that newer copy.

Account for a live replica needle only when the .ecx holds it at the same
size, or holds it deleted at the same offset, which is the encoded record
deleted on the EC volume since. A needle resized, or deleted in the .ecx
while the replica holds another record of it, keeps the replica.
2026-12-06 00:46:12 -08:00
Chris Lu 13199aaf5f erasure_coding: prune orphan source sightings in one topology walk
Pruning counted the EC shards of each remembered sighting with its own
walk of the topology, under the sightings lock. Count the shards of all
sighted volumes in a single walk, outside the lock.
2026-12-06 00:41:55 -08:00
Chris Lu 29ca7f3fe3 ec: return EC shard holders by their advertised address
LargestEcGenerationHolders returned the data node id, which drops a
holder's Address and custom gRPC port, so reading its .ecx dialed the
wrong endpoint. Build each holder address from the data node instead.
2026-12-06 00:40:39 -08:00
Chris Lu f81b0e3a49 erasure_coding: treat a source replica as orphaned only after it has sat beside the shards for a while
A volume being decoded holds a freshly built regular copy beside its
complete shard set until the shards are removed, and that copy is
read-only with every needle in the .ecx, so the orphan cleanup could
delete it before the shards go.

Detection now records when it first sees each regular replica beside a
complete shard set and forgets the sighting once that stops being true.
Cleanup deletes a replica only after minOrphanSourceCoexistence (30m) of
coexistence. The record is in memory; a restart only delays cleanup.
2026-12-06 00:05:01 -08:00
Chris Lu 2984d0622e erasure_coding: keep a source replica that holds needles the EC volume lacks
A regular replica that coexists with a complete EC shard set was deleted
whenever it was read-only. Read-only does not show the replica took no
writes after the encode, so deleting it can drop needles the EC volume
never had.

Before deleting, read the replica's .idx and the .ecx of a holder of the
counted EC generation over CopyFile, and delete only when every live needle
key in the replica is a key of the .ecx, in any state. A replica holding
other live needles is kept with a warning; a replica or holder that cannot
be read refuses the delete.
2026-12-05 23:44:55 -08:00
Chris Lu 9d069cfd08 ec: name the holders of the largest EC shard generation
CountExistingEcShardsForVolume picks the largest encode generation by shard
count; LargestEcGenerationHolders returns the nodes holding that generation,
so a caller can read files of the EC volume that was counted rather than of
a stale run. A tie names no holder.
2026-12-05 23:41:15 -08:00
4 changed files with 713 additions and 12 deletions

No files matched your search

+74 -12
View File
@@ -1463,10 +1463,63 @@ func (ecb *ecBalancer) applyShardMoveRPC(src, dst *EcNode, collection string, vi
// separates generations living on different disks; same-disk mixing is prevented
// upstream by the pre-encode artifact wipe and the cross-run read guard.
func CountExistingEcShardsForVolume(topologyInfo *master_pb.TopologyInfo, volumeID uint32, collection string) int {
if topologyInfo == nil {
return 0
key := EcVolumeKey{VolumeId: volumeID, Collection: collection}
return CountExistingEcShardsForVolumes(topologyInfo, map[EcVolumeKey]struct{}{key: {}})[key]
}
// EcVolumeKey names an EC volume by id and collection.
type EcVolumeKey struct {
VolumeId uint32
Collection string
}
// CountExistingEcShardsForVolumes is CountExistingEcShardsForVolume for many
// volumes in one topology walk.
func CountExistingEcShardsForVolumes(topologyInfo *master_pb.TopologyInfo, volumes map[EcVolumeKey]struct{}) map[EcVolumeKey]int {
counts := make(map[EcVolumeKey]int, len(volumes))
for key, generations := range ecShardGenerations(topologyInfo, volumes) {
for _, gen := range generations {
if c := gen.bits.Count(); c > counts[key] {
counts[key] = c
}
}
}
perGeneration := make(map[int64]erasure_coding.ShardBits)
return counts
}
// LargestEcGenerationHolders returns the addresses of the nodes holding shards
// of the generation CountExistingEcShardsForVolume counts, or nil when no
// generation is strictly largest and so none can be named the EC volume.
func LargestEcGenerationHolders(topologyInfo *master_pb.TopologyInfo, volumeID uint32, collection string) []pb.ServerAddress {
key := EcVolumeKey{VolumeId: volumeID, Collection: collection}
var largest *ecShardGeneration
tied := false
for _, gen := range ecShardGenerations(topologyInfo, map[EcVolumeKey]struct{}{key: {}})[key] {
switch {
case largest == nil || gen.bits.Count() > largest.bits.Count():
largest, tied = gen, false
case gen.bits.Count() == largest.bits.Count():
tied = true
}
}
if largest == nil || tied {
return nil
}
return largest.holders
}
type ecShardGeneration struct {
bits erasure_coding.ShardBits
holders []pb.ServerAddress
}
// ecShardGenerations groups the shards of the given volumes in the topology
// by encode generation, recording each generation's shard bits and holders.
func ecShardGenerations(topologyInfo *master_pb.TopologyInfo, volumes map[EcVolumeKey]struct{}) map[EcVolumeKey]map[int64]*ecShardGeneration {
if topologyInfo == nil || len(volumes) == 0 {
return nil
}
found := make(map[EcVolumeKey]map[int64]*ecShardGeneration)
for _, dc := range topologyInfo.DataCenterInfos {
for _, rack := range dc.RackInfos {
for _, node := range rack.DataNodeInfos {
@@ -1478,22 +1531,31 @@ func CountExistingEcShardsForVolume(topologyInfo *master_pb.TopologyInfo, volume
if ecShardInfo == nil {
continue
}
if ecShardInfo.Id != volumeID || ecShardInfo.Collection != collection {
key := EcVolumeKey{VolumeId: ecShardInfo.Id, Collection: ecShardInfo.Collection}
if _, want := volumes[key]; !want {
continue
}
perGeneration[ecShardInfo.EncodeTsNs] |= erasure_coding.ShardBits(ecShardInfo.EcIndexBits)
perGeneration := found[key]
if perGeneration == nil {
perGeneration = make(map[int64]*ecShardGeneration)
found[key] = perGeneration
}
gen := perGeneration[ecShardInfo.EncodeTsNs]
if gen == nil {
gen = &ecShardGeneration{}
perGeneration[ecShardInfo.EncodeTsNs] = gen
}
bits := erasure_coding.ShardBits(ecShardInfo.EcIndexBits)
gen.bits |= bits
if holder := pb.NewServerAddressFromDataNode(node); bits.Count() > 0 && !slices.Contains(gen.holders, holder) {
gen.holders = append(gen.holders, holder)
}
}
}
}
}
}
best := 0
for _, bits := range perGeneration {
if c := bits.Count(); c > best {
best = c
}
}
return best
return found
}
// ParseVolumeIdsFlag parses a comma-separated -volumeIds flag value, dropping
@@ -1,10 +1,16 @@
package erasure_coding
import (
"bytes"
"context"
"fmt"
"io"
"maps"
"math"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
@@ -16,18 +22,29 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding/ecbalancer"
"github.com/seaweedfs/seaweedfs/weed/storage/idx"
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
"github.com/seaweedfs/seaweedfs/weed/storage/super_block"
storagetypes "github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/util/wildcard"
"github.com/seaweedfs/seaweedfs/weed/worker/tasks/base"
workerutil "github.com/seaweedfs/seaweedfs/weed/worker/tasks/util"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
"google.golang.org/grpc"
)
const (
minProposalsBeforeEarlyStop = 10
maxConsecutivePlanningFailures = 10
// A volume being decoded briefly holds a regular copy beside its complete
// shard set; only a replica that stays there this long is an orphan.
minOrphanSourceCoexistence = 30 * time.Minute
)
// orphanSourceIndexReadTimeout bounds each .idx/.ecx read of the orphan
// cleanup, so a stalled server cannot hold up detection.
var orphanSourceIndexReadTimeout = 5 * time.Minute
// Detection implements the detection logic for erasure coding tasks.
// It respects ctx cancellation and can stop early once maxResults is reached.
func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, clusterInfo *types.ClusterInfo, config base.TaskConfig, maxResults int) ([]*types.TaskDetectionResult, bool, error) {
@@ -57,6 +74,10 @@ func Detection(ctx context.Context, metrics []*types.VolumeHealthMetrics, cluste
skippedTooFewNodes := 0
consecutivePlanningFailures := 0
if clusterInfo != nil && clusterInfo.ActiveTopology != nil {
pruneOrphanSourceSightings(clusterInfo.ActiveTopology)
}
// EC shard replica placement: explicit config wins, else the master default.
var replicaPlacement *super_block.ReplicaPlacement
if clusterInfo != nil {
@@ -703,6 +724,10 @@ func findExistingECShards(activeTopology *topology.ActiveTopology, volumeID uint
// targeted server, never EC shards (those live in a separate store path).
// The cluster-wide `volume.delete` shell command is what would have nuked
// the EC shards too; the targeted RPC used here is safe by construction.
// A replica is deleted only once it has sat beside the shards for
// minOrphanSourceCoexistence, only while read-only, and only when every live
// needle in its .idx is accounted for by the EC volume's .ecx (see
// needlesMissingFromEc); one that took writes after the encode is kept.
// Returns the count of replicas successfully deleted plus any error.
func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.ClusterInfo, metric *types.VolumeHealthMetrics, expectedShards int) (int, error) {
if clusterInfo == nil || clusterInfo.ActiveTopology == nil {
@@ -728,11 +753,26 @@ func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.Cluster
return 0, nil
}
ecx := &ecxReader{
holders: ec.LargestEcGenerationHolders(clusterInfo.ActiveTopology.GetTopologyInfo(), metric.VolumeID, metric.Collection),
volumeID: metric.VolumeID,
collection: metric.Collection,
dialOption: clusterInfo.GrpcDialOption,
}
deleted := 0
var deleteErrors []string
now := time.Now()
for _, replica := range replicas {
serverAddress := replica.ServerID
sighting := orphanSourceKey{volumeID: metric.VolumeID, collection: metric.Collection, server: serverAddress}
if sat := now.Sub(sightOrphanSource(sighting, expectedShards, now)); sat < minOrphanSourceCoexistence {
glog.V(1).Infof("EC Detection: source replica for volume %d on %s has sat beside the EC shards for %v; waiting %v before treating it as orphaned",
metric.VolumeID, serverAddress, sat.Truncate(time.Second), minOrphanSourceCoexistence)
continue
}
var isReadOnly bool
var missing int
err := operation.WithVolumeServerClient(false, pb.ServerAddress(serverAddress), clusterInfo.GrpcDialOption,
func(client volume_server_pb.VolumeServerClient) error {
// Re-probe before deleting: only a still-readonly source replica is
@@ -746,6 +786,12 @@ func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.Cluster
if !isReadOnly {
return nil
}
// Read-only does not prove the replica took no writes after
// the encode: it may have been writable in between.
var checkErr error
if missing, checkErr = needlesMissingFromEc(ctx, client, metric.VolumeID, metric.Collection, ecx); checkErr != nil || missing > 0 {
return checkErr
}
_, deleteErr := client.VolumeDelete(ctx, &volume_server_pb.VolumeDeleteRequest{
VolumeId: metric.VolumeID,
OnlyEmpty: false,
@@ -760,7 +806,12 @@ func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.Cluster
glog.Warningf("EC Detection: source replica for volume %d on %s is writable; not deleting (may hold writes the EC shards lack)", metric.VolumeID, serverAddress)
continue
}
if missing > 0 {
glog.Warningf("EC Detection: source replica for volume %d on %s holds %d needles the EC volume lacks or holds differently; keeping it", metric.VolumeID, serverAddress, missing)
continue
}
deleted++
forgetOrphanSource(sighting)
glog.V(1).Infof("EC Detection: deleted orphan regular replica for volume %d on %s", metric.VolumeID, serverAddress)
}
@@ -770,6 +821,181 @@ func cleanupOrphanSourceReplicas(ctx context.Context, clusterInfo *types.Cluster
return deleted, nil
}
type orphanSourceKey struct {
volumeID uint32
collection string
server string
}
// orphanSourceSighting is when detection first saw a regular replica beside a
// complete EC shard set, and the shard count that made the set complete.
type orphanSourceSighting struct {
at time.Time
expectedShards int
}
// orphanSourceSightings is in memory only: a restart just delays cleanup.
var orphanSourceSightings = struct {
sync.Mutex
firstSeen map[orphanSourceKey]orphanSourceSighting
}{firstSeen: make(map[orphanSourceKey]orphanSourceSighting)}
// sightOrphanSource records a sighting and returns the first one.
func sightOrphanSource(key orphanSourceKey, expectedShards int, now time.Time) time.Time {
orphanSourceSightings.Lock()
defer orphanSourceSightings.Unlock()
sighting, found := orphanSourceSightings.firstSeen[key]
if !found {
sighting.at = now
}
sighting.expectedShards = expectedShards
orphanSourceSightings.firstSeen[key] = sighting
return sighting.at
}
func forgetOrphanSource(key orphanSourceKey) {
orphanSourceSightings.Lock()
defer orphanSourceSightings.Unlock()
delete(orphanSourceSightings.firstSeen, key)
}
// pruneOrphanSourceSightings forgets every sighting whose replica no longer
// sits beside a complete EC shard set, so a coexistence that ends and later
// recurs starts its wait over.
func pruneOrphanSourceSightings(activeTopology *topology.ActiveTopology) {
orphanSourceSightings.Lock()
sightings := maps.Clone(orphanSourceSightings.firstSeen)
orphanSourceSightings.Unlock()
if len(sightings) == 0 {
return
}
volumes := make(map[ec.EcVolumeKey]struct{}, len(sightings))
for key := range sightings {
volumes[ec.EcVolumeKey{VolumeId: key.volumeID, Collection: key.collection}] = struct{}{}
}
shardCounts := ec.CountExistingEcShardsForVolumes(activeTopology.GetTopologyInfo(), volumes)
var ended []orphanSourceKey
for key, sighting := range sightings {
if shardCounts[ec.EcVolumeKey{VolumeId: key.volumeID, Collection: key.collection}] < sighting.expectedShards ||
!slices.ContainsFunc(findVolumeReplicaLocations(activeTopology, key.volumeID, key.collection), func(replica topology.VolumeReplica) bool {
return replica.ServerID == key.server
}) {
ended = append(ended, key)
}
}
orphanSourceSightings.Lock()
defer orphanSourceSightings.Unlock()
for _, key := range ended {
delete(orphanSourceSightings.firstSeen, key)
}
}
// needlesMissingFromEc counts the live needles in the replica's .idx that the
// EC volume's .ecx does not account for. The .ecx lists the needles live at
// encode time with their sizes; a later delete marks its entry in place and
// keeps the offset. A live replica needle is accounted for when the .ecx holds
// it at the same size, or deleted at the same offset (the encoded record,
// deleted since). Anything else may be data the EC volume never had.
func needlesMissingFromEc(ctx context.Context, client volume_server_pb.VolumeServerClient, volumeID uint32, collection string, ecx *ecxReader) (int, error) {
idxBytes, err := readVolumeFile(ctx, client, volumeID, collection, ".idx", false)
if err != nil {
return 0, fmt.Errorf("read source replica .idx: %w", err)
}
live := make(map[storagetypes.NeedleId]needle_map.NeedleValue)
err = idx.WalkIndexFile(bytes.NewReader(idxBytes), 0, func(key storagetypes.NeedleId, offset storagetypes.Offset, size storagetypes.Size) error {
if offset.IsZero() || !size.IsValid() {
delete(live, key)
} else {
live[key] = needle_map.NeedleValue{Key: key, Offset: offset, Size: size}
}
return nil
})
if err != nil {
return 0, fmt.Errorf("walk source replica .idx: %w", err)
}
if len(live) == 0 {
return 0, nil
}
ecxBytes, err := ecx.read(ctx)
if err != nil {
return 0, err
}
err = idx.WalkIndexFile(bytes.NewReader(ecxBytes), 0, func(key storagetypes.NeedleId, offset storagetypes.Offset, size storagetypes.Size) error {
if replica, found := live[key]; found && (size == replica.Size || size.IsDeleted() && offset == replica.Offset) {
delete(live, key)
}
return nil
})
if err != nil {
return 0, fmt.Errorf("walk .ecx: %w", err)
}
return len(live), nil
}
// ecxReader fetches the EC volume's .ecx from one of its shard holders, once.
type ecxReader struct {
holders []pb.ServerAddress
volumeID uint32
collection string
dialOption grpc.DialOption
content []byte
loaded bool
}
func (r *ecxReader) read(ctx context.Context) ([]byte, error) {
if r.loaded {
return r.content, nil
}
if len(r.holders) == 0 {
return nil, fmt.Errorf("no EC shard holder of volume %d to read .ecx from", r.volumeID)
}
var errs []string
for _, holder := range r.holders {
err := operation.WithVolumeServerClient(false, holder, r.dialOption,
func(client volume_server_pb.VolumeServerClient) error {
content, readErr := readVolumeFile(ctx, client, r.volumeID, r.collection, ".ecx", true)
r.content = content
return readErr
})
if err == nil {
r.loaded = true
return r.content, nil
}
errs = append(errs, fmt.Sprintf("%s: %v", holder, err))
}
return nil, fmt.Errorf("read .ecx of volume %d: %s", r.volumeID, strings.Join(errs, "; "))
}
// readVolumeFile reads a whole volume file over the CopyFile RPC.
func readVolumeFile(ctx context.Context, client volume_server_pb.VolumeServerClient, volumeID uint32, collection, ext string, isEcVolume bool) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, orphanSourceIndexReadTimeout)
defer cancel()
stream, err := client.CopyFile(ctx, &volume_server_pb.CopyFileRequest{
VolumeId: volumeID,
Collection: collection,
Ext: ext,
CompactionRevision: math.MaxUint32,
StopOffset: math.MaxInt64,
IsEcVolume: isEcVolume,
})
if err != nil {
return nil, err
}
var buf bytes.Buffer
for {
resp, recvErr := stream.Recv()
if recvErr == io.EOF {
return buf.Bytes(), nil
}
if recvErr != nil {
return nil, recvErr
}
buf.Write(resp.GetFileContent())
}
}
// countExistingEcShardsForVolume counts (volumeID, collection) EC shards in the
// topology, counting only the single largest encode generation; see
// ec.CountExistingEcShardsForVolume for the generation semantics.
@@ -5,6 +5,8 @@ import (
"testing"
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
"github.com/seaweedfs/seaweedfs/weed/ec"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/stretchr/testify/require"
)
@@ -90,3 +92,50 @@ func TestCountExistingEcShards_PreUpgradeZeroGeneration(t *testing.T) {
})
require.Equal(t, 14, countExistingEcShardsForVolume(at, vid, ""))
}
// The .ecx used to vet a source replica must come from a holder of the
// generation that is counted as the EC volume, never from a stale run, and no
// holder is named when two generations tie.
func TestLargestEcGenerationHolders(t *testing.T) {
const vid = uint32(45)
at := buildEcTopology(t, vid, "", []ecShardSet{
{bits: ecBits(0, 1, 2), encodeTsNs: 1},
{bits: ecBits(0, 1, 2, 3, 4, 5, 6), encodeTsNs: 2},
{bits: ecBits(7, 8, 9, 10, 11, 12, 13), encodeTsNs: 2},
})
require.Equal(t, []pb.ServerAddress{"10.0.0.2:8080", "10.0.0.3:8080"}, ec.LargestEcGenerationHolders(at.GetTopologyInfo(), vid, ""))
tied := buildEcTopology(t, vid, "", []ecShardSet{
{bits: ecBits(0, 1, 2), encodeTsNs: 1},
{bits: ecBits(3, 4, 5), encodeTsNs: 2},
})
require.Nil(t, ec.LargestEcGenerationHolders(tied.GetTopologyInfo(), vid, ""))
require.Nil(t, ec.LargestEcGenerationHolders(nil, vid, ""))
}
// One walk counts each requested volume as CountExistingEcShardsForVolume does,
// keeping generations and collections apart and skipping unrequested volumes.
func TestCountExistingEcShardsForVolumes(t *testing.T) {
shards := func(vid uint32, collection string, bits uint32, encodeTsNs int64) *master_pb.VolumeEcShardInformationMessage {
return &master_pb.VolumeEcShardInformationMessage{Id: vid, Collection: collection, EcIndexBits: bits, EncodeTsNs: encodeTsNs}
}
node := func(id string, infos ...*master_pb.VolumeEcShardInformationMessage) *master_pb.DataNodeInfo {
return &master_pb.DataNodeInfo{Id: id, DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {EcShardInfos: infos}}}
}
topologyInfo := &master_pb.TopologyInfo{DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{Id: "rack1", DataNodeInfos: []*master_pb.DataNodeInfo{
node("10.0.0.1:8080", shards(1, "", ecBits(0, 1, 2, 3, 4, 5, 6), 7), shards(2, "", ecBits(0, 1, 2), 1)),
node("10.0.0.2:8080", shards(1, "", ecBits(7, 8, 9, 10, 11, 12, 13), 7), shards(2, "", ecBits(3, 4), 2), shards(2, "other", ecBits(5, 6, 7, 8), 1)),
node("10.0.0.3:8080", shards(3, "", ecBits(0, 1), 1)),
}}},
}}}
counts := ec.CountExistingEcShardsForVolumes(topologyInfo, map[ec.EcVolumeKey]struct{}{
{VolumeId: 1}: {},
{VolumeId: 2}: {},
{VolumeId: 4}: {},
})
require.Equal(t, map[ec.EcVolumeKey]int{{VolumeId: 1}: 14, {VolumeId: 2}: 3}, counts)
require.Equal(t, 14, ec.CountExistingEcShardsForVolume(topologyInfo, 1, ""))
require.Equal(t, 4, ec.CountExistingEcShardsForVolume(topologyInfo, 2, "other"))
}
@@ -1,7 +1,13 @@
package erasure_coding
import (
"bytes"
"context"
"fmt"
"net"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -10,6 +16,9 @@ import (
"github.com/seaweedfs/seaweedfs/weed/admin/topology"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
"github.com/seaweedfs/seaweedfs/weed/storage/needle_map"
storagetypes "github.com/seaweedfs/seaweedfs/weed/storage/types"
"github.com/seaweedfs/seaweedfs/weed/worker/types"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
@@ -36,6 +45,7 @@ func TestCleanupOrphanSkipsWritableSourceReplica(t *testing.T) {
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
metric := &types.VolumeHealthMetrics{VolumeID: volumeID, Collection: ""}
backdateOrphanSource(t, volumeID, "", clusterHarness.VolumeServerAddress())
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
@@ -92,3 +102,357 @@ func buildSingleNodeTopology(t *testing.T, serverAddr string, volumeID uint32) *
require.NoError(t, at.UpdateTopology(topologyInfo))
return at
}
// fakeOrphanServer is a stub VolumeServer serving a read-only source replica's
// .idx or an EC shard holder's .ecx, and recording a VolumeDelete.
type fakeOrphanServer struct {
volume_server_pb.UnimplementedVolumeServerServer
mu sync.Mutex
files map[string][]byte
copyErr error
stall bool
deleted bool
}
func (f *fakeOrphanServer) VolumeStatus(context.Context, *volume_server_pb.VolumeStatusRequest) (*volume_server_pb.VolumeStatusResponse, error) {
return &volume_server_pb.VolumeStatusResponse{IsReadOnly: true}, nil
}
func (f *fakeOrphanServer) VolumeDelete(context.Context, *volume_server_pb.VolumeDeleteRequest) (*volume_server_pb.VolumeDeleteResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.deleted = true
return &volume_server_pb.VolumeDeleteResponse{}, nil
}
func (f *fakeOrphanServer) CopyFile(req *volume_server_pb.CopyFileRequest, stream grpc.ServerStreamingServer[volume_server_pb.CopyFileResponse]) error {
if f.copyErr != nil {
return f.copyErr
}
if f.stall {
<-stream.Context().Done()
return stream.Context().Err()
}
f.mu.Lock()
content, found := f.files[req.GetExt()]
f.mu.Unlock()
if !found || req.GetIsEcVolume() != (req.GetExt() == ".ecx") {
return fmt.Errorf("volume %d%s not found", req.GetVolumeId(), req.GetExt())
}
return stream.Send(&volume_server_pb.CopyFileResponse{FileContent: content})
}
func (f *fakeOrphanServer) setFile(ext string, content []byte) {
f.mu.Lock()
defer f.mu.Unlock()
f.files[ext] = content
}
func (f *fakeOrphanServer) wasDeleted() bool {
f.mu.Lock()
defer f.mu.Unlock()
return f.deleted
}
func startFakeOrphanServer(t *testing.T, server *fakeOrphanServer) string {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
grpcServer := grpc.NewServer()
volume_server_pb.RegisterVolumeServerServer(grpcServer, server)
go grpcServer.Serve(lis)
t.Cleanup(grpcServer.Stop)
_, port, err := net.SplitHostPort(lis.Addr().String())
require.NoError(t, err)
return "127.0.0.1:0." + port
}
// indexEntry is one index record; an unset offset is derived from the key.
type indexEntry struct {
key uint64
size storagetypes.Size
offset int64
}
func indexBytes(entries ...indexEntry) []byte {
var buf bytes.Buffer
for _, e := range entries {
offset := e.offset
if offset == 0 {
offset = int64(e.key) * 8
}
buf.Write(needle_map.ToBytes(storagetypes.NeedleId(e.key), storagetypes.ToOffset(offset), e.size))
}
return buf.Bytes()
}
// buildOrphanTopology places the regular replica on replicaAddr and the full
// EC shard set on holderAddr. The holder reports its gRPC port in GrpcPort
// rather than in its id, so it is reachable only through that port.
func buildOrphanTopology(t *testing.T, replicaAddr, holderAddr string, volumeID uint32) *topology.ActiveTopology {
t.Helper()
grpcPort, err := strconv.Atoi(holderAddr[strings.LastIndex(holderAddr, ".")+1:])
require.NoError(t, err)
at := topology.NewActiveTopology(10)
require.NoError(t, at.UpdateTopology(&master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{
Id: "rack1",
DataNodeInfos: []*master_pb.DataNodeInfo{
{Id: replicaAddr, DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {
VolumeInfos: []*master_pb.VolumeInformationMessage{{Id: volumeID}},
}}},
{Id: "ec-holder", Address: "127.0.0.1:1", GrpcPort: uint32(grpcPort), DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{
Id: volumeID,
EcIndexBits: uint32(1)<<erasure_coding.TotalShardsCount - 1,
EncodeTsNs: 1,
}},
}}},
},
}},
}},
}))
return at
}
// A read-only source replica is deleted only when the EC volume's .ecx accounts
// for every live needle in its .idx: held at the same size, or deleted at the
// same offset.
func TestCleanupOrphanChecksSourceNeedlesAgainstEcx(t *testing.T) {
const volumeID = uint32(956)
ecx := indexBytes(
indexEntry{key: 1, size: 100},
indexEntry{key: 2, size: storagetypes.TombstoneFileSize},
indexEntry{key: 3, size: 100},
)
tests := []struct {
name string
idx []byte
ecxCopyErr error
wantDeleted bool
wantErr bool
}{
{
name: "live needles held in ecx or deleted there in place",
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 2, size: 100}, indexEntry{key: 3, size: 100}),
wantDeleted: true,
},
{
name: "live needles in ecx at other offsets",
idx: indexBytes(indexEntry{key: 1, size: 100, offset: 800}, indexEntry{key: 3, size: 100, offset: 808}),
wantDeleted: true,
},
{
name: "needle rewritten at another size",
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 3, size: 100}, indexEntry{key: 3, size: 150, offset: 800}),
},
{
name: "needle deleted in ecx but rewritten in the replica",
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 2, size: 100, offset: 800}),
},
{
name: "live needle absent from ecx",
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 4, size: 100}, indexEntry{key: 5, size: 100}),
},
{
name: "needle absent from ecx is deleted in the replica",
idx: indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 4, size: 100}, indexEntry{key: 4, size: storagetypes.TombstoneFileSize}),
wantDeleted: true,
},
{
name: "ecx copy fails",
idx: indexBytes(indexEntry{key: 1, size: 100}),
ecxCopyErr: fmt.Errorf("holder unreachable"),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
replica := &fakeOrphanServer{files: map[string][]byte{".idx": tt.idx}}
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": ecx}, copyErr: tt.ecxCopyErr}
replicaAddr := startFakeOrphanServer(t, replica)
clusterInfo := &types.ClusterInfo{
ActiveTopology: buildOrphanTopology(t, replicaAddr, startFakeOrphanServer(t, holder), volumeID),
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
backdateOrphanSource(t, volumeID, "", replicaAddr)
metric := &types.VolumeHealthMetrics{VolumeID: volumeID}
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
require.Equal(t, tt.wantDeleted, replica.wasDeleted())
if tt.wantDeleted {
require.Equal(t, 1, deleted)
} else {
require.Equal(t, 0, deleted)
}
require.False(t, holder.wasDeleted())
})
}
}
// backdateOrphanSource records a sighting old enough for cleanup to act on.
func backdateOrphanSource(t *testing.T, volumeID uint32, collection, server string) {
t.Helper()
key := orphanSourceKey{volumeID: volumeID, collection: collection, server: server}
orphanSourceSightings.Lock()
orphanSourceSightings.firstSeen[key] = orphanSourceSighting{
at: time.Now().Add(-minOrphanSourceCoexistence - time.Minute),
expectedShards: erasure_coding.TotalShardsCount,
}
orphanSourceSightings.Unlock()
t.Cleanup(func() { forgetOrphanSource(key) })
}
// A replica first seen beside the shards is left alone; once it has sat there
// for minOrphanSourceCoexistence it is deleted, still subject to the needle check.
func TestCleanupOrphanWaitsForSustainedCoexistence(t *testing.T) {
const volumeID = uint32(957)
ecx := indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 2, size: 100})
replica := &fakeOrphanServer{files: map[string][]byte{".idx": indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 3, size: 100})}}
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": ecx}}
replicaAddr := startFakeOrphanServer(t, replica)
clusterInfo := &types.ClusterInfo{
ActiveTopology: buildOrphanTopology(t, replicaAddr, startFakeOrphanServer(t, holder), volumeID),
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
metric := &types.VolumeHealthMetrics{VolumeID: volumeID}
t.Cleanup(func() { forgetOrphanSource(orphanSourceKey{volumeID: volumeID, server: replicaAddr}) })
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
require.NoError(t, err)
require.Equal(t, 0, deleted)
require.False(t, replica.wasDeleted(), "a replica first seen beside the shards must not be deleted")
backdateOrphanSource(t, volumeID, "", replicaAddr)
deleted, err = cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
require.NoError(t, err)
require.Equal(t, 0, deleted)
require.False(t, replica.wasDeleted(), "an aged replica holding needles the EC volume lacks must be kept")
replica.setFile(".idx", indexBytes(indexEntry{key: 1, size: 100}, indexEntry{key: 2, size: 100}))
deleted, err = cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
require.NoError(t, err)
require.Equal(t, 1, deleted)
require.True(t, replica.wasDeleted())
}
// A sighting is forgotten once the replica no longer sits beside a complete
// shard set, so a later coexistence (such as a decode) waits from scratch.
func TestOrphanSourceSightingResetsWhenCoexistenceEnds(t *testing.T) {
const volumeID = uint32(958)
ecx := indexBytes(indexEntry{key: 1, size: 100})
replica := &fakeOrphanServer{files: map[string][]byte{".idx": indexBytes(indexEntry{key: 1, size: 100})}}
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": ecx}}
replicaAddr := startFakeOrphanServer(t, replica)
fullTopology := buildOrphanTopology(t, replicaAddr, startFakeOrphanServer(t, holder), volumeID)
clusterInfo := &types.ClusterInfo{
ActiveTopology: fullTopology,
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
metric := &types.VolumeHealthMetrics{VolumeID: volumeID}
key := orphanSourceKey{volumeID: volumeID, server: replicaAddr}
backdateOrphanSource(t, volumeID, "", replicaAddr)
goneKey := orphanSourceKey{volumeID: volumeID, server: "127.0.0.1:0.1"}
backdateOrphanSource(t, volumeID, "", goneKey.server)
pruneOrphanSourceSightings(fullTopology)
orphanSourceSightings.Lock()
_, kept := orphanSourceSightings.firstSeen[key]
_, goneKept := orphanSourceSightings.firstSeen[goneKey]
orphanSourceSightings.Unlock()
require.True(t, kept, "a sighting must survive while the coexistence lasts")
require.False(t, goneKept, "a sighting of a server no longer holding the replica must be forgotten")
pruneOrphanSourceSightings(buildSingleNodeTopology(t, replicaAddr, volumeID))
orphanSourceSightings.Lock()
_, kept = orphanSourceSightings.firstSeen[key]
orphanSourceSightings.Unlock()
require.False(t, kept, "a sighting must be forgotten once the shards are gone")
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, metric, erasure_coding.TotalShardsCount)
require.NoError(t, err)
require.Equal(t, 0, deleted)
require.False(t, replica.wasDeleted(), "a renewed coexistence must wait again")
}
// A collection encoded with fewer shards than the default ratio is complete at
// its own count, so its sighting must age instead of being pruned every cycle.
func TestOrphanSourceSightingKeepsCustomRatioShardSet(t *testing.T) {
const volumeID = uint32(960)
const customShards = 9
replica := &fakeOrphanServer{files: map[string][]byte{".idx": indexBytes(indexEntry{key: 1, size: 100})}}
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": indexBytes(indexEntry{key: 1, size: 100})}}
replicaAddr := startFakeOrphanServer(t, replica)
at := buildOrphanTopology(t, replicaAddr, startFakeOrphanServer(t, holder), volumeID)
topologyInfo := at.GetTopologyInfo()
topologyInfo.DataCenterInfos[0].RackInfos[0].DataNodeInfos[1].DiskInfos["hdd"].EcShardInfos[0].EcIndexBits = uint32(1)<<customShards - 1
require.NoError(t, at.UpdateTopology(topologyInfo))
clusterInfo := &types.ClusterInfo{
ActiveTopology: at,
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
key := orphanSourceKey{volumeID: volumeID, server: replicaAddr}
t.Cleanup(func() { forgetOrphanSource(key) })
sightOrphanSource(key, customShards, time.Now().Add(-minOrphanSourceCoexistence-time.Minute))
pruneOrphanSourceSightings(at)
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, &types.VolumeHealthMetrics{VolumeID: volumeID}, customShards)
require.NoError(t, err)
require.Equal(t, 1, deleted)
require.True(t, replica.wasDeleted(), "a sighting of a complete custom-ratio shard set must survive the prune")
}
// A holder that stalls mid-read is given up on after orphanSourceIndexReadTimeout
// and the .ecx is read from the next holder instead.
func TestCleanupOrphanReadsEcxPastStalledHolder(t *testing.T) {
const volumeID = uint32(959)
saved := orphanSourceIndexReadTimeout
orphanSourceIndexReadTimeout = 200 * time.Millisecond
t.Cleanup(func() { orphanSourceIndexReadTimeout = saved })
ecx := indexBytes(indexEntry{key: 1, size: 100})
replica := &fakeOrphanServer{files: map[string][]byte{".idx": ecx}}
stalled := &fakeOrphanServer{stall: true}
holder := &fakeOrphanServer{files: map[string][]byte{".ecx": ecx}}
replicaAddr := startFakeOrphanServer(t, replica)
half := func(addr string, bits uint32) *master_pb.DataNodeInfo {
return &master_pb.DataNodeInfo{Id: addr, DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {
EcShardInfos: []*master_pb.VolumeEcShardInformationMessage{{Id: volumeID, EcIndexBits: bits, EncodeTsNs: 1}},
}}}
}
at := topology.NewActiveTopology(10)
require.NoError(t, at.UpdateTopology(&master_pb.TopologyInfo{
DataCenterInfos: []*master_pb.DataCenterInfo{{
Id: "dc1",
RackInfos: []*master_pb.RackInfo{{
Id: "rack1",
DataNodeInfos: []*master_pb.DataNodeInfo{
{Id: replicaAddr, DiskInfos: map[string]*master_pb.DiskInfo{"hdd": {
VolumeInfos: []*master_pb.VolumeInformationMessage{{Id: volumeID}},
}}},
half(startFakeOrphanServer(t, stalled), uint32(1)<<erasure_coding.DataShardsCount-1),
half(startFakeOrphanServer(t, holder), (uint32(1)<<erasure_coding.TotalShardsCount-1)&^(uint32(1)<<erasure_coding.DataShardsCount-1)),
},
}},
}},
}))
clusterInfo := &types.ClusterInfo{
ActiveTopology: at,
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}
backdateOrphanSource(t, volumeID, "", replicaAddr)
deleted, err := cleanupOrphanSourceReplicas(context.Background(), clusterInfo, &types.VolumeHealthMetrics{VolumeID: volumeID}, erasure_coding.TotalShardsCount)
require.NoError(t, err)
require.Equal(t, 1, deleted)
require.True(t, replica.wasDeleted())
}