From f2e9e49842b06c37e6245f191cfecbf58cf6ad5d Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Thu, 26 Nov 2026 22:46:28 -0800 Subject: [PATCH] master: stop volume growth from leaking volumes into a just-deleted collection (#13035) * topology: stop a grow once a delete fences its collection A grow request creates its volumes one after another and resolves the collection by name for each, so once the collection was deleted the rest of the request recreated it. The request now keeps the collection it started in and holds a per-collection fence shared while it creates each volume. A delete can raise the fence exclusively, which waits out the volume in flight, and the request stops at its next volume. A collection dropped only because its last layout emptied is followed to the one published under its name. Co-Authored-By: Claude Opus 5.5 * master: fence volume growth before deleting a collection The delete listed the collection's servers, fanned out DeleteCollection, and only then dropped the collection from the topology. A grow still running created its next volumes during or after the fan-out, on servers that had already been cleaned or were not in the list, and those volumes registered a new layout for the deleted collection that nothing removed. A bucket deleted right after its first write leaked most of its initial volumes this way. The delete now raises the collection's growth fence first, so the volume in flight registers and is deleted with the rest, and the grow stops. A failed fan-out lifts the fence, since the collection stays in place. Co-Authored-By: Claude Opus 5.5 * topology: refuse assigns from a collection being deleted The delete waits for the volume a grow is creating before it lists the collection's servers, and the collection's writable volumes stayed assignable meanwhile, so a write could land in a volume about to be deleted. The delete now raises the fence before it waits, and assigns check it. Co-Authored-By: Claude Opus 5.5 * topology: list only collections that hold a volume layout A grow request publishes its collection before its first volume registers, so one that created nothing left a collection with no volume in the list. Co-Authored-By: Claude Opus 5.5 * topology: queue no grow for a collection being deleted PickForWrite returned the layout's shouldGrow before it checked the fence, so an assign on an empty layout of a collection being deleted still queued a grow. That grow could run after the delete finished and recreate the collection. Check the fence right after the pick, before any early return. Co-Authored-By: Claude Opus 5.5 * topology: keep an emptied collection published while growth holds it DeleteLayout unpublished a collection as soon as its last layout emptied, even while a grow held it or a delete had fenced it. The volume in flight then registered by name into a new collection that the delete never listed servers for, and the delete's final DeleteCollection dropped it from the topology while it stayed on disk. Unpublish an empty collection only when no grow or delete holds it. Co-Authored-By: Claude Opus 5.5 * topology: fence the collection still published under the name An emptied-layout cleanup that passed its fence check could unpublish the collection while the delete waited to fence it. The delete then fenced and listed an orphaned object, while growth published a new collection under the name that no fence held. Topology.FenceGrowth re-checks publication once the fence is up and moves to the collection published since. Co-Authored-By: Claude Opus 5.5 * topology: run one delete of a collection at a time Two deletes of one collection both fenced it and fanned out by name. Once the first removed it, a write could recreate the collection, and the second delete removed the new one's volumes and topology entry. FenceGrowth now waits for a delete already running on the collection and finds nothing once that delete removed it; a delete that failed hands the collection to the one waiting. Co-Authored-By: Claude Opus 5.5 * topology: stop a delete another delete beat to the collection A delete that fenced the collection but had not yet checked that it was still published retried when it was not, for the collection an emptied layout drops. A delete that removed it in between also left it unpublished, so the retry fenced and returned the collection a write had recreated under the name since. finish(true) now marks the collection deleted before it unpublishes it, and the retry stops at that mark. Co-Authored-By: Claude Opus 5.5 * master: keep the name fenced through the EC pass of a delete The normal pass unpublished the collection and let growth back in before the EC pass ran. The EC pass deletes by name on every server holding the collection's shards, and DeleteCollection on a server also drops its normal volumes, so a write recreating the bucket in between could land a volume that the EC pass then deleted. A second delete of the name, finding no collection, also ran its own EC pass by name. deleteCollection now fences the name once, before either pass, and lifts or ends the fence after both. finish(true) unpublishes the collection then. A name with EC shards only gets an empty collection to fence, so an assign under it is refused too, and a delete that finds nothing skips both passes. Co-Authored-By: Claude Opus 5.5 * topology: wait for the second delete's lock instead of sleeping The overlapping-delete tests slept before acting on the first delete. A second delete scheduled late started after the collection was replaced, or after the first delete was already over, so the tests could fail or pass without the overlap they check. They now wait until the second delete is blocked on the delete lock, read from the goroutine stacks. Co-Authored-By: Claude Opus 5.5 * topology: empty the layout through UnRegisterVolumeLayout in the test The test called DeleteLayout, whose signature differs in builds that key layouts by more than replication, TTL and disk type. UnRegisterVolumeLayout reaches the same cleanup from a VolumeInfo and has one signature everywhere. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/server/master_grpc_server_collection.go | 25 +- .../master_grpc_server_collection_test.go | 257 +++++++++++- weed/topology/collection.go | 1 + weed/topology/collection_growth.go | 119 ++++++ weed/topology/collection_growth_test.go | 381 ++++++++++++++++++ weed/topology/topology.go | 13 +- weed/topology/volume_growth.go | 11 + 7 files changed, 785 insertions(+), 22 deletions(-) create mode 100644 weed/topology/collection_growth.go create mode 100644 weed/topology/collection_growth_test.go diff --git a/weed/server/master_grpc_server_collection.go b/weed/server/master_grpc_server_collection.go index 08e95db9f1..5f9eafb04d 100644 --- a/weed/server/master_grpc_server_collection.go +++ b/weed/server/master_grpc_server_collection.go @@ -11,6 +11,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" + "github.com/seaweedfs/seaweedfs/weed/topology" ) // deleteCollectionTimeout bounds one DeleteCollection RPC to a volume server, so @@ -65,8 +66,16 @@ func (ms *MasterServer) deleteCollection(ctx context.Context, collectionName str // running to come back for them. Each RPC is bounded on its own. ctx = context.WithoutCancel(ctx) - normalErr := ms.doDeleteNormalCollection(ctx, collectionName) + // Before listing the servers, and held through both passes: a grow still + // running, or an assign or grow under the name, would otherwise place a + // volume on a server one pass misses, or one that a pass then deletes by name. + collection, finish, ok := ms.Topo.FenceGrowth(collectionName) + if !ok { + return nil + } + normalErr := ms.doDeleteNormalCollection(ctx, collection) ecErr := ms.doDeleteEcCollection(ctx, collectionName) + finish(normalErr == nil) if normalErr != nil { if ecErr != nil { @@ -78,12 +87,7 @@ func (ms *MasterServer) deleteCollection(ctx context.Context, collectionName str return ecErr } -func (ms *MasterServer) doDeleteNormalCollection(ctx context.Context, collectionName string) error { - - collection, ok := ms.Topo.FindCollection(collectionName) - if !ok { - return nil - } +func (ms *MasterServer) doDeleteNormalCollection(ctx context.Context, collection *topology.Collection) error { // One RPC per server, not one per replica: ListVolumeServers reports a node // once for every replica it holds, while DeleteCollection removes the whole @@ -100,12 +104,7 @@ func (ms *MasterServer) doDeleteNormalCollection(ctx context.Context, collection servers = append(servers, address) } - if err := ms.deleteCollectionFrom(ctx, collectionName, servers); err != nil { - return err - } - ms.Topo.DeleteCollection(collectionName) - - return nil + return ms.deleteCollectionFrom(ctx, collection.Name, servers) } func (ms *MasterServer) doDeleteEcCollection(ctx context.Context, collectionName string) error { diff --git a/weed/server/master_grpc_server_collection_test.go b/weed/server/master_grpc_server_collection_test.go index 49a6719447..1e4e31cdb7 100644 --- a/weed/server/master_grpc_server_collection_test.go +++ b/weed/server/master_grpc_server_collection_test.go @@ -7,11 +7,15 @@ import ( "testing" "time" + "github.com/seaweedfs/raft" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb" + "github.com/seaweedfs/seaweedfs/weed/sequence" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/storage/super_block" "github.com/seaweedfs/seaweedfs/weed/topology" ) @@ -117,7 +121,7 @@ func TestDoDeleteNormalCollectionBoundsEachVolumeServerRPC(t *testing.T) { ms := newCollectionTestMaster(topo) done := make(chan error, 1) - go func() { done <- ms.doDeleteNormalCollection(context.Background(), collection) }() + go func() { done <- ms.deleteCollection(context.Background(), collection) }() call := awaitCall(t, stub, "bounded RPC") if call.budget <= 0 { @@ -131,10 +135,10 @@ func TestDoDeleteNormalCollectionBoundsEachVolumeServerRPC(t *testing.T) { select { case err := <-done: if err != nil { - t.Errorf("doDeleteNormalCollection returned %v, want nil once the volume server answers", err) + t.Errorf("deleteCollection returned %v, want nil once the volume server answers", err) } case <-time.After(15 * time.Second): - t.Fatal("doDeleteNormalCollection did not return after the volume server answered") + t.Fatal("deleteCollection did not return after the volume server answered") } } @@ -210,8 +214,8 @@ func TestDoDeleteNormalCollectionSendsOneRPCPerVolumeServer(t *testing.T) { } ms := newCollectionTestMaster(topo) - if err := ms.doDeleteNormalCollection(context.Background(), collection); err != nil { - t.Fatalf("doDeleteNormalCollection: %v", err) + if err := ms.deleteCollection(context.Background(), collection); err != nil { + t.Fatalf("deleteCollection: %v", err) } awaitCall(t, stub, "one RPC per server") @@ -243,8 +247,8 @@ func TestDoDeleteNormalCollectionKeepsGoingPastAFailingServer(t *testing.T) { }, healthyNode) ms := newCollectionTestMaster(topo) - if err := ms.doDeleteNormalCollection(context.Background(), collection); err == nil { - t.Fatal("doDeleteNormalCollection reported success while a server refused") + if err := ms.deleteCollection(context.Background(), collection); err == nil { + t.Fatal("deleteCollection reported success while a server refused") } awaitCall(t, failing, "failing server") @@ -285,3 +289,242 @@ func TestDeleteCollectionRunsTheEcPassWhenTheNormalPassFails(t *testing.T) { t.Error("the normal collection was dropped from the topology despite failing; nothing would retry it") } } + +// growingVolumeServer keeps the volumes AllocateVolume creates until +// DeleteCollection drops them. The holdAt-th allocation, counted from 1, waits +// for release before it creates its volume, and the holdDeleteAt-th +// DeleteCollection waits for deleteRelease before it drops any. +type growingVolumeServer struct { + volume_server_pb.UnimplementedVolumeServerServer + + holdAt int + held chan struct{} + release chan struct{} + + holdDeleteAt int + deleteHeld chan struct{} + deleteRelease chan struct{} + + mu sync.Mutex + allocations int + deletes int + volumes map[uint32]string +} + +func (s *growingVolumeServer) AllocateVolume(ctx context.Context, req *volume_server_pb.AllocateVolumeRequest) (*volume_server_pb.AllocateVolumeResponse, error) { + s.mu.Lock() + s.allocations++ + hold := s.allocations == s.holdAt + s.mu.Unlock() + if hold { + close(s.held) + <-s.release + } + s.mu.Lock() + s.volumes[req.VolumeId] = req.Collection + s.mu.Unlock() + return &volume_server_pb.AllocateVolumeResponse{}, nil +} + +func (s *growingVolumeServer) DeleteCollection(ctx context.Context, req *volume_server_pb.DeleteCollectionRequest) (*volume_server_pb.DeleteCollectionResponse, error) { + s.mu.Lock() + s.deletes++ + hold := s.deletes == s.holdDeleteAt + s.mu.Unlock() + if hold { + close(s.deleteHeld) + <-s.deleteRelease + } + s.mu.Lock() + defer s.mu.Unlock() + for vid, collection := range s.volumes { + if collection == req.Collection { + delete(s.volumes, vid) + } + } + return &volume_server_pb.DeleteCollectionResponse{}, nil +} + +// growthRaftServer answers as leader and applies the volume id bound growth asks for. +type growthRaftServer struct { + raft.Server + topo *topology.Topology +} + +func (growthRaftServer) State() string { return raft.Leader } + +func (s growthRaftServer) Do(c raft.Command) (interface{}, error) { + if command, ok := c.(*topology.MaxVolumeIdCommand); ok { + s.topo.UpAdjustMaxVolumeId(command.MaxVolumeId) + } + return nil, nil +} + +// A bucket's first write starts a grow of several volumes, and the bucket can be +// deleted before that grow is done. The volumes created after the delete +// recreated the collection and were never removed. +func TestDeleteCollectionStopsAGrowInFlight(t *testing.T) { + const collection = "bucket-g" + + stub := &growingVolumeServer{ + holdAt: 2, + held: make(chan struct{}), + release: make(chan struct{}), + volumes: make(map[uint32]string), + } + releaseOnce := sync.OnceFunc(func() { close(stub.release) }) + t.Cleanup(releaseOnce) + + topo := topology.NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false) + topo.RaftServer = growthRaftServer{topo: topo} + grpcPort := serveGrpc(t, func(s *grpc.Server) { + volume_server_pb.RegisterVolumeServerServer(s, stub) + }) + topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1"). + GetOrCreateDataNode("127.0.0.1", grpcPort-10000, grpcPort, "", "vs1", map[string]uint32{"": 10}) + ms := newCollectionTestMaster(topo) + + rp, _ := super_block.NewReplicaPlacementFromString("000") + option := &topology.VolumeGrowOption{ + Collection: collection, + ReplicaPlacement: rp, + Ttl: needle.EMPTY_TTL, + Version: uint32(needle.GetCurrentVersion()), + } + grown := make(chan struct{}) + go func() { + defer close(grown) + topology.NewDefaultVolumeGrowth().GrowByCountAndType(ms.grpcDialOption, 7, option, topo) + }() + + select { + case <-stub.held: + case <-time.After(15 * time.Second): + t.Fatal("the grow never reached its second volume") + } + deleted := make(chan error, 1) + go func() { deleted <- ms.deleteCollection(context.Background(), collection) }() + + // The delete waits for the volume being created rather than racing it. + time.Sleep(200 * time.Millisecond) + stub.mu.Lock() + early := stub.deletes + stub.mu.Unlock() + if early != 0 { + t.Error("the delete reached the volume server while the grow was still creating a volume") + } + releaseOnce() + + select { + case <-grown: + case <-time.After(15 * time.Second): + t.Fatal("the grow did not finish") + } + select { + case err := <-deleted: + if err != nil { + t.Fatalf("deleteCollection: %v", err) + } + case <-time.After(15 * time.Second): + t.Fatal("the delete did not finish") + } + + stub.mu.Lock() + left := len(stub.volumes) + stub.mu.Unlock() + if left != 0 { + t.Errorf("%d volumes of the deleted collection are left on the volume server", left) + } + if _, found := topo.FindCollection(collection); found { + t.Error("the grow recreated the deleted collection in the topology") + } +} + +// The EC pass deletes by name after the normal pass, on servers that can also +// hold normal volumes, so the name stays fenced until both passes are done: a +// write recreating the bucket in between would place a volume the EC pass then +// deletes. A second delete of the name waits, then finds nothing left to do. +func TestDeleteCollectionKeepsTheNameFencedThroughTheEcPass(t *testing.T) { + const collection = "bucket-h" + + stub := &growingVolumeServer{ + holdDeleteAt: 2, + deleteHeld: make(chan struct{}), + deleteRelease: make(chan struct{}), + volumes: map[uint32]string{1: collection}, + } + releaseOnce := sync.OnceFunc(func() { close(stub.deleteRelease) }) + t.Cleanup(releaseOnce) + + topo := topology.NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false) + topo.RaftServer = growthRaftServer{topo: topo} + grpcPort := serveGrpc(t, func(s *grpc.Server) { + volume_server_pb.RegisterVolumeServerServer(s, stub) + }) + dn := topo.GetOrCreateDataCenter("dc1").GetOrCreateRack("rack1"). + GetOrCreateDataNode("127.0.0.1", grpcPort-10000, grpcPort, "", "vs1", map[string]uint32{"": 10}) + topo.SyncDataNodeRegistration([]*master_pb.VolumeInformationMessage{ + {Id: 1, Collection: collection, Version: 3}, + }, dn) + topo.SyncDataNodeEcShards([]*master_pb.VolumeEcShardInformationMessage{ + {Id: 9, Collection: collection, EcIndexBits: 0x1f}, + }, dn) + ms := newCollectionTestMaster(topo) + + rp, _ := super_block.NewReplicaPlacementFromString("000") + grow := func() error { + _, err := topology.NewDefaultVolumeGrowth().GrowByCountAndType(ms.grpcDialOption, 1, &topology.VolumeGrowOption{ + Collection: collection, + ReplicaPlacement: rp, + Ttl: needle.EMPTY_TTL, + Version: uint32(needle.GetCurrentVersion()), + }, topo) + return err + } + + first := make(chan error, 1) + go func() { first <- ms.deleteCollection(context.Background(), collection) }() + select { + case <-stub.deleteHeld: + case <-time.After(15 * time.Second): + t.Fatal("the EC pass never reached the volume server") + } + + if err := grow(); err == nil { + t.Error("a grow under the name went ahead while the EC pass was deleting it") + } + second := make(chan error, 1) + go func() { second <- ms.deleteCollection(context.Background(), collection) }() + waitForLockWaiter(t, "(*Topology).FenceGrowth") + releaseOnce() + + for _, done := range []chan error{first, second} { + select { + case err := <-done: + if err != nil { + t.Fatalf("deleteCollection: %v", err) + } + case <-time.After(15 * time.Second): + t.Fatal("a delete did not finish") + } + } + + stub.mu.Lock() + allocations, deletes, left := stub.allocations, stub.deletes, len(stub.volumes) + stub.mu.Unlock() + if allocations != 0 { + t.Errorf("%d volumes were created under the name while it was being deleted", allocations) + } + if deletes != 2 { + t.Errorf("the volume server got %d DeleteCollection calls, want 2: the second delete came back after the first removed the collection", deletes) + } + if left != 0 { + t.Errorf("%d volumes of the deleted collection are left on the volume server", left) + } + if _, found := topo.FindCollection(collection); found { + t.Error("the collection is still in the topology after the delete") + } + if err := grow(); err != nil { + t.Errorf("a grow under the name failed once the delete was done: %v", err) + } +} diff --git a/weed/topology/collection.go b/weed/topology/collection.go index 254c951dc7..3875d09913 100644 --- a/weed/topology/collection.go +++ b/weed/topology/collection.go @@ -16,6 +16,7 @@ type Collection struct { replicationAsMin bool maxWritableVolumes int storageType2VolumeLayout *util.ConcurrentReadMap + growth growthFence } func NewCollection(name string, volumeSizeLimit uint64, replicationAsMin bool) *Collection { diff --git a/weed/topology/collection_growth.go b/weed/topology/collection_growth.go new file mode 100644 index 0000000000..670273df71 --- /dev/null +++ b/weed/topology/collection_growth.go @@ -0,0 +1,119 @@ +package topology + +import ( + "sync" + "sync/atomic" +) + +// growthFence keeps volume growth and assigns out of a collection being +// deleted. Growth holds lock shared while it creates one volume; a delete +// raises deleting and then takes lock, so the volume in flight has registered, +// and is found by the delete, before the delete lists the collection's servers. +// deleteLock runs one delete of the collection at a time, and deleted marks a +// collection a delete removed. +type growthFence struct { + lock sync.RWMutex + deleting atomic.Int32 + deleteLock sync.Mutex + deleted atomic.Bool +} + +// FenceGrowth stops assigns and volume growth in the collection, and returns +// once the volume growth is creating has registered. The returned func lets +// them back in, for a delete that failed and leaves the collection in place. +func (c *Collection) FenceGrowth() (unfence func()) { + c.growth.deleting.Add(1) + c.growth.lock.Lock() + c.growth.lock.Unlock() + return func() { + c.growth.deleting.Add(-1) + } +} + +// FenceGrowth fences the collection published under the name, an empty one for +// a name with EC shards only, so no assign or grow places a volume under the +// name while a delete runs. A collection unpublished for being empty before its +// fence went up is let go, and the one published since, where growth registers +// its volumes, is fenced instead. It then waits for a delete already running on +// the collection. Once another delete removed the collection it finds nothing, +// so a delete never reaches a collection recreated under the name after that. +// finish ends the delete: deleted unpublishes the collection, otherwise growth +// is let back in. +func (t *Topology) FenceGrowth(collectionName string) (c *Collection, finish func(deleted bool), found bool) { + var unfence func() + for { + c = t.getOrCreateCollection(collectionName) + unfence = c.FenceGrowth() + if published, stillFound := t.FindCollection(collectionName); stillFound && published == c { + break + } + unfence() + if c.growth.deleted.Load() { + return nil, nil, false + } + } + c.growth.deleteLock.Lock() + if published, stillFound := t.FindCollection(collectionName); !stillFound || published != c { + c.growth.deleteLock.Unlock() + unfence() + return nil, nil, false + } + return c, func(deleted bool) { + if deleted { + c.growth.deleted.Store(true) + t.DeleteCollection(collectionName) + } else { + unfence() + } + c.growth.deleteLock.Unlock() + }, true +} + +func (c *Collection) isDeleting() bool { + return c.growth.deleting.Load() > 0 +} + +func (c *Collection) unlockForGrowth() { + c.growth.lock.RUnlock() +} + +// lockForGrowth holds off a delete of the grow request's collection while +// growth creates one volume in it, and fails once a delete fenced it. A +// collection dropped only because its last layout emptied is followed to the +// one now published under its name, where the volume registers. +func (t *Topology) lockForGrowth(option *VolumeGrowOption) bool { + for { + c := option.collection + c.growth.lock.RLock() + if c.isDeleting() { + c.growth.lock.RUnlock() + return false + } + if published, found := t.FindCollection(c.Name); found && published == c { + return true + } + c.growth.lock.RUnlock() + option.collection = t.getOrCreateCollection(c.Name) + } +} + +// deleteEmptyCollection keeps a collection that growth or a delete holds +// published: the volume in flight registers by name, and must land where the +// delete lists the servers, not in a new collection under the same name. +func (t *Topology) deleteEmptyCollection(c *Collection) { + if !c.growth.lock.TryLock() { + return + } + defer c.growth.lock.Unlock() + if !c.isDeleting() { + t.DeleteCollection(c.Name) + } +} + +func (t *Topology) getOrCreateCollection(collectionName string) *Collection { + return t.collectionMap.Get(collectionName, func() interface{} { + c := NewCollection(collectionName, t.volumeSizeLimit, t.replicationAsMin) + c.maxWritableVolumes = t.maxWritableVolumes + return c + }).(*Collection) +} diff --git a/weed/topology/collection_growth_test.go b/weed/topology/collection_growth_test.go new file mode 100644 index 0000000000..a3fab9c937 --- /dev/null +++ b/weed/topology/collection_growth_test.go @@ -0,0 +1,381 @@ +package topology + +import ( + "runtime" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/sequence" + "github.com/seaweedfs/seaweedfs/weed/storage" + "github.com/seaweedfs/seaweedfs/weed/storage/needle" + "github.com/seaweedfs/seaweedfs/weed/storage/super_block" + "github.com/seaweedfs/seaweedfs/weed/storage/types" +) + +func newGrowthFenceTopology() (*Topology, *VolumeGrowOption) { + topo := NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false) + return topo, &VolumeGrowOption{Collection: "bucket", collection: topo.getOrCreateCollection("bucket")} +} + +func TestGrowthFenceWaitsForTheVolumeInFlight(t *testing.T) { + topo, option := newGrowthFenceTopology() + c := option.collection + + if !topo.lockForGrowth(option) { + t.Fatal("growth refused by a collection nothing is deleting") + } + fenced := make(chan func(), 1) + go func() { fenced <- c.FenceGrowth() }() + select { + case <-fenced: + t.Fatal("FenceGrowth returned while growth was still creating a volume") + case <-time.After(100 * time.Millisecond): + } + c.unlockForGrowth() + + var unfence func() + select { + case unfence = <-fenced: + case <-time.After(5 * time.Second): + t.Fatal("FenceGrowth did not return after the volume in flight finished") + } + if topo.lockForGrowth(option) { + t.Fatal("growth entered a collection being deleted") + } + + unfence() + if !topo.lockForGrowth(option) { + t.Fatal("growth still refused after a failed delete lifted the fence") + } + c.unlockForGrowth() +} + +func TestGrowthStaysOutOfARecreatedCollection(t *testing.T) { + topo, option := newGrowthFenceTopology() + + option.collection.FenceGrowth() + topo.DeleteCollection("bucket") + topo.getOrCreateCollection("bucket") + + if topo.lockForGrowth(option) { + t.Fatal("growth that started before the delete entered the collection recreated under the same name") + } +} + +func TestGrowthFollowsACollectionDroppedForBeingEmpty(t *testing.T) { + topo, option := newGrowthFenceTopology() + + topo.DeleteCollection("bucket") + + if !topo.lockForGrowth(option) { + t.Fatal("growth refused after its collection was dropped without a delete") + } + defer option.collection.unlockForGrowth() + if published, _ := topo.FindCollection("bucket"); published != option.collection { + t.Error("growth did not follow the collection now published under its name") + } +} + +func TestEmptiedCollectionStaysPublishedWhileHeld(t *testing.T) { + topo, option := newGrowthFenceTopology() + c := option.collection + rp, _ := super_block.NewReplicaPlacementFromString("000") + dn := NewDataNode("dn1") + emptyLayout := func() { + topo.UnRegisterVolumeLayout(storage.VolumeInfo{Id: 1, Collection: "bucket", ReplicaPlacement: rp, Ttl: needle.EMPTY_TTL}, dn) + } + + if !topo.lockForGrowth(option) { + t.Fatal("growth refused by a collection nothing is deleting") + } + emptyLayout() + if published, _ := topo.FindCollection("bucket"); published != c { + t.Error("collection dropped while growth was creating a volume in it") + } + c.unlockForGrowth() + + unfence := c.FenceGrowth() + emptyLayout() + if published, _ := topo.FindCollection("bucket"); published != c { + t.Error("collection being deleted dropped before the delete listed its servers") + } + unfence() + + emptyLayout() + if _, found := topo.FindCollection("bucket"); found { + t.Error("idle empty collection still published") + } +} + +// An emptied-layout cleanup that passed its fence check unpublishes the +// collection while the delete waits to fence it, and growth then publishes a +// new one under the name. The delete must fence and list that one. +func TestDeleteFencesTheCollectionPublishedSinceItsLookup(t *testing.T) { + topo, option := newGrowthFenceTopology() + c := option.collection + + c.growth.lock.Lock() + type result struct { + c *Collection + finish func(bool) + } + fenced := make(chan result, 1) + go func() { + fc, finish, _ := topo.FenceGrowth("bucket") + fenced <- result{fc, finish} + }() + for deadline := time.Now().Add(5 * time.Second); !c.isDeleting(); { + if time.Now().After(deadline) { + t.Fatal("FenceGrowth did not mark the collection as being deleted") + } + time.Sleep(time.Millisecond) + } + topo.DeleteCollection("bucket") + replacement := topo.getOrCreateCollection("bucket") + c.growth.lock.Unlock() + + var got result + select { + case got = <-fenced: + case <-time.After(5 * time.Second): + t.Fatal("FenceGrowth did not return") + } + if got.c != replacement { + t.Fatal("the delete fenced a collection no longer published under its name") + } + if !replacement.isDeleting() || c.isDeleting() { + t.Error("the fence is not on the published collection alone") + } + got.finish(false) +} + +// A second delete of the name waits for the one running. Once that one removed +// the collection, the second finds nothing, and leaves alone a collection a +// write recreated under the name in between. +func TestOverlappingDeletesRemoveOnlyTheFencedCollection(t *testing.T) { + topo, option := newGrowthFenceTopology() + c := option.collection + + _, finishFirst, found := topo.FenceGrowth("bucket") + if !found { + t.Fatal("first delete found no collection") + } + type result struct { + c *Collection + found bool + } + second := make(chan result, 1) + go func() { + fc, _, found := topo.FenceGrowth("bucket") + second <- result{fc, found} + }() + waitForLockWaiter(t, "(*Topology).FenceGrowth") + + finishFirst(true) + replacement := topo.getOrCreateCollection("bucket") + + select { + case got := <-second: + if got.found || got.c != nil { + t.Fatal("second delete went on to the collection recreated under the name") + } + case <-time.After(5 * time.Second): + t.Fatal("second delete did not return") + } + if replacement.isDeleting() { + t.Error("the recreated collection was fenced") + } + if !c.isDeleting() { + t.Error("the deleted collection let growth back in") + } +} + +// A delete waiting on one that failed takes over the collection left in place. +func TestDeleteAfterAFailedOneTakesOverTheCollection(t *testing.T) { + topo, option := newGrowthFenceTopology() + c := option.collection + + _, finishFirst, _ := topo.FenceGrowth("bucket") + type result struct { + c *Collection + finish func(bool) + } + second := make(chan result, 1) + go func() { + fc, finish, _ := topo.FenceGrowth("bucket") + second <- result{fc, finish} + }() + waitForLockWaiter(t, "(*Topology).FenceGrowth") + finishFirst(false) + + var got result + select { + case got = <-second: + case <-time.After(5 * time.Second): + t.Fatal("second delete did not return") + } + if got.c != c || !c.isDeleting() { + t.Fatal("second delete does not hold the collection the failed one left") + } + got.finish(false) + if c.isDeleting() { + t.Error("growth stayed fenced after both deletes failed") + } +} + +// A delete that read the collection but had not checked its publication yet +// when another delete removed it must stop there, not go on to the collection a +// write recreated under the name since. +func TestDeleteFindsNothingOnceAnotherDeleteRemovedTheCollection(t *testing.T) { + topo, option := newGrowthFenceTopology() + c := option.collection + + _, finishFirst, _ := topo.FenceGrowth("bucket") + c.growth.lock.RLock() + type result struct { + c *Collection + found bool + } + second := make(chan result, 1) + go func() { + fc, _, found := topo.FenceGrowth("bucket") + second <- result{fc, found} + }() + for deadline := time.Now().Add(5 * time.Second); c.growth.deleting.Load() < 2; { + if time.Now().After(deadline) { + t.Fatal("second delete never fenced the collection") + } + time.Sleep(time.Millisecond) + } + finishFirst(true) + replacement := topo.getOrCreateCollection("bucket") + c.growth.lock.RUnlock() + + select { + case got := <-second: + if got.found || got.c != nil { + t.Fatal("second delete went on to the collection recreated under the name") + } + case <-time.After(5 * time.Second): + t.Fatal("second delete did not return") + } + if replacement.isDeleting() { + t.Error("the recreated collection was fenced") + } +} + +// A name with EC shards only has no collection to fence. The delete fences an +// empty one, which an assign under the name finds and is refused by, and which +// is gone again once the delete is done. +func TestDeleteFencesANameWithoutACollection(t *testing.T) { + topo := NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false) + + c, finish, found := topo.FenceGrowth("ec-only") + if !found { + t.Fatal("the delete fenced nothing for a name with no collection") + } + if published, _ := topo.FindCollection("ec-only"); published != c || !c.isDeleting() { + t.Fatal("the name is not fenced while the delete runs") + } + if names := topo.ListCollections(true, false); len(names) != 0 { + t.Errorf("ListCollections = %v, want no collection for the fence", names) + } + finish(true) + if _, found := topo.FindCollection("ec-only"); found { + t.Error("the fence outlived the delete") + } +} + +// waitForLockWaiter waits until a goroutine running fn is blocked on a mutex. +func waitForLockWaiter(t *testing.T, fn string) { + t.Helper() + buf := make([]byte, 1<<20) + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + n := runtime.Stack(buf, true) + if n == len(buf) { + buf = make([]byte, 2*len(buf)) + continue + } + for _, g := range strings.Split(string(buf[:n]), "\n\n") { + if strings.Contains(g, "sync.(*Mutex).lockSlow") && strings.Contains(g, fn) { + return + } + } + time.Sleep(time.Millisecond) + } + t.Fatalf("%s never waited on a mutex", fn) +} + +func TestAssignStaysOutOfACollectionBeingDeleted(t *testing.T) { + layout := ` +{ + "dc1":{ + "rack1":{ + "server1":{ + "volumes":[ + {"id":1, "size":4096, "fileCount":1, "replication":"000"} + ], + "limit":10 + } + } + } +} +` + topo, vl := setupPickTest(t, layout, 30*1024*1024) + rp, _ := super_block.NewReplicaPlacementFromString("000") + option := &VolumeGrowOption{ReplicaPlacement: rp} + c, _ := topo.FindCollection("") + + growth := &VolumeGrowOption{collection: c} + if !topo.lockForGrowth(growth) { + t.Fatal("growth refused by a collection nothing is deleting") + } + fenced := make(chan func(), 1) + go func() { fenced <- c.FenceGrowth() }() + for deadline := time.Now().Add(5 * time.Second); !c.isDeleting(); { + if time.Now().After(deadline) { + t.Fatal("FenceGrowth did not mark the collection as being deleted") + } + time.Sleep(time.Millisecond) + } + if _, _, _, _, err := topo.PickForWrite(1, option, vl, 0); err == nil { + t.Error("assign picked a volume while the delete waited for the volume in flight") + } + c.unlockForGrowth() + unfence := <-fenced + if _, _, _, _, err := topo.PickForWrite(1, option, vl, 0); err == nil { + t.Error("assign picked a volume of a fenced collection") + } + + unfence() + if _, _, _, _, err := topo.PickForWrite(1, option, vl, 0); err != nil { + t.Errorf("assign still refused after a failed delete lifted the fence: %v", err) + } +} + +func TestAssignQueuesNoGrowthForACollectionBeingDeleted(t *testing.T) { + topo, option := newGrowthFenceTopology() + option.ReplicaPlacement, _ = super_block.NewReplicaPlacementFromString("000") + option.Ttl = needle.EMPTY_TTL + vl := topo.GetVolumeLayout("bucket", option.ReplicaPlacement, option.Ttl, types.HardDriveType) + + option.collection.FenceGrowth() + if _, _, _, shouldGrow, err := topo.PickForWrite(1, option, vl, 0); err == nil || shouldGrow { + t.Errorf("pick from an empty layout of a collection being deleted: shouldGrow %v, err %v", shouldGrow, err) + } +} + +func TestFailedGrowListsNoCollection(t *testing.T) { + topo := NewTopology("test", sequence.NewMemorySequencer(), 32*1024, 5, false) + rp, _ := super_block.NewReplicaPlacementFromString("000") + option := &VolumeGrowOption{Collection: "archive", ReplicaPlacement: rp, DiskType: types.HardDriveType} + + if _, err := NewDefaultVolumeGrowth().GrowByCountAndType(nil, 1, option, topo); err == nil { + t.Fatal("grow succeeded on a topology with no volume servers") + } + if got := topo.ListCollections(true, false); len(got) != 0 { + t.Errorf("a grow that created nothing left collections %v listed", got) + } +} diff --git a/weed/topology/topology.go b/weed/topology/topology.go index 47efeac322..73107fcae3 100644 --- a/weed/topology/topology.go +++ b/weed/topology/topology.go @@ -707,6 +707,11 @@ const DefaultNeedleSizeEstimate uint64 = 1024 * 1024 // 1 MB func (t *Topology) PickForWrite(requestedCount uint64, option *VolumeGrowOption, volumeLayout *VolumeLayout, expectedDataSize uint64) (fileId string, count uint64, volumeLocationList *VolumeLocationList, shouldGrow bool, err error) { var vid needle.VolumeId vid, count, volumeLocationList, shouldGrow, err = volumeLayout.PickForWrite(requestedCount, option) + // Its volumes are about to be deleted: a write placed there is lost, and a + // grow queued for it would recreate the collection after the delete. + if c, found := t.FindCollection(option.Collection); found && c.isDeleting() { + return "", 0, nil, false, fmt.Errorf("collection %q is being deleted", option.Collection) + } if err != nil { return "", 0, nil, shouldGrow, fmt.Errorf("failed to find writable volumes for collection:%s replication:%s ttl:%s error: %v", option.Collection, option.ReplicaPlacement.String(), option.Ttl.String(), err) } @@ -814,7 +819,11 @@ func (t *Topology) ListCollections(includeNormalVolumes, includeEcVolumes bool) if includeNormalVolumes { for _, c := range t.collectionMap.Items() { - found[c.(*Collection).Name] = true + // A grow request publishes its collection before its first volume + // registers, and one that fails leaves it empty. + if len(c.(*Collection).GetAllVolumeLayouts()) > 0 { + found[c.(*Collection).Name] = true + } } } @@ -870,7 +879,7 @@ func (t *Topology) DeleteLayout(collectionName string, rp *super_block.ReplicaPl } collection.DeleteVolumeLayout(rp, ttl, diskType) if len(collection.storageType2VolumeLayout.Items()) == 0 { - t.DeleteCollection(collectionName) + t.deleteEmptyCollection(collection) } } diff --git a/weed/topology/volume_growth.go b/weed/topology/volume_growth.go index ff1c284529..ec3bb460f6 100644 --- a/weed/topology/volume_growth.go +++ b/weed/topology/volume_growth.go @@ -76,6 +76,9 @@ type VolumeGrowOption struct { // refused holds the data nodes that refused an allocation earlier in the // same grow request; they offer no free slots for the rest of it. refused map[*DataNode]bool + // collection is the collection the grow request started in, so a delete + // of it stops the request instead of the request recreating it. + collection *Collection Collection string `json:"collection,omitempty"` ReplicaPlacement *super_block.ReplicaPlacement `json:"replication,omitempty"` @@ -150,6 +153,9 @@ func (vg *VolumeGrowth) AutomaticGrowByType(option *VolumeGrowOption, grpcDialOp return result, err } func (vg *VolumeGrowth) GrowByCountAndType(grpcDialOption grpc.DialOption, targetCount uint32, option *VolumeGrowOption, topo *Topology) (result []*master_pb.VolumeLocation, err error) { + // Taken before waiting for the lock: a delete that lands while this request + // waits behind another grow stops it as well. + collection := topo.getOrCreateCollection(option.Collection) vg.accessLock.Lock() defer vg.accessLock.Unlock() @@ -160,6 +166,7 @@ func (vg *VolumeGrowth) GrowByCountAndType(grpcDialOption grpc.DialOption, targe placed := *option placed.layoutLoad = nil placed.refused = nil + placed.collection = collection option = &placed retries := 0 for i := uint32(0); i < targetCount; i++ { @@ -205,6 +212,10 @@ func (vg *VolumeGrowth) findAndGrow(grpcDialOption grpc.DialOption, topo *Topolo glog.V(0).Infof("wait for volume servers to join back") time.Sleep(topo.WarmupDuration() / WarmupPulseMultiplier / 2) } + if !topo.lockForGrowth(option) { + return nil, fmt.Errorf("collection %q is being deleted", option.Collection) + } + defer option.collection.unlockForGrowth() if option.layoutLoad == nil { option.layoutLoad = option.withLayoutLoad(topo).layoutLoad }