diff --git a/weed/mq/broker/broker_partition_fence.go b/weed/mq/broker/broker_partition_fence.go index a845df87fa..305107d56a 100644 --- a/weed/mq/broker/broker_partition_fence.go +++ b/weed/mq/broker/broker_partition_fence.go @@ -107,19 +107,20 @@ func (b *MessageQueueBroker) takePartitionFence(ctx context.Context, t topic.Top // retireStaleLeader retires p if it lost its fence or holds it for an older // leadership than epoch, so the partition reloads from its files under a new -// fence. The caller holds accessLock; it is released while p's last flush lands, -// because the flush takes it, so the caller must look the partition up again. +// fence. p stays registered until its last flush lands, so a concurrent loader +// finds it and waits for the same flush rather than taking the fence first. +// The caller holds accessLock; it is released during the wait, because the flush +// takes it, so the caller must look the partition up again. func (b *MessageQueueBroker) retireStaleLeader(t topic.Topic, p *topic.LocalPartition, epoch int64) bool { if p == nil || p.Fence == nil || (!p.Fence.IsLost() && p.Fence.Epoch >= epoch) { return false } - if !b.localTopicManager.RemoveLocalPartition(t, p) { - return false - } + p.Shutdown() b.accessLock.Unlock() p.LogBuffer.WaitForShutdown() b.accessLock.Lock() - return true + // once the broker is stopping, its Shutdown retires p instead + return b.localTopicManager.RemoveLocalPartition(t, p) || b.localTopicManager.GetLocalPartition(t, p.Partition) != p } // fenceTokenCondition holds while the fence entry is still the one written with token. diff --git a/weed/mq/broker/broker_partition_fence_test.go b/weed/mq/broker/broker_partition_fence_test.go index 00da38f5e5..481302ac0c 100644 --- a/weed/mq/broker/broker_partition_fence_test.go +++ b/weed/mq/broker/broker_partition_fence_test.go @@ -49,6 +49,8 @@ type fencingFiler struct { beforeApply func() volume *httptest.Server uploads atomic.Int32 + // uploads wait for it while set + uploadGate chan struct{} } func (f *fencingFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { @@ -145,6 +147,9 @@ func newFencingFiler(t *testing.T) (*fencingFiler, *MessageQueueBroker) { f := &fencingFiler{entries: map[string]*filer_pb.Entry{}, outcome: map[string]*filer_pb.ObjectTransactionResponse{}} f.volume = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.uploads.Add(1) + if f.uploadGate != nil { + <-f.uploadGate + } _, _ = io.Copy(io.Discard, r.Body) w.WriteHeader(http.StatusCreated) _, _ = io.WriteString(w, `{"size":4}`) @@ -384,3 +389,52 @@ func TestLookupReloadsAnOlderEpoch(t *testing.T) { t.Errorf("serving fence %+v", current.Fence) } } + +// Two loaders reloading a stale copy at once both wait for its last flush, so +// neither takes the new fence while that flush is pending. +func TestConcurrentReloadsWaitForTheLastFlush(t *testing.T) { + f, b := newFencingFiler(t) + old, _ := newFencedPartition(t, b) + if err := old.Publish(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil { + t.Fatal(err) + } + f.uploadGate = make(chan struct{}) + + var wg sync.WaitGroup + for range 2 { + wg.Add(1) + go func() { + defer wg.Done() + if _, err := b.AssignTopicPartitions(context.Background(), &mq_pb.AssignTopicPartitionsRequest{ + Topic: fenceTestTopic.ToPbTopic(), + BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{Partition: fenceTestPartition.ToPbPartition(), Epoch: 2}}, + }); err != nil { + t.Error(err) + } + }() + } + for f.uploads.Load() == 0 { + time.Sleep(time.Millisecond) + } + time.Sleep(50 * time.Millisecond) + close(f.uploadGate) + wg.Wait() + + current := b.localTopicManager.GetLocalPartition(fenceTestTopic, fenceTestPartition) + t.Cleanup(current.LogBuffer.ShutdownLogBuffer) + if current == old || current.Fence.Epoch != 2 { + t.Fatalf("serving fence %+v", current.Fence) + } + var names []string + for _, txn := range f.transactions() { + names = append(names, txn.Mutations[0].Entry.Name) + } + if len(names) != 3 || names[0] != topic.PartitionFenceName || !strings.HasPrefix(names[1], "20") || names[2] != topic.PartitionFenceName { + t.Errorf("transactions %v, want the old copy's last window before one new fence", names) + } + for _, txn := range f.transactions() { + if f.outcome[txn.RequestId].GetErrorCode() == filer_pb.FilerError_PRECONDITION_FAILED { + t.Errorf("%s was refused", txn.Mutations[0].Entry.Name) + } + } +}