diff --git a/weed/mq/README.md b/weed/mq/README.md index 6a641c009d..a3d1a36443 100644 --- a/weed/mq/README.md +++ b/weed/mq/README.md @@ -53,12 +53,12 @@ The client will write the messages for this segment to the selected brokers. The broker leader does not contain any state. If it fails, the masters will select a different broker. -For a segment, if any one of the selected brokers is down, the remaining brokers should try to write received messages -to the filer, and close the segment to the clients. +A partition's files are written only by the broker holding the partition's fence, so a broker that lost its +leadership cannot add to them. When that broker fails, the partition is assigned to another broker, which takes the +fence at a new epoch and continues from the files. -Then the clients should start a new segment. The masters should assign other healthy brokers to handle the new segment. - -So any brokers can go down without losing data. +A follower keeps the messages it receives in memory and does not write them. Until followers can take over a failed +broker's partition, messages it acknowledged but had not flushed yet are lost when it fails. ## Auto Split or Merge diff --git a/weed/mq/broker/broker_grpc_assign.go b/weed/mq/broker/broker_grpc_assign.go index 45977496bf..f2b5b703c0 100644 --- a/weed/mq/broker/broker_grpc_assign.go +++ b/weed/mq/broker/broker_grpc_assign.go @@ -6,7 +6,6 @@ import ( "sync" "github.com/seaweedfs/seaweedfs/weed/glog" - "github.com/seaweedfs/seaweedfs/weed/mq/logstore" "github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer" "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/pb" @@ -27,23 +26,28 @@ func (b *MessageQueueBroker) AssignTopicPartitions(c context.Context, request *m b.accessLock.Lock() if request.IsDraining { // TODO drain existing topic partition subscriptions - b.localTopicManager.RemoveLocalPartition(t, partition) + b.localTopicManager.RemoveLocalPartition(t, b.localTopicManager.GetLocalPartition(t, partition)) } else { - var localPartition *topic.LocalPartition - if localPartition = b.localTopicManager.GetLocalPartition(t, partition); localPartition == nil { - localPartition = topic.NewLocalPartition(partition, b.option.LogFlushInterval, b.genLogFlushFunc(t, partition), logstore.GenMergedReadFunc(b, t, partition)) - - // Initialize offset from existing data to ensure continuity on restart - b.initializePartitionOffsetFromExistingData(localPartition, t, partition) - + existing := b.localTopicManager.GetLocalPartition(t, partition) + for b.retireStaleLeader(t, existing, assignment.Epoch) { + existing = b.localTopicManager.GetLocalPartition(t, partition) + } + // checked after the reload, which can wait out a Shutdown that starts meanwhile + if b.localTopicManager.IsStopping() { + b.accessLock.Unlock() + return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress()) + } + if existing == nil { + localPartition, genErr := b.newLeaderPartition(t, partition, assignment.Epoch) + if genErr != nil { + b.accessLock.Unlock() + return nil, genErr + } if !b.localTopicManager.AddLocalPartition(t, localPartition) { localPartition.Shutdown() b.accessLock.Unlock() return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress()) } - } else if b.localTopicManager.IsStopping() { - b.accessLock.Unlock() - return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress()) } } b.accessLock.Unlock() @@ -82,6 +86,7 @@ func (b *MessageQueueBroker) assignTopicPartitionsToBrokers(ctx context.Context, BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{ { Partition: bpa.Partition, + Epoch: bpa.Epoch, }, }, IsLeader: true, diff --git a/weed/mq/broker/broker_grpc_pub.go b/weed/mq/broker/broker_grpc_pub.go index 6e9bc07f3e..1afa21df7f 100644 --- a/weed/mq/broker/broker_grpc_pub.go +++ b/weed/mq/broker/broker_grpc_pub.go @@ -2,6 +2,7 @@ package broker import ( "context" + "errors" "fmt" "io" "math/rand/v2" @@ -71,6 +72,10 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis // get or generate a local partition t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition) localTopicPartition, getOrGenErr := b.GetOrGenerateLocalPartition(t, p) + if errors.Is(getOrGenErr, errFenceLost) { + response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, getOrGenErr.Error()) + return stream.Send(response) + } if getOrGenErr != nil { response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorTopicNotFound, fmt.Sprintf("topic %v not found: %v", t, getOrGenErr)) glog.Errorf("topic %v not found: %v", t, getOrGenErr) @@ -81,6 +86,10 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is not assigned to this broker", t, p)) return stream.Send(response) } + if localTopicPartition.IsFenced() { + response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is fenced by another broker", t, p)) + return stream.Send(response) + } // connect to follower brokers if followerErr := localTopicPartition.MaybeConnectToFollowers(initMessage, b.grpcDialOption); followerErr != nil { @@ -136,7 +145,7 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis localTopicPartition.Publishers.RemovePublisher(clientName) // Use topic-aware shutdown logic to prevent aggressive removal of system topics if localTopicPartition.MaybeShutdownLocalPartitionForTopic(t.Name) { - b.localTopicManager.RemoveLocalPartition(t, p) + b.localTopicManager.RemoveLocalPartition(t, localTopicPartition) glog.V(0).Infof("Removed local topic %v partition %v", initMessage.Topic, initMessage.Partition) } }() @@ -184,6 +193,11 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis // The control message should still be sent to the follower // to avoid timing issue when ack messages. + if localTopicPartition.IsFenced() { + response.ErrorCode, response.Error = CreateBrokerError(BrokerErrorNotLeaderOrFollower, fmt.Sprintf("topic %v partition %v is fenced by another broker", t, p)) + return stream.Send(response) + } + // Send to the local partition with offset assignment t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition) diff --git a/weed/mq/broker/broker_grpc_pub_follow.go b/weed/mq/broker/broker_grpc_pub_follow.go index c85c47e3bf..5ce9dd8323 100644 --- a/weed/mq/broker/broker_grpc_pub_follow.go +++ b/weed/mq/broker/broker_grpc_pub_follow.go @@ -1,6 +1,7 @@ package broker import ( + "context" "fmt" "io" "time" @@ -115,15 +116,12 @@ func (b *MessageQueueBroker) PublishFollowMe(stream mq_pb.SeaweedMessaging_Publi // TODO trim data earlier than lastFlushTsNs - targetFile := fmt.Sprintf("%s/%s", partitionDir, startTime.Format(topic.TIME_FORMAT)) + targetFile := fmt.Sprintf("%s/%s", partitionDir, topic.LogFileName(startTime, 0)) - for { - if err := b.appendToFile(targetFile, mem.buf); err != nil { - glog.V(0).Infof("metadata log write failed %s: %v", targetFile, err) - time.Sleep(737 * time.Millisecond) - } else { - break - } + // A follower holds no fence, so the fenced writer refuses its copy. + if err := b.writeLogFile(context.Background(), nil, targetFile, mem.buf); err != nil { + glog.Warningf("dropping remaining data at %v %v size %d: %v", t, p, len(mem.buf), err) + continue } glog.V(0).Infof("flushed remaining data at %v to %s size %d", mem.stopTime.UnixNano(), targetFile, len(mem.buf)) diff --git a/weed/mq/broker/broker_grpc_sub.go b/weed/mq/broker/broker_grpc_sub.go index 51a74c6a9d..b388d083c7 100644 --- a/weed/mq/broker/broker_grpc_sub.go +++ b/weed/mq/broker/broker_grpc_sub.go @@ -68,7 +68,7 @@ func (b *MessageQueueBroker) SubscribeMessage(stream mq_pb.SeaweedMessaging_Subs glog.V(0).Infof("Subscriber %s on %v %v disconnected, sent %d", clientName, t, partition, counter) // Use topic-aware shutdown logic to prevent aggressive removal of system topics if localTopicPartition.MaybeShutdownLocalPartitionForTopic(t.Name) { - b.localTopicManager.RemoveLocalPartition(t, partition) + b.localTopicManager.RemoveLocalPartition(t, localTopicPartition) } }() diff --git a/weed/mq/broker/broker_partition_fence.go b/weed/mq/broker/broker_partition_fence.go new file mode 100644 index 0000000000..305107d56a --- /dev/null +++ b/weed/mq/broker/broker_partition_fence.go @@ -0,0 +1,156 @@ +package broker + +import ( + "context" + "errors" + "fmt" + "os" + "strconv" + "time" + + "github.com/google/uuid" + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/mq" + "github.com/seaweedfs/seaweedfs/weed/mq/logstore" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +var ( + errFenceLost = errors.New("partition fence is held by another broker") + // the filer recorded this failure under the request id, so a retry of that id replays it + errTransactionFailed = errors.New("transaction failed") +) + +// fenceTakeTimeout bounds the filer calls a fence take makes while holding accessLock. +var fenceTakeTimeout = 10 * time.Second + +// newLeaderPartition takes the partition's fence for epoch before anything reads +// the partition's files, so a previous leader can no longer add to them. +func (b *MessageQueueBroker) newLeaderPartition(t topic.Topic, partition topic.Partition, epoch int64) (*topic.LocalPartition, error) { + ctx, cancel := context.WithTimeout(context.Background(), fenceTakeTimeout) + defer cancel() + fence, err := b.takePartitionFence(ctx, t, partition, epoch) + if err != nil { + return nil, fmt.Errorf("take fence of %s %s at epoch %d: %w", t, partition, epoch, err) + } + localPartition := topic.NewLocalPartition(partition, b.option.LogFlushInterval, b.genLogFlushFunc(t, partition, fence), logstore.GenMergedReadFunc(b, t, partition)) + localPartition.Fence = fence + b.initializePartitionOffsetFromExistingData(localPartition, t, partition) + return localPartition, nil +} + +func fenceEpoch(entry *filer_pb.Entry) (int64, error) { + value, found := entry.Extended[mq.ExtendedAttrFenceEpoch] + if !found { + return 0, nil + } + return strconv.ParseInt(string(value), 10, 64) +} + +func (b *MessageQueueBroker) takePartitionFence(ctx context.Context, t topic.Topic, partition topic.Partition, epoch int64) (*topic.PartitionFence, error) { + fencePath := util.FullPath(topic.PartitionFencePath(t, partition)) + dir, name := fencePath.DirAndName() + self := string(b.option.BrokerAddress()) + + current, _, _, err := filer_pb.GetEntry(ctx, b, fencePath) + if err != nil && !errors.Is(err, filer_pb.ErrNotFound) { + return nil, err + } + condition := &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS} + if current != nil { + storedEpoch, parseErr := fenceEpoch(current) + if parseErr != nil { + return nil, fmt.Errorf("fence %s epoch: %w", fencePath, parseErr) + } + if storedEpoch > epoch { + return nil, fmt.Errorf("fence %s is at epoch %d held by %s: %w", fencePath, storedEpoch, current.Extended[mq.ExtendedAttrFenceWriter], errFenceLost) + } + if string(current.Extended[mq.ExtendedAttrFenceSealed]) == "true" { + return nil, fmt.Errorf("fence %s is sealed", fencePath) + } + condition = &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: current} + if token := current.Extended[s3_constants.ExtETagKey]; len(token) > 0 { + condition = fenceTokenCondition(string(token)) + } + } + + // The token is the fence entry's etag, so writes can require it without reading + // the entry back through a filer that may not have caught up with the owner. + token := uuid.NewString() + now := time.Now().Unix() + fenceEntry := &filer_pb.Entry{ + Name: name, + Attributes: &filer_pb.FuseAttributes{ + Crtime: now, + Mtime: now, + FileMode: uint32(os.FileMode(0644)), + }, + Extended: map[string][]byte{ + mq.ExtendedAttrFenceWriter: []byte(self), + mq.ExtendedAttrFenceEpoch: []byte(strconv.FormatInt(epoch, 10)), + s3_constants.ExtETagKey: []byte(token), + }, + } + if err := b.fencedTransaction(ctx, string(fencePath), condition, uuid.NewString(), &filer_pb.ObjectMutation{ + Type: filer_pb.ObjectMutation_PUT, + Directory: dir, + Entry: fenceEntry, + }); err != nil { + return nil, err + } + glog.V(0).Infof("broker %s took fence %s at epoch %d", self, fencePath, epoch) + return &topic.PartitionFence{Path: string(fencePath), Epoch: epoch, Token: token}, nil +} + +// 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. 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 + } + p.Shutdown() + b.accessLock.Unlock() + p.LogBuffer.WaitForShutdown() + b.accessLock.Lock() + // 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. +func fenceTokenCondition(token string) *filer_pb.WriteCondition_Clause { + return &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ETAG_MATCH, Etags: []string{token}} +} + +// fencedTransaction applies mutation on the filer owning the fence while condition +// holds on the fence entry; a failed condition is errFenceLost. +func (b *MessageQueueBroker) fencedTransaction(ctx context.Context, fencePath string, condition *filer_pb.WriteCondition_Clause, requestId string, mutation *filer_pb.ObjectMutation) error { + var resp *filer_pb.ObjectTransactionResponse + err := b.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) (err error) { + resp, err = client.ObjectTransaction(ctx, &filer_pb.ObjectTransactionRequest{ + LockKey: fencePath, + RouteKey: s3_constants.ObjectWriteRouteKeyPrefix + fencePath, + ConditionKey: fencePath, + Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{condition}}, + Mutations: []*filer_pb.ObjectMutation{mutation}, + RequestId: requestId, + }) + return err + }) + if err != nil { + return err + } + if resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED { + return fmt.Errorf("%s: %w", fencePath, errFenceLost) + } + if resp.Error != "" { + return fmt.Errorf("transaction on %s: %s: %w", fencePath, resp.Error, errTransactionFailed) + } + return nil +} diff --git a/weed/mq/broker/broker_partition_fence_test.go b/weed/mq/broker/broker_partition_fence_test.go new file mode 100644 index 0000000000..b087df4b4b --- /dev/null +++ b/weed/mq/broker/broker_partition_fence_test.go @@ -0,0 +1,446 @@ +package broker + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/filer_client" + "github.com/seaweedfs/seaweedfs/weed/mq" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/mq_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// fencingFiler keeps entries in memory and applies ObjectTransaction the way the +// filer does: replay by request id, evaluate the condition, then PUT. +type fencingFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + mu sync.Mutex + entries map[string]*filer_pb.Entry + txns []*filer_pb.ObjectTransactionRequest + outcome map[string]*filer_pb.ObjectTransactionResponse + // applies the next transactions but answers with an error, like a lost response + dropResponses int + // records a mutation failure for the next transactions, as a store error does + failMutations int + // lookups answer from these entries, as a filer that has not caught up with the owner does + lagging map[string]*filer_pb.Entry + // lookups wait for their caller to give up, as a stalled filer does + stalled bool + // runs under the lock before a transaction applies, to interleave another writer + 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) { + f.mu.Lock() + if f.stalled { + f.mu.Unlock() + <-ctx.Done() + return nil, ctx.Err() + } + defer f.mu.Unlock() + entries := f.entries + if f.lagging != nil { + entries = f.lagging + } + entry, found := entries[string(util.NewFullPath(req.Directory, req.Name))] + if !found { + return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error()) + } + return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil +} + +func (f *fencingFiler) ObjectTransaction(_ context.Context, req *filer_pb.ObjectTransactionRequest) (*filer_pb.ObjectTransactionResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.txns = append(f.txns, proto.Clone(req).(*filer_pb.ObjectTransactionRequest)) + resp, replayed := f.outcome[req.RequestId] + if !replayed { + if f.beforeApply != nil { + f.beforeApply() + } + if f.failMutations > 0 { + f.failMutations-- + resp = &filer_pb.ObjectTransactionResponse{Error: "mutation 0: store unavailable"} + } else { + resp = f.apply(req) + } + f.outcome[req.RequestId] = resp + } + if f.dropResponses > 0 { + f.dropResponses-- + return nil, status.Error(codes.Unavailable, "response lost") + } + return resp, nil +} + +func (f *fencingFiler) apply(req *filer_pb.ObjectTransactionRequest) *filer_pb.ObjectTransactionResponse { + current := f.entries[req.ConditionKey] + for _, clause := range req.Condition.GetClauses() { + var holds bool + switch clause.Kind { + case filer_pb.WriteCondition_IF_NOT_EXISTS: + holds = current == nil + case filer_pb.WriteCondition_IF_ENTRY_EQUAL: + holds = current != nil && clause.ExpectedEntry != nil && proto.Equal(current, clause.ExpectedEntry) + case filer_pb.WriteCondition_IF_ETAG_MATCH: + holds = current != nil && slices.Contains(clause.Etags, string(current.Extended[s3_constants.ExtETagKey])) + } + if !holds { + return &filer_pb.ObjectTransactionResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED} + } + } + for _, m := range req.Mutations { + stored := proto.Clone(m.Entry).(*filer_pb.Entry) + // the filer fills in attributes the writer did not send + stored.Attributes.Inode = 4242 + f.entries[string(util.NewFullPath(m.Directory, stored.Name))] = stored + } + return &filer_pb.ObjectTransactionResponse{} +} + +func (f *fencingFiler) AssignVolume(context.Context, *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) { + return &filer_pb.AssignVolumeResponse{FileId: "3,01637037d6", Location: &filer_pb.Location{Url: strings.TrimPrefix(f.volume.URL, "http://")}}, nil +} + +func (f *fencingFiler) transactions() []*filer_pb.ObjectTransactionRequest { + f.mu.Lock() + defer f.mu.Unlock() + return append([]*filer_pb.ObjectTransactionRequest(nil), f.txns...) +} + +func (f *fencingFiler) entry(path string) *filer_pb.Entry { + f.mu.Lock() + defer f.mu.Unlock() + return f.entries[path] +} + +func (f *fencingFiler) put(path string, entry *filer_pb.Entry) { + f.mu.Lock() + defer f.mu.Unlock() + f.entries[path] = entry +} + +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}`) + })) + t.Cleanup(f.volume.Close) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, f) + go server.Serve(listener) + t.Cleanup(server.Stop) + + flushCtx, flushCancel := context.WithCancel(context.Background()) + t.Cleanup(flushCancel) + return f, &MessageQueueBroker{ + option: &MessageQueueBrokerOption{Ip: "127.0.0.1", Port: 17777}, + grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + currentFiler: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port), + flushCtx: flushCtx, + } +} + +var ( + fenceTestTopic = topic.NewTopic("test", "t") + fenceTestPartition = topic.Partition{RingSize: 2520, RangeStop: 2520, UnixTimeNs: 1} +) + +func TestTakeAbsentFenceRequiresItStillAbsent(t *testing.T) { + f, b := newFencingFiler(t) + fence, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3) + if err != nil { + t.Fatal(err) + } + path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition) + txns := f.transactions() + if len(txns) != 1 { + t.Fatalf("%d transactions, want 1", len(txns)) + } + txn := txns[0] + if txn.LockKey != path || txn.ConditionKey != path || txn.RouteKey != s3_constants.ObjectWriteRouteKeyPrefix+path || txn.RequestId == "" { + t.Errorf("transaction keys lock=%q condition=%q route=%q request=%q", txn.LockKey, txn.ConditionKey, txn.RouteKey, txn.RequestId) + } + if clauses := txn.Condition.GetClauses(); len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_NOT_EXISTS || clauses[0].ExpectedEntry != nil { + t.Errorf("condition %v, want IF_NOT_EXISTS", txn.Condition) + } + put := txn.Mutations[0].Entry + if len(put.Chunks) != 0 || string(put.Extended[mq.ExtendedAttrFenceWriter]) != "127.0.0.1:17777" || string(put.Extended[mq.ExtendedAttrFenceEpoch]) != "3" { + t.Errorf("fence entry %v", put) + } + for _, key := range []string{mq.ExtendedAttrOffsetMin, mq.ExtendedAttrOffsetMax, mq.ExtendedAttrBufferStart} { + if _, found := put.Extended[key]; found { + t.Errorf("fence carries %s", key) + } + } + if fence.Path != path || fence.Token == "" || string(f.entry(path).Extended[s3_constants.ExtETagKey]) != fence.Token { + t.Errorf("held fence token %q is not the stored %v", fence.Token, f.entry(path)) + } +} + +func TestTakePresentFenceRequiresTheEntryAsRead(t *testing.T) { + f, b := newFencingFiler(t) + path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition) + previous := &filer_pb.Entry{ + Name: topic.PartitionFenceName, + Attributes: &filer_pb.FuseAttributes{Mtime: 1, Inode: 7}, + Extended: map[string][]byte{mq.ExtendedAttrFenceWriter: []byte("127.0.0.1:18888"), mq.ExtendedAttrFenceEpoch: []byte("2")}, + } + f.put(path, previous) + + fence, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3) + if err != nil { + t.Fatal(err) + } + clauses := f.transactions()[0].Condition.GetClauses() + if len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ENTRY_EQUAL || !proto.Equal(clauses[0].ExpectedEntry, previous) { + t.Errorf("condition %v, want IF_ENTRY_EQUAL on %v", clauses, previous) + } + if stored := f.entry(path); string(stored.Extended[mq.ExtendedAttrFenceEpoch]) != "3" || string(stored.Extended[s3_constants.ExtETagKey]) != fence.Token { + t.Errorf("stored fence %v, held token %q", stored, fence.Token) + } + + // the same epoch can be taken again, as a restarted leader does, requiring the token as read + again, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 3) + if err != nil { + t.Fatal(err) + } + if clauses := f.transactions()[1].Condition.GetClauses(); len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || !slices.Equal(clauses[0].Etags, []string{fence.Token}) { + t.Errorf("retake condition %v, want the token %q", clauses, fence.Token) + } + if again.Token == fence.Token { + t.Error("a retaken fence kept its token") + } +} + +// The take is decided by the owner's transaction, so a filer whose reads lag +// behind the owner does not turn a taken fence into a lost one. +func TestTakeFenceThroughALaggingFiler(t *testing.T) { + f, b := newFencingFiler(t) + f.lagging = map[string]*filer_pb.Entry{} + localPartition, flush := newFencedPartition(t, b) + flush(localPartition.LogBuffer, time.Now(), time.Now(), []byte("data"), 0, 9) + if localPartition.IsFenced() || len(f.transactions()) != 2 { + t.Errorf("fenced=%v after %d transactions", localPartition.IsFenced(), len(f.transactions())) + } +} + +func TestTakeFenceRefusesAHigherEpoch(t *testing.T) { + f, b := newFencingFiler(t) + path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition) + f.put(path, &filer_pb.Entry{ + Name: topic.PartitionFenceName, + Attributes: &filer_pb.FuseAttributes{}, + Extended: map[string][]byte{mq.ExtendedAttrFenceWriter: []byte("127.0.0.1:18888"), mq.ExtendedAttrFenceEpoch: []byte("5")}, + }) + if _, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 4); !errors.Is(err, errFenceLost) { + t.Fatalf("took a fence at a higher epoch: %v", err) + } + if txns := f.transactions(); len(txns) != 0 { + t.Errorf("sent %d transactions for a refused fence", len(txns)) + } +} + +func TestTakeFenceLosingTheRace(t *testing.T) { + f, b := newFencingFiler(t) + path := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition) + f.beforeApply = func() { + f.entries[path] = &filer_pb.Entry{Name: topic.PartitionFenceName, Attributes: &filer_pb.FuseAttributes{}, + Extended: map[string][]byte{mq.ExtendedAttrFenceWriter: []byte("127.0.0.1:18888"), mq.ExtendedAttrFenceEpoch: []byte("1")}} + } + if _, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 1); !errors.Is(err, errFenceLost) { + t.Fatalf("took a fence another broker wrote first: %v", err) + } +} + +func TestTakeFenceGivesUpOnAStalledFiler(t *testing.T) { + f, b := newFencingFiler(t) + f.stalled = true + defer func(timeout time.Duration) { fenceTakeTimeout = timeout }(fenceTakeTimeout) + fenceTakeTimeout = 100 * time.Millisecond + + done := make(chan error, 1) + go func() { + _, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, 1) + done <- err + }() + select { + case err := <-done: + if err == nil { + t.Fatal("took a fence through a stalled filer") + } + case <-time.After(10 * time.Second): + t.Fatal("fence take waited on a stalled filer") + } +} + +// A broker that lost a partition's fence and is made its leader again reloads it +// and takes the newer epoch's fence instead of serving the fenced copy. +func TestReassignedLeaderReplacesItsFencedPartition(t *testing.T) { + f, b := newFencingFiler(t) + b.localTopicManager = topic.NewLocalTopicManager() + b.fca = &filer_client.FilerClientAccessor{ + GetGrpcDialOption: b.GetGrpcDialOption, + GetFilers: func() []pb.ServerAddress { return []pb.ServerAddress{b.GetFiler()} }, + } + assign := func(epoch int64) { + t.Helper() + if _, err := b.AssignTopicPartitions(context.Background(), &mq_pb.AssignTopicPartitionsRequest{ + Topic: fenceTestTopic.ToPbTopic(), + BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{Partition: fenceTestPartition.ToPbPartition(), Epoch: epoch}}, + }); err != nil { + t.Fatal(err) + } + } + assign(1) + old := b.localTopicManager.GetLocalPartition(fenceTestTopic, fenceTestPartition) + old.Fence.MarkLost() + + assign(3) + current := b.localTopicManager.GetLocalPartition(fenceTestTopic, fenceTestPartition) + if current == old || current.IsFenced() { + t.Fatal("still serving the fenced partition") + } + if epoch, _ := fenceEpoch(f.entry(topic.PartitionFencePath(fenceTestTopic, fenceTestPartition))); epoch != 3 { + t.Fatalf("fence at epoch %d, want 3", epoch) + } +} + +// A copy loaded under an older epoch is reloaded even before a refused flush +// marks its fence lost, so it does not take publishes its next flush would drop. +// Its last flush lands first, under its own fence, before the reload reads the files. +func TestReassignmentReloadsAnOlderEpoch(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) + } + assign := func(epoch int64) *topic.LocalPartition { + t.Helper() + if _, err := b.AssignTopicPartitions(context.Background(), &mq_pb.AssignTopicPartitionsRequest{ + Topic: fenceTestTopic.ToPbTopic(), + BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{Partition: fenceTestPartition.ToPbPartition(), Epoch: epoch}}, + }); err != nil { + t.Fatal(err) + } + current := b.localTopicManager.GetLocalPartition(fenceTestTopic, fenceTestPartition) + t.Cleanup(current.LogBuffer.ShutdownLogBuffer) + return current + } + if assign(1) != old { + t.Fatal("reloaded at the epoch it holds") + } + reloaded := assign(2) + if reloaded == old || reloaded.Fence.Epoch != 2 { + t.Fatalf("serving fence %+v after an assignment at epoch 2", reloaded.Fence) + } + txns := f.transactions() + if len(txns) != 3 || !strings.HasPrefix(txns[1].Mutations[0].Entry.Name, "20") || txns[2].Mutations[0].Entry.Name != topic.PartitionFenceName { + t.Errorf("%d transactions, want the old copy's last window before the new fence", len(txns)) + } +} + +func TestLookupReloadsAnOlderEpoch(t *testing.T) { + _, b := newFencingFiler(t) + old, _ := newFencedPartition(t, b) + conf := &mq_pb.ConfigureTopicResponse{BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{ + {Partition: fenceTestPartition.ToPbPartition(), LeaderBroker: "127.0.0.1:17777", Epoch: 2}, + }} + current, _, err := b.doGetOrGenLocalPartition(fenceTestTopic, fenceTestPartition, conf) + if err != nil { + t.Fatal(err) + } + t.Cleanup(current.LogBuffer.ShutdownLogBuffer) + if current == old || current.Fence.Epoch != 2 { + 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 deadline := time.Now().Add(10 * time.Second); f.uploads.Load() == 0; time.Sleep(time.Millisecond) { + if time.Now().After(deadline) { + close(f.uploadGate) + t.Fatal("the stale copy's last flush never started") + } + } + time.Sleep(50 * time.Millisecond) + close(f.uploadGate) + wg.Wait() + + current := b.localTopicManager.GetLocalPartition(fenceTestTopic, fenceTestPartition) + if current == nil { + t.Fatal("no partition after the reloads") + } + 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) + } + } +} diff --git a/weed/mq/broker/broker_topic_conf_read_write.go b/weed/mq/broker/broker_topic_conf_read_write.go index 40f3c386fb..73124d03f3 100644 --- a/weed/mq/broker/broker_topic_conf_read_write.go +++ b/weed/mq/broker/broker_topic_conf_read_write.go @@ -10,7 +10,6 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/mq" - "github.com/seaweedfs/seaweedfs/weed/mq/logstore" "github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer" "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/pb" @@ -138,7 +137,11 @@ func (b *MessageQueueBroker) doGetOrGenLocalPartition(t topic.Topic, partition t b.accessLock.Lock() defer b.accessLock.Unlock() - if localPartition = b.localTopicManager.GetLocalPartition(t, partition); localPartition == nil { + localPartition = b.localTopicManager.GetLocalPartition(t, partition) + for b.retireStaleLeader(t, localPartition, b.assignedLeaderEpoch(partition, conf)) { + localPartition = b.localTopicManager.GetLocalPartition(t, partition) + } + if localPartition == nil { localPartition, isGenerated, err = b.genLocalPartitionFromFiler(t, partition, conf) if err != nil { return nil, false, err @@ -147,6 +150,17 @@ func (b *MessageQueueBroker) doGetOrGenLocalPartition(t topic.Topic, partition t return localPartition, isGenerated, nil } +// assignedLeaderEpoch is the epoch of conf's assignment making this broker the +// partition's leader, or 0 if conf names another leader. +func (b *MessageQueueBroker) assignedLeaderEpoch(partition topic.Partition, conf *mq_pb.ConfigureTopicResponse) int64 { + for _, assignment := range conf.BrokerPartitionAssignments { + if pb.ServerAddress(assignment.LeaderBroker).Equals(b.option.BrokerAddress()) && partition.LogicalEquals(topic.FromPbPartition(assignment.Partition)) { + return assignment.Epoch + } + } + return 0 +} + func (b *MessageQueueBroker) genLocalPartitionFromFiler(t topic.Topic, partition topic.Partition, conf *mq_pb.ConfigureTopicResponse) (localPartition *topic.LocalPartition, isGenerated bool, err error) { self := b.option.BrokerAddress() glog.V(4).Infof("genLocalPartitionFromFiler for %s %s, self=%s", t, partition, self) @@ -161,10 +175,9 @@ func (b *MessageQueueBroker) genLocalPartitionFromFiler(t topic.Topic, partition glog.V(4).Infof("assignmentPartition details: RangeStart=%d, RangeStop=%d, RingSize=%d, UnixTimeNs=%d", assignmentPartition.RangeStart, assignmentPartition.RangeStop, assignmentPartition.RingSize, assignmentPartition.UnixTimeNs) if pb.ServerAddress(assignment.LeaderBroker).Equals(self) && partition.LogicalEquals(assignmentPartition) { glog.V(4).Infof("Creating local partition for %s %s", t, partition) - localPartition = topic.NewLocalPartition(partition, b.option.LogFlushInterval, b.genLogFlushFunc(t, partition), logstore.GenMergedReadFunc(b, t, partition)) - - // Initialize offset from existing data to ensure continuity on restart - b.initializePartitionOffsetFromExistingData(localPartition, t, partition) + if localPartition, err = b.newLeaderPartition(t, partition, assignment.Epoch); err != nil { + return nil, false, err + } if !b.localTopicManager.AddLocalPartition(t, localPartition) { localPartition.Shutdown() diff --git a/weed/mq/broker/broker_topic_partition_read_write.go b/weed/mq/broker/broker_topic_partition_read_write.go index 9c27733755..de4005fb74 100644 --- a/weed/mq/broker/broker_topic_partition_read_write.go +++ b/weed/mq/broker/broker_topic_partition_read_write.go @@ -2,6 +2,7 @@ package broker import ( "context" + "errors" "fmt" "time" @@ -21,7 +22,7 @@ type LogBufferStart struct { StartIndex int64 // Starting buffer offset (count = len(chunks)) } -func (b *MessageQueueBroker) genLogFlushFunc(t topic.Topic, p topic.Partition) log_buffer.LogFlushFuncType { +func (b *MessageQueueBroker) genLogFlushFunc(t topic.Topic, p topic.Partition, fence *topic.PartitionFence) log_buffer.LogFlushFuncType { partitionDir := topic.PartitionDir(t, p) return func(logBuffer *log_buffer.LogBuffer, startTime, stopTime time.Time, buf []byte, minOffset, maxOffset int64) { @@ -31,30 +32,22 @@ func (b *MessageQueueBroker) genLogFlushFunc(t topic.Topic, p topic.Partition) l startTime, stopTime = startTime.UTC(), stopTime.UTC() - targetFile := fmt.Sprintf("%s/%s", partitionDir, startTime.Format(topic.TIME_FORMAT)) - - // Get buffer offset (sequential: 0, 1, 2, 3...) - bufferOffset := logBuffer.GetOffset() + targetFile := fmt.Sprintf("%s/%s", partitionDir, topic.LogFileName(startTime, minOffset)) ctx := b.flushCtx if ctx == nil { ctx = context.Background() } - for { - err := b.appendToFileWithBufferIndex(ctx, targetFile, buf, bufferOffset, minOffset, maxOffset) - if err == nil { - break - } - glog.V(0).Infof("metadata log write failed %s: %v", targetFile, err) - // Once cancelled, every later window drops too, so neither the watermark - // nor the follower's flush notice passes a dropped window. - select { - case <-ctx.Done(): - logBuffer.NoteFlushDropped(len(buf)) + if err := b.writeLogFile(ctx, fence, targetFile, buf, minOffset, maxOffset); err != nil { + // Once cancelled or fenced, every later window drops too, so neither the + // watermark nor the follower's flush notice passes a dropped window. + logBuffer.NoteFlushDropped(len(buf)) + if errors.Is(err, errFenceLost) { + glog.Warningf("flush to %s refused, %d bytes dropped: %v", targetFile, len(buf), err) + } else { glog.Warningf("flush to %s abandoned during shutdown, %d bytes dropped: %v", targetFile, len(buf), err) - return - case <-time.After(737 * time.Millisecond): } + return } logBuffer.SetLastFlushTsNs(stopTime.UnixNano()) @@ -65,6 +58,6 @@ func (b *MessageQueueBroker) genLogFlushFunc(t topic.Topic, p topic.Partition) l localPartition.NotifyLogFlushed(logBuffer.GetLastFlushTsNs()) } - glog.V(0).Infof("flushing at %d to %s size %d from buffer %s (offset %d)", logBuffer.GetLastFlushTsNs(), targetFile, len(buf), logBuffer.GetName(), bufferOffset) + glog.V(0).Infof("flushing at %d to %s size %d from buffer %s (offsets %d-%d)", logBuffer.GetLastFlushTsNs(), targetFile, len(buf), logBuffer.GetName(), minOffset, maxOffset) } } diff --git a/weed/mq/broker/broker_write.go b/weed/mq/broker/broker_write.go index b692e68130..f9f6fac925 100644 --- a/weed/mq/broker/broker_write.go +++ b/weed/mq/broker/broker_write.go @@ -3,13 +3,15 @@ package broker import ( "context" "encoding/binary" + "errors" "fmt" "os" "time" - "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/google/uuid" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/mq" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/operation" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" @@ -17,10 +19,6 @@ import ( "github.com/seaweedfs/seaweedfs/weed/util/mem" ) -func (b *MessageQueueBroker) appendToFile(targetFile string, data []byte) error { - return b.appendToFileWithBufferIndex(context.Background(), targetFile, data, 0) -} - // offsetRange reads the optional (minOffset, maxOffset) of a flushed window. // A partition's first window starts at offset 0. func offsetRange(offsetArgs []int64) (minOffset, maxOffset int64, ok bool) { @@ -31,135 +29,82 @@ func offsetRange(offsetArgs []int64) (minOffset, maxOffset int64, ok bool) { return minOffset, maxOffset, minOffset >= 0 && maxOffset >= minOffset } -func (b *MessageQueueBroker) appendToFileWithBufferIndex(ctx context.Context, targetFile string, data []byte, bufferOffset int64, offsetArgs ...int64) error { +// writeLogFile stores one window as a new file while fence is still the partition's fence. +// It uploads once and retries only the transaction, under one request id. +func (b *MessageQueueBroker) writeLogFile(ctx context.Context, fence *topic.PartitionFence, targetFile string, data []byte, offsetArgs ...int64) error { + if fence == nil { + return fmt.Errorf("%s: this broker holds no fence: %w", targetFile, errFenceLost) + } + if fence.IsLost() { + return fmt.Errorf("%s: %w", fence.Path, errFenceLost) + } if err := ctx.Err(); err != nil { return err } - minOffset, maxOffset, hasOffsetRange := offsetRange(offsetArgs) - fileId, uploadResult, err2 := b.assignAndUpload(ctx, targetFile, data) - if err2 != nil { - return err2 + var fileId string + var uploadResult *operation.UploadResult + if err := retryLogWrite(ctx, targetFile, func() (err error) { + fileId, uploadResult, err = b.assignAndUpload(ctx, targetFile, data) + return err + }); err != nil { + return err } - // find out existing entry - fullpath := util.FullPath(targetFile) - dir, name := fullpath.DirAndName() - entry, _, _, err := filer_pb.GetEntry(ctx, b, fullpath) - var offset int64 = 0 - if err == filer_pb.ErrNotFound { - entry = &filer_pb.Entry{ - Name: name, - IsDirectory: false, - Attributes: &filer_pb.FuseAttributes{ - Crtime: time.Now().Unix(), - Mtime: time.Now().Unix(), - FileMode: uint32(os.FileMode(0644)), - Uid: uint32(os.Getuid()), - Gid: uint32(os.Getgid()), - }, - } - - // Add buffer start offset for deduplication tracking (binary format) - if bufferOffset != 0 { - entry.Extended = make(map[string][]byte) - bufferStartBytes := make([]byte, 8) - binary.BigEndian.PutUint64(bufferStartBytes, uint64(bufferOffset)) - entry.Extended[mq.ExtendedAttrBufferStart] = bufferStartBytes - } - - // Add offset range metadata for Kafka integration - if hasOffsetRange { - if entry.Extended == nil { - entry.Extended = make(map[string][]byte) - } - minOffsetBytes := make([]byte, 8) - binary.BigEndian.PutUint64(minOffsetBytes, uint64(minOffset)) - entry.Extended[mq.ExtendedAttrOffsetMin] = minOffsetBytes - - maxOffsetBytes := make([]byte, 8) - binary.BigEndian.PutUint64(maxOffsetBytes, uint64(maxOffset)) - entry.Extended[mq.ExtendedAttrOffsetMax] = maxOffsetBytes - } - } else if err != nil { - return fmt.Errorf("find %s: %v", fullpath, err) - } else { - offset = int64(filer.TotalSize(entry.GetChunks())) - - // Verify buffer offset continuity for existing files (append operations) - if bufferOffset != 0 { - if entry.Extended == nil { - entry.Extended = make(map[string][]byte) - } - - // Check for existing buffer start (binary format) - if existingData, exists := entry.Extended[mq.ExtendedAttrBufferStart]; exists { - if len(existingData) == 8 { - existingStartIndex := int64(binary.BigEndian.Uint64(existingData)) - - // Verify that the new buffer offset is consecutive - // Expected offset = start + number of existing chunks - expectedOffset := existingStartIndex + int64(len(entry.GetChunks())) - if bufferOffset != expectedOffset { - // This shouldn't happen in normal operation - // Log warning but continue (don't crash the system) - glog.Warningf("non-consecutive buffer offset for %s. Expected %d, got %d", - fullpath, expectedOffset, bufferOffset) - } - // Note: We don't update the start offset - it stays the same - } - } else { - // No existing buffer start, create new one (shouldn't happen for existing files) - bufferStartBytes := make([]byte, 8) - binary.BigEndian.PutUint64(bufferStartBytes, uint64(bufferOffset)) - entry.Extended[mq.ExtendedAttrBufferStart] = bufferStartBytes - } - } - - // Update offset range metadata for existing files - if hasOffsetRange { - // Update minimum offset if this chunk has a lower minimum - if existingMinData, exists := entry.Extended[mq.ExtendedAttrOffsetMin]; exists && len(existingMinData) == 8 { - existingMin := int64(binary.BigEndian.Uint64(existingMinData)) - if minOffset < existingMin { - minOffsetBytes := make([]byte, 8) - binary.BigEndian.PutUint64(minOffsetBytes, uint64(minOffset)) - entry.Extended[mq.ExtendedAttrOffsetMin] = minOffsetBytes - } - } else { - // No existing minimum, set it - minOffsetBytes := make([]byte, 8) - binary.BigEndian.PutUint64(minOffsetBytes, uint64(minOffset)) - entry.Extended[mq.ExtendedAttrOffsetMin] = minOffsetBytes - } - - // Update maximum offset if this chunk has a higher maximum - if existingMaxData, exists := entry.Extended[mq.ExtendedAttrOffsetMax]; exists && len(existingMaxData) == 8 { - existingMax := int64(binary.BigEndian.Uint64(existingMaxData)) - if maxOffset > existingMax { - maxOffsetBytes := make([]byte, 8) - binary.BigEndian.PutUint64(maxOffsetBytes, uint64(maxOffset)) - entry.Extended[mq.ExtendedAttrOffsetMax] = maxOffsetBytes - } - } else { - // No existing maximum, set it - maxOffsetBytes := make([]byte, 8) - binary.BigEndian.PutUint64(maxOffsetBytes, uint64(maxOffset)) - entry.Extended[mq.ExtendedAttrOffsetMax] = maxOffsetBytes - } + now := time.Now() + chunk := uploadResult.ToPbFileChunk(fileId, 0, now.UnixNano()) + dir, name := util.FullPath(targetFile).DirAndName() + entry := &filer_pb.Entry{ + Name: name, + Chunks: []*filer_pb.FileChunk{chunk}, + Attributes: &filer_pb.FuseAttributes{ + FileSize: chunk.Size, + Crtime: now.Unix(), + Mtime: now.Unix(), + FileMode: uint32(os.FileMode(0644)), + Uid: uint32(os.Getuid()), + Gid: uint32(os.Getgid()), + }, + } + if minOffset, maxOffset, ok := offsetRange(offsetArgs); ok { + entry.Extended = map[string][]byte{ + mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(minOffset)), + mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(maxOffset)), + mq.ExtendedAttrBufferStart: binary.BigEndian.AppendUint64(nil, uint64(minOffset)), } } - // append to existing chunks - entry.Chunks = append(entry.GetChunks(), uploadResult.ToPbFileChunk(fileId, offset, time.Now().UnixNano())) - - // update the entry - return b.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - return filer_pb.CreateEntry(ctx, client, &filer_pb.CreateEntryRequest{ - Directory: dir, - Entry: entry, - }) + condition := fenceTokenCondition(fence.Token) + mutation := &filer_pb.ObjectMutation{Type: filer_pb.ObjectMutation_PUT, Directory: dir, Entry: entry} + requestId := uuid.NewString() + err := retryLogWrite(ctx, targetFile, func() error { + err := b.fencedTransaction(ctx, fence.Path, condition, requestId, mutation) + if errors.Is(err, errTransactionFailed) { + // putting the same entry again is harmless, so run it anew rather than replay the failure + requestId = uuid.NewString() + } + return err }) + if errors.Is(err, errFenceLost) { + fence.MarkLost() + } + return err +} + +// retryLogWrite retries write until it succeeds, the fence is lost, or ctx ends. +func retryLogWrite(ctx context.Context, targetFile string, write func() error) error { + for { + err := write() + if err == nil || errors.Is(err, errFenceLost) { + return err + } + glog.V(0).Infof("metadata log write failed %s: %v", targetFile, err) + select { + case <-ctx.Done(): + return err + case <-time.After(737 * time.Millisecond): + } + } } // assignAndUpload stops waiting once ctx ends. The abandoned upload works on its diff --git a/weed/mq/broker/broker_write_test.go b/weed/mq/broker/broker_write_test.go index c6f6e28f23..012ea2ae2e 100644 --- a/weed/mq/broker/broker_write_test.go +++ b/weed/mq/broker/broker_write_test.go @@ -2,13 +2,17 @@ package broker import ( "context" + "encoding/binary" + "errors" "net" "testing" "time" + "github.com/seaweedfs/seaweedfs/weed/mq" "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/util/log_buffer" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" @@ -68,7 +72,8 @@ func TestStoppingBrokerAbandonsAFailingFlush(t *testing.T) { currentFiler: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port), flushCtx: flushCtx, } - flush := b.genLogFlushFunc(topic.NewTopic("test", "t"), topic.Partition{RingSize: 2520, RangeStop: 2520}) + fence := &topic.PartitionFence{Path: topic.PartitionFencePath(fenceTestTopic, fenceTestPartition), Token: "token"} + flush := b.genLogFlushFunc(fenceTestTopic, fenceTestPartition, fence) logBuffer := log_buffer.NewLogBuffer("test", time.Hour, flush, nil, nil) defer logBuffer.ShutdownLogBuffer() @@ -89,3 +94,147 @@ func TestStoppingBrokerAbandonsAFailingFlush(t *testing.T) { }) } } + +func newFencedPartition(t *testing.T, b *MessageQueueBroker) (*topic.LocalPartition, log_buffer.LogFlushFuncType) { + fence, err := b.takePartitionFence(context.Background(), fenceTestTopic, fenceTestPartition, 1) + if err != nil { + t.Fatal(err) + } + flush := b.genLogFlushFunc(fenceTestTopic, fenceTestPartition, fence) + localPartition := topic.NewLocalPartition(fenceTestPartition, 3600, flush, nil) + localPartition.Fence = fence + t.Cleanup(localPartition.LogBuffer.ShutdownLogBuffer) + b.localTopicManager = topic.NewLocalTopicManager() + b.localTopicManager.AddLocalPartition(fenceTestTopic, localPartition) + return localPartition, flush +} + +// A lost transaction response is retried under the same request id without +// uploading the window again, and the window lands as its own file. +func TestFlushWritesOneFencedFilePerWindow(t *testing.T) { + f, b := newFencingFiler(t) + localPartition, flush := newFencedPartition(t, b) + fence := localPartition.Fence + f.mu.Lock() + f.dropResponses = 1 + f.mu.Unlock() + + start := time.Date(2026, 11, 30, 10, 0, 5, 0, time.UTC) + flush(localPartition.LogBuffer, start, start.Add(time.Second), []byte("data"), 200, 399) + + txns := f.transactions()[1:] + if len(txns) != 2 { + t.Fatalf("%d flush transactions, want a retry after the lost response", len(txns)) + } + if txns[0].RequestId == "" || txns[0].RequestId != txns[1].RequestId { + t.Errorf("request ids %q and %q, want one per window", txns[0].RequestId, txns[1].RequestId) + } + if n := f.uploads.Load(); n != 1 { + t.Errorf("%d uploads, want 1", n) + } + txn := txns[0] + if txn.LockKey != fence.Path || txn.ConditionKey != fence.Path || txn.RouteKey != s3_constants.ObjectWriteRouteKeyPrefix+fence.Path { + t.Errorf("transaction keys lock=%q condition=%q route=%q", txn.LockKey, txn.ConditionKey, txn.RouteKey) + } + if clauses := txn.Condition.GetClauses(); len(clauses) != 1 || clauses[0].Kind != filer_pb.WriteCondition_IF_ETAG_MATCH || len(clauses[0].Etags) != 1 || clauses[0].Etags[0] != fence.Token { + t.Errorf("condition %v, want the held fence's token", txn.Condition) + } + + partitionDir := topic.PartitionDir(fenceTestTopic, fenceTestPartition) + written := f.entry(partitionDir + "/2026-11-30-10-00-05.00000000000000000200") + if written == nil { + t.Fatalf("no file named by start time and first offset; transactions %v", txns) + } + if len(written.Chunks) != 1 || written.Attributes.FileSize != written.Chunks[0].Size || written.Attributes.FileMode != 0644 { + t.Errorf("written entry %v", written) + } + for key, want := range map[string]uint64{mq.ExtendedAttrOffsetMin: 200, mq.ExtendedAttrOffsetMax: 399, mq.ExtendedAttrBufferStart: 200} { + if got := written.Extended[key]; len(got) != 8 || binary.BigEndian.Uint64(got) != want { + t.Errorf("%s = %v, want %d", key, got, want) + } + } + if got := localPartition.LogBuffer.GetLastFlushTsNs(); got != start.Add(time.Second).UnixNano() { + t.Errorf("flush watermark %d", got) + } +} + +// A failure the filer recorded is replayed for its request id, so the retry runs +// the same write under a new one. +func TestFlushRetriesARecordedFailureUnderANewRequestId(t *testing.T) { + f, b := newFencingFiler(t) + localPartition, flush := newFencedPartition(t, b) + f.mu.Lock() + f.failMutations = 1 + f.mu.Unlock() + + start := time.Date(2026, 11, 30, 10, 0, 5, 0, time.UTC) + done := make(chan struct{}) + go func() { + defer close(done) + flush(localPartition.LogBuffer, start, start.Add(time.Second), []byte("data"), 0, 9) + }() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("flush kept replaying the recorded failure") + } + + txns := f.transactions()[1:] + if len(txns) != 2 || txns[0].RequestId == txns[1].RequestId { + t.Fatalf("%d flush transactions, want a retry under a new request id", len(txns)) + } + if f.entry(topic.PartitionDir(fenceTestTopic, fenceTestPartition)+"/2026-11-30-10-00-05.00000000000000000000") == nil { + t.Error("the window was not written after the store recovered") + } + if n := f.uploads.Load(); n != 1 { + t.Errorf("%d uploads, want 1", n) + } +} + +// Once another broker takes the fence, the flush stops at the first refusal and +// the partition stops serving; later windows are dropped without an upload. +func TestFlushStopsWhenTheFenceIsTaken(t *testing.T) { + f, b := newFencingFiler(t) + localPartition, flush := newFencedPartition(t, b) + f.put(localPartition.Fence.Path, &filer_pb.Entry{ + Name: topic.PartitionFenceName, + Attributes: &filer_pb.FuseAttributes{}, + Extended: map[string][]byte{mq.ExtendedAttrFenceWriter: []byte("127.0.0.1:18888"), mq.ExtendedAttrFenceEpoch: []byte("2")}, + }) + + done := make(chan struct{}) + go func() { + defer close(done) + flush(localPartition.LogBuffer, time.Now(), time.Now(), []byte("data"), 0, 9) + }() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("flush kept retrying after the fence was taken") + } + if !localPartition.IsFenced() { + t.Error("partition still serves after losing its fence") + } + if localPartition.LogBuffer.GetLastFlushTsNs() != 0 { + t.Error("a refused flush advanced the flush watermark") + } + + flush(localPartition.LogBuffer, time.Now(), time.Now(), []byte("more"), 10, 19) + if txns := f.transactions(); len(txns) != 2 { + t.Errorf("%d transactions, want the fence take and one refused flush", len(txns)) + } + if n := f.uploads.Load(); n != 1 { + t.Errorf("%d uploads, want none after the fence was lost", n) + } +} + +func TestFollowerCannotWriteWithoutAFence(t *testing.T) { + f, b := newFencingFiler(t) + err := b.writeLogFile(context.Background(), nil, topic.PartitionDir(fenceTestTopic, fenceTestPartition)+"/x", []byte("data")) + if !errors.Is(err, errFenceLost) { + t.Fatalf("wrote without a fence: %v", err) + } + if f.uploads.Load() != 0 || len(f.transactions()) != 0 { + t.Error("a refused write reached the filer") + } +} diff --git a/weed/mq/logstore/log_to_parquet.go b/weed/mq/logstore/log_to_parquet.go index 067ddf1b09..afdc783cf8 100644 --- a/weed/mq/logstore/log_to_parquet.go +++ b/weed/mq/logstore/log_to_parquet.go @@ -99,13 +99,13 @@ func compactTopicPartition(filerClient filer_pb.FilerClient, t topic.Topic, time func compactTopicPartitionDir(filerClient filer_pb.FilerClient, topicName, partitionDir string, timeAgo time.Duration, recordType *schema_pb.RecordType, preference *operation.StoragePreference) error { // read all existing parquet files - minTsNs, maxTsNs, err := readAllParquetFiles(filerClient, partitionDir) + maxTsNs, compacted, err := readAllParquetFiles(filerClient, partitionDir) if err != nil { return err } // read all log files - logFiles, err := readAllLogFiles(filerClient, partitionDir, timeAgo, minTsNs, maxTsNs) + logFiles, err := readAllLogFiles(filerClient, partitionDir, timeAgo, maxTsNs, compacted) if err != nil { return err } @@ -142,7 +142,7 @@ func groupFilesBySize(logFiles []*filer_pb.Entry, maxGroupSize int64) (logFileGr var logFileGroup []*filer_pb.Entry var groupSize int64 for _, logFile := range logFiles { - if groupSize+int64(logFile.Attributes.FileSize) > maxGroupSize { + if len(logFileGroup) > 0 && groupSize+int64(logFile.Attributes.FileSize) > maxGroupSize { logFileGroups = append(logFileGroups, logFileGroup) logFileGroup = nil groupSize = 0 @@ -156,7 +156,10 @@ func groupFilesBySize(logFiles []*filer_pb.Entry, maxGroupSize int64) (logFileGr return } -func readAllLogFiles(filerClient filer_pb.FilerClient, partitionDir string, timeAgo time.Duration, minTsNs, maxTsNs int64) (logFiles []*filer_pb.Entry, err error) { +// readAllLogFiles lists the log files no parquet file holds yet. A compacted file is +// known by name from the parquet sources; a log file named by its start second only +// is also taken as compacted when that second is not after the newest parquet row. +func readAllLogFiles(filerClient filer_pb.FilerClient, partitionDir string, timeAgo time.Duration, maxTsNs int64, compacted map[string]bool) (logFiles []*filer_pb.Entry, err error) { err = filer_pb.ReadDirAllEntries(context.Background(), filerClient, util.FullPath(partitionDir), "", func(entry *filer_pb.Entry, isLast bool) error { if strings.HasSuffix(entry.Name, ".parquet") { return nil @@ -164,12 +167,15 @@ func readAllLogFiles(filerClient filer_pb.FilerClient, partitionDir string, time if entry.Attributes.Crtime > time.Now().Unix()-int64(timeAgo/time.Second) { return nil } - logTime, err := time.Parse(topic.TIME_FORMAT, entry.Name) + logTime, err := topic.ParseLogFileTime(entry.Name) if err != nil { // glog.Warningf("parse log time %s: %v", entry.Name, err) return nil } - if maxTsNs > 0 && logTime.UnixNano() <= maxTsNs { + if compacted[entry.Name] { + return nil + } + if entry.Name == topic.LogFileTimePrefix(entry.Name) && maxTsNs > 0 && logTime.UnixNano() <= maxTsNs { return nil } logFiles = append(logFiles, entry) @@ -178,7 +184,10 @@ func readAllLogFiles(filerClient filer_pb.FilerClient, partitionDir string, time return } -func readAllParquetFiles(filerClient filer_pb.FilerClient, partitionDir string) (minTsNs, maxTsNs int64, err error) { +// readAllParquetFiles reports the newest row any parquet file holds and the log +// files the parquet files were made from. +func readAllParquetFiles(filerClient filer_pb.FilerClient, partitionDir string) (maxTsNs int64, compacted map[string]bool, err error) { + compacted = make(map[string]bool) err = filer_pb.ReadDirAllEntries(context.Background(), filerClient, util.FullPath(partitionDir), "", func(entry *filer_pb.Entry, isLast bool) error { if !strings.HasSuffix(entry.Name, ".parquet") { return nil @@ -186,15 +195,11 @@ func readAllParquetFiles(filerClient filer_pb.FilerClient, partitionDir string) if len(entry.Extended) == 0 { return nil } - - // read min ts - minTsBytes := entry.Extended[mq.ExtendedAttrTimestampMin] - if len(minTsBytes) != 8 { - return nil - } - minTs := int64(binary.BigEndian.Uint64(minTsBytes)) - if minTsNs == 0 || minTs < minTsNs { - minTsNs = minTs + var sources []string + if json.Unmarshal(entry.Extended[mq.ExtendedAttrSources], &sources) == nil { + for _, source := range sources { + compacted[source] = true + } } // read max ts @@ -380,7 +385,8 @@ func writeLogFilesToParquet(filerClient filer_pb.FilerClient, partitionDir strin } // write to parquet file to partitionDir - parquetFileName := fmt.Sprintf("%s.parquet", time.Unix(0, startTsNs).UTC().Format("2006-01-02-15-04-05")) + // log file names are unique, so groups that start in one second keep apart + parquetFileName := logFileGroups[0].Name + ".parquet" // Collect source log file names and buffer_start metadata for deduplication var sourceLogFiles []string diff --git a/weed/mq/logstore/log_to_parquet_select_test.go b/weed/mq/logstore/log_to_parquet_select_test.go new file mode 100644 index 0000000000..ce643f755c --- /dev/null +++ b/weed/mq/logstore/log_to_parquet_select_test.go @@ -0,0 +1,78 @@ +package logstore + +import ( + "encoding/binary" + "encoding/json" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/mq" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "google.golang.org/grpc" +) + +// A window starting in an already compacted second is compacted unless a parquet +// file lists it as a source. +func TestCompactionSelectsWindowsBySourceName(t *testing.T) { + second := time.Date(2026, 11, 30, 10, 0, 5, 0, time.UTC) + compactedLog := "2026-11-30-10-00-05.00000000000000000100" + sources, _ := json.Marshal([]string{compactedLog}) + log := func(name string) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{Crtime: 1}} + } + filer := &listingFiler{entries: []*filer_pb.Entry{ + log("2026-11-30-10-00-04"), + log(compactedLog), + {Name: compactedLog + ".parquet", Attributes: &filer_pb.FuseAttributes{Crtime: 1}, Extended: map[string][]byte{ + mq.ExtendedAttrTimestampMax: binary.BigEndian.AppendUint64(nil, uint64(second.Add(200*time.Millisecond).UnixNano())), + mq.ExtendedAttrSources: sources, + }}, + log("2026-11-30-10-00-05.00000000000000000200"), + }} + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, filer) + go server.Serve(listener) + defer server.Stop() + client := listingFilerClient{address: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port)} + + maxTsNs, compacted, err := readAllParquetFiles(client, "/topics/test/t/v1/0000-2520") + if err != nil { + t.Fatal(err) + } + logFiles, err := readAllLogFiles(client, "/topics/test/t/v1/0000-2520", 0, maxTsNs, compacted) + if err != nil { + t.Fatal(err) + } + if len(logFiles) != 1 || logFiles[0].Name != "2026-11-30-10-00-05.00000000000000000200" { + var names []string + for _, f := range logFiles { + names = append(names, f.Name) + } + t.Fatalf("selected %v, want only the window not yet compacted", names) + } +} + +// A log file larger than a group starts its own group instead of leaving an empty one. +func TestGroupFilesBySizeLeavesNoEmptyGroup(t *testing.T) { + file := func(name string, size uint64) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{FileSize: size}} + } + groups := groupFilesBySize([]*filer_pb.Entry{file("a", 300), file("b", 50), file("c", 60), file("d", 400)}, 100) + var names [][]string + for _, group := range groups { + var groupNames []string + for _, f := range group { + groupNames = append(groupNames, f.Name) + } + names = append(names, groupNames) + } + if len(names) != 4 || len(names[0]) != 1 || names[0][0] != "a" || len(names[1]) != 1 || names[1][0] != "b" || names[2][0] != "c" || names[3][0] != "d" { + t.Errorf("groups %v", names) + } +} diff --git a/weed/mq/logstore/read_log_from_disk.go b/weed/mq/logstore/read_log_from_disk.go index 86c8b40cc4..a52d7f8ff7 100644 --- a/weed/mq/logstore/read_log_from_disk.go +++ b/weed/mq/logstore/read_log_from_disk.go @@ -185,7 +185,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top glog.V(2).Infof("listing directory %s for offset %d startFileName=%q", partitionDir, startOffset, startFileName) return filer_pb.SeaweedList(context.Background(), client, partitionDir, "", func(entry *filer_pb.Entry, isLast bool) error { - if entry.IsDirectory { + if entry.IsDirectory || entry.Name == topic.PartitionFenceName { return nil } if strings.HasSuffix(entry.Name, ".parquet") { @@ -194,7 +194,7 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top if strings.HasSuffix(entry.Name, ".offset") { return nil } - if stopTsNs != 0 && entry.Name > stopTime.UTC().Format(topic.TIME_FORMAT) { + if stopTsNs != 0 && topic.LogFileTimePrefix(entry.Name) > stopTime.UTC().Format(topic.TIME_FORMAT) { return nil } diff --git a/weed/mq/logstore/read_log_from_disk_test.go b/weed/mq/logstore/read_log_from_disk_test.go new file mode 100644 index 0000000000..3f3911c68b --- /dev/null +++ b/weed/mq/logstore/read_log_from_disk_test.go @@ -0,0 +1,134 @@ +package logstore + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "sort" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/mq/topic" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/seaweedfs/seaweedfs/weed/util/log_buffer" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/proto" +) + +type listingFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + entries []*filer_pb.Entry + volumeUrl string +} + +func (f *listingFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error { + for _, entry := range f.entries { + if entry.Name < req.StartFromFileName || (!req.InclusiveStartFrom && entry.Name == req.StartFromFileName) { + continue + } + if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil { + return err + } + } + return nil +} + +func (f *listingFiler) LookupVolume(_ context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) { + resp := &filer_pb.LookupVolumeResponse{LocationsMap: map[string]*filer_pb.Locations{}} + for _, vid := range req.VolumeIds { + resp.LocationsMap[vid] = &filer_pb.Locations{Locations: []*filer_pb.Location{{Url: f.volumeUrl}}} + } + return resp, nil +} + +type listingFilerClient struct { + address pb.ServerAddress +} + +func (c listingFilerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error { + return pb.WithGrpcFilerClient(streamingMode, 0, c.address, grpc.WithTransportCredentials(insecure.NewCredentials()), security.FilerAdminToken, fn) +} +func (c listingFilerClient) AdjustedUrl(location *filer_pb.Location) string { return location.Url } +func (c listingFilerClient) GetDataCenter() string { return "" } + +func logChunk(t *testing.T, tsNs ...int64) []byte { + var buf []byte + for _, ts := range tsNs { + data, err := proto.Marshal(&filer_pb.LogEntry{TsNs: ts, Key: []byte("k")}) + if err != nil { + t.Fatal(err) + } + size := make([]byte, 4) + util.Uint32toBytes(size, uint32(len(data))) + buf = append(append(buf, size...), data...) + } + return buf +} + +// A window flushed in the stop second is named after that second plus its offset, +// and must not be dropped as if it started later; the fence is never read. +func TestReadFromDiskKeepsAFileStartingInTheStopSecond(t *testing.T) { + second := time.Date(2026, 11, 30, 10, 0, 5, 0, time.UTC) + chunks := map[string][]byte{ + "/3,01": logChunk(t, second.Add(-500*time.Millisecond).UnixNano()), + "/3,02": logChunk(t, second.Add(100*time.Millisecond).UnixNano()), + "/3,03": logChunk(t, second.Add(1100*time.Millisecond).UnixNano()), + } + var fetchedLock sync.Mutex + fetched := map[string]int{} + volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fetchedLock.Lock() + fetched[r.URL.Path]++ + fetchedLock.Unlock() + w.Write(chunks[r.URL.Path]) + })) + defer volume.Close() + + file := func(name, fileId string) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{}, + Chunks: []*filer_pb.FileChunk{{FileId: fileId, Size: uint64(len(chunks["/"+fileId]))}}} + } + filer := &listingFiler{volumeUrl: strings.TrimPrefix(volume.URL, "http://"), entries: []*filer_pb.Entry{ + {Name: topic.PartitionFenceName, Attributes: &filer_pb.FuseAttributes{}}, + file("2026-11-30-10-00-04", "3,01"), + file(topic.LogFileName(second, 5), "3,02"), + file(topic.LogFileName(second.Add(time.Second), 9), "3,03"), + }} + sort.Slice(filer.entries, func(i, j int) bool { return filer.entries[i].Name < filer.entries[j].Name }) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, filer) + go server.Serve(listener) + defer server.Stop() + client := listingFilerClient{address: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port)} + + read := GenLogOnDiskReadFunc(client, topic.NewTopic("test", "t"), topic.Partition{RingSize: 2520, RangeStop: 2520, UnixTimeNs: 1}) + var got []int64 + _, _, err = read(log_buffer.NewMessagePosition(second.Add(-10*time.Second).UnixNano(), -2), second.Add(500*time.Millisecond).UnixNano(), func(logEntry *filer_pb.LogEntry) (bool, error) { + got = append(got, logEntry.TsNs) + return false, nil + }) + if err != nil { + t.Fatal(err) + } + want := []int64{second.Add(-500 * time.Millisecond).UnixNano(), second.Add(100 * time.Millisecond).UnixNano()} + if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] { + t.Errorf("read %v, want %v", got, want) + } + fetchedLock.Lock() + defer fetchedLock.Unlock() + if fetched["/3,03"] != 0 { + t.Error("read a file starting after the stop second") + } +} diff --git a/weed/mq/metadata_constants.go b/weed/mq/metadata_constants.go index 31f86c9108..f80a4a7fa1 100644 --- a/weed/mq/metadata_constants.go +++ b/weed/mq/metadata_constants.go @@ -16,4 +16,9 @@ const ( // Source file tracking for parquet deduplication ExtendedAttrSources = "sources" // JSON-encoded list of source log files + + // Partition fence metadata + ExtendedAttrFenceWriter = "writer" // address of the broker holding the partition's fence + ExtendedAttrFenceEpoch = "epoch" // decimal assignment epoch the fence was taken for + ExtendedAttrFenceSealed = "sealed" // "true" once the partition takes no more writes ) diff --git a/weed/mq/pub_balancer/allocate.go b/weed/mq/pub_balancer/allocate.go index f6af60c6b8..4837b6a12a 100644 --- a/weed/mq/pub_balancer/allocate.go +++ b/weed/mq/pub_balancer/allocate.go @@ -104,6 +104,7 @@ func pickBrokersExcluded(brokers []string, count int, excludedLeadBroker string, // EnsureAssignmentsToActiveBrokers moves leaders and followers off inactive brokers. A leader // moves only when a live replacement exists, and a follower is never its own leader. +// Every leader change, including the first, bumps the assignment's epoch. func EnsureAssignmentsToActiveBrokers(activeBrokers cmap.ConcurrentMap[string, *BrokerStats], followerCount int, assignments []*mq_pb.BrokerPartitionAssignment) (hasChanges bool) { glog.V(4).Infof("EnsureAssignmentsToActiveBrokers: activeBrokers: %v, followerCount: %d, assignments: %v", activeBrokers.Count(), followerCount, assignments) @@ -136,6 +137,10 @@ func EnsureAssignmentsToActiveBrokers(activeBrokers cmap.ConcurrentMap[string, * } } if leader != assignment.LeaderBroker || follower != assignment.FollowerBroker { + // The epoch fences the old leader's flushes, so it moves only with the leader. + if leader != "" && (assignment.LeaderBroker == "" || !pb.ServerAddress(leader).Equals(pb.ServerAddress(assignment.LeaderBroker))) { + assignment.Epoch++ + } assignment.LeaderBroker, assignment.FollowerBroker = leader, follower hasChanges = true } diff --git a/weed/mq/pub_balancer/allocate_test.go b/weed/mq/pub_balancer/allocate_test.go index e29463830f..7baa9a6eb4 100644 --- a/weed/mq/pub_balancer/allocate_test.go +++ b/weed/mq/pub_balancer/allocate_test.go @@ -246,3 +246,34 @@ func TestEnsureAssignmentsLeavesLiveAssignmentsAlone(t *testing.T) { assignment := &mq_pb.BrokerPartitionAssignment{LeaderBroker: "localhost:1", FollowerBroker: "localhost:2"} assert.False(t, EnsureAssignmentsToActiveBrokers(brokerSet("localhost:1", "localhost:2", "localhost:3"), 1, []*mq_pb.BrokerPartitionAssignment{assignment})) } + +func TestAllocatedAssignmentsStartAtEpochOne(t *testing.T) { + for _, assignment := range AllocateTopicPartitions(brokerSet("localhost:1", "localhost:2"), 4) { + assert.Equal(t, int64(1), assignment.Epoch) + } + for _, assignment := range AllocateTopicPartitions(brokerSet(), 2) { + assert.Equal(t, "", assignment.LeaderBroker) + assert.Equal(t, int64(0), assignment.Epoch) + } +} + +func TestEnsureAssignmentsBumpsEpochOnlyWithTheLeader(t *testing.T) { + assignment := &mq_pb.BrokerPartitionAssignment{LeaderBroker: "localhost:1", FollowerBroker: "localhost:9", Epoch: 3} + assert.True(t, EnsureAssignmentsToActiveBrokers(brokerSet("localhost:1", "localhost:2"), 1, []*mq_pb.BrokerPartitionAssignment{assignment})) + assert.Equal(t, "localhost:2", assignment.FollowerBroker) + assert.Equal(t, int64(3), assignment.Epoch, "a follower change keeps the epoch") + + assert.True(t, EnsureAssignmentsToActiveBrokers(brokerSet("localhost:2"), 1, []*mq_pb.BrokerPartitionAssignment{assignment})) + assert.Equal(t, "localhost:2", assignment.LeaderBroker) + assert.Equal(t, int64(4), assignment.Epoch) + + sameBroker := &mq_pb.BrokerPartitionAssignment{LeaderBroker: "localhost:1", Epoch: 2} + EnsureAssignmentsToActiveBrokers(brokerSet("localhost:1.18001"), 1, []*mq_pb.BrokerPartitionAssignment{sameBroker}) + assert.Equal(t, int64(2), sameBroker.Epoch, "re-spelling the same leader's address keeps the epoch") + + unassigned := &mq_pb.BrokerPartitionAssignment{} + EnsureAssignmentsToActiveBrokers(brokerSet(), 1, []*mq_pb.BrokerPartitionAssignment{unassigned}) + assert.Equal(t, int64(0), unassigned.Epoch) + assert.True(t, EnsureAssignmentsToActiveBrokers(brokerSet("localhost:1"), 1, []*mq_pb.BrokerPartitionAssignment{unassigned})) + assert.Equal(t, int64(1), unassigned.Epoch) +} diff --git a/weed/mq/topic/local_manager.go b/weed/mq/topic/local_manager.go index 2b68bd94ba..9c2e0721c3 100644 --- a/weed/mq/topic/local_manager.go +++ b/weed/mq/topic/local_manager.go @@ -212,20 +212,17 @@ func (manager *LocalTopicManager) RemoveTopic(topic Topic) { manager.topics.Remove(topic.String()) } -// RemoveLocalPartition retires a partition, or reports false once Shutdown has -// started, which then retires it from its own snapshot. -func (manager *LocalTopicManager) RemoveLocalPartition(topic Topic, partition Partition) (removed bool) { +// RemoveLocalPartition retires p if it is still registered, so a copy that has +// replaced it stays. It reports false once Shutdown has started, which then +// retires p from its own snapshot. +func (manager *LocalTopicManager) RemoveLocalPartition(topic Topic, p *LocalPartition) (removed bool) { manager.stopMu.RLock() defer manager.stopMu.RUnlock() - if manager.stopped { + if manager.stopped || p == nil { return false } localTopic, ok := manager.topics.Get(topic.String()) - if !ok { - return false - } - p := localTopic.removePartition(partition) - if p == nil { + if !ok || !localTopic.removePartition(p) { return false } manager.retire(p) diff --git a/weed/mq/topic/local_manager_test.go b/weed/mq/topic/local_manager_test.go index 99572f095a..d60c34973b 100644 --- a/weed/mq/topic/local_manager_test.go +++ b/weed/mq/topic/local_manager_test.go @@ -150,7 +150,7 @@ func TestShutdownWaitsForDrainedPartitions(t *testing.T) { if err := p.LogBuffer.AddDataToBuffer([]byte("k"), []byte("v"), time.Now().UnixNano()); err != nil { t.Fatal(err) } - if !manager.RemoveLocalPartition(tp, partition) { + if !manager.RemoveLocalPartition(tp, p) { t.Fatal("partition not removed") } @@ -173,7 +173,7 @@ func TestRemoveAfterShutdownStarts(t *testing.T) { manager.AddLocalPartition(tp, NewLocalPartition(partition, 3600, nil, nil)) manager.Shutdown() - if manager.RemoveLocalPartition(tp, partition) { + if manager.RemoveLocalPartition(tp, manager.GetLocalPartition(tp, partition)) { t.Fatal("removed a partition after Shutdown started") } } @@ -186,3 +186,26 @@ func TestPartitionShutdownTwiceWithSubscriber(t *testing.T) { p.Shutdown() p.Shutdown() } + +// A client of a replaced copy removing that copy on its way out leaves the +// replacement registered. +func TestRemovingAReplacedPartitionKeepsTheReplacement(t *testing.T) { + manager := NewLocalTopicManager() + tp := NewTopic("test", "replaced") + partition := Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520} + old := NewLocalPartition(partition, 3600, nil, nil) + manager.AddLocalPartition(tp, old) + if !manager.RemoveLocalPartition(tp, old) { + t.Fatal("partition not removed") + } + replacement := NewLocalPartition(partition, 3600, nil, nil) + defer replacement.Shutdown() + manager.AddLocalPartition(tp, replacement) + + if manager.RemoveLocalPartition(tp, old) { + t.Error("removed the replaced copy twice") + } + if manager.GetLocalPartition(tp, partition) != replacement { + t.Error("the replaced copy's removal took its replacement") + } +} diff --git a/weed/mq/topic/local_partition.go b/weed/mq/topic/local_partition.go index f03bca2f5d..8973b821b7 100644 --- a/weed/mq/topic/local_partition.go +++ b/weed/mq/topic/local_partition.go @@ -31,6 +31,9 @@ type LocalPartition struct { Publishers *LocalPartitionPublishers Subscribers *LocalPartitionSubscribers + // held while this broker leads the partition; nil on a follower + Fence *PartitionFence + publishFolloweMeStream mq_pb.SeaweedMessaging_PublishFollowMeClient followerGrpcConnection *grpc.ClientConn Follower string @@ -67,6 +70,11 @@ func NewLocalPartition(partition Partition, logFlushInterval int, logFlushFn log return lp } +// IsFenced reports that another broker took the partition's fence, so this one must stop serving it. +func (p *LocalPartition) IsFenced() bool { + return p.Fence != nil && p.Fence.IsLost() +} + func (p *LocalPartition) Publish(message *mq_pb.DataMessage) error { if err := p.LogBuffer.AddToBuffer(message); err != nil { return fmt.Errorf("failed to add message to log buffer: %w", err) diff --git a/weed/mq/topic/local_topic.go b/weed/mq/topic/local_topic.go index 6cb37885b3..2765307c62 100644 --- a/weed/mq/topic/local_topic.go +++ b/weed/mq/topic/local_topic.go @@ -34,23 +34,17 @@ func (localTopic *LocalTopic) findPartition(partition Partition) *LocalPartition glog.V(4).Infof("No matching partition found for %s", partition.String()) return nil } -func (localTopic *LocalTopic) removePartition(partition Partition) *LocalPartition { +func (localTopic *LocalTopic) removePartition(p *LocalPartition) bool { localTopic.partitionLock.Lock() defer localTopic.partitionLock.Unlock() - foundPartitionIndex := -1 for i, localPartition := range localTopic.Partitions { - if localPartition.Partition.LogicalEquals(partition) { - foundPartitionIndex = i - break + if localPartition == p { + localTopic.Partitions = append(localTopic.Partitions[:i], localTopic.Partitions[i+1:]...) + return true } } - if foundPartitionIndex == -1 { - return nil - } - removed := localTopic.Partitions[foundPartitionIndex] - localTopic.Partitions = append(localTopic.Partitions[:foundPartitionIndex], localTopic.Partitions[foundPartitionIndex+1:]...) - return removed + return false } func (localTopic *LocalTopic) addPartition(localPartition *LocalPartition) { localTopic.partitionLock.Lock() diff --git a/weed/mq/topic/log_file_name.go b/weed/mq/topic/log_file_name.go new file mode 100644 index 0000000000..ef02a15640 --- /dev/null +++ b/weed/mq/topic/log_file_name.go @@ -0,0 +1,31 @@ +package topic + +import ( + "fmt" + "strconv" + "strings" + "time" +) + +// LogFileName names a flushed window by its start second, then its first offset, +// so names sort by time and then by offset. +func LogFileName(startTime time.Time, minOffset int64) string { + return fmt.Sprintf("%s.%020d", startTime.UTC().Format(TIME_FORMAT), max(minOffset, 0)) +} + +// LogFileTimePrefix is the start-second part of a log file name, which may carry an offset suffix. +func LogFileTimePrefix(name string) string { + return name[:min(len(name), len(TIME_FORMAT))] +} + +// ParseLogFileTime reads the start second of a log file named with or without an offset suffix. +func ParseLogFileTime(name string) (time.Time, error) { + prefix := LogFileTimePrefix(name) + if suffix := name[len(prefix):]; suffix != "" { + digits, dotted := strings.CutPrefix(suffix, ".") + if _, err := strconv.ParseUint(digits, 10, 64); !dotted || err != nil { + return time.Time{}, fmt.Errorf("not a log file name: %q", name) + } + } + return time.Parse(TIME_FORMAT, prefix) +} diff --git a/weed/mq/topic/log_file_name_test.go b/weed/mq/topic/log_file_name_test.go new file mode 100644 index 0000000000..b9fc248c75 --- /dev/null +++ b/weed/mq/topic/log_file_name_test.go @@ -0,0 +1,50 @@ +package topic + +import ( + "sort" + "testing" + "time" +) + +func TestLogFileNamesSortByTimeThenOffset(t *testing.T) { + second := time.Date(2026, 11, 30, 10, 0, 5, 0, time.UTC) + if got, want := LogFileName(second, 200), "2026-11-30-10-00-05.00000000000000000200"; got != want { + t.Fatalf("LogFileName = %q, want %q", got, want) + } + ordered := []string{ + PartitionFenceName, + "2026-11-30-10-00-04", + LogFileName(second.Add(-time.Second), 9999), + "2026-11-30-10-00-05", + LogFileName(second, 9), + LogFileName(second, 10), + LogFileName(second, 100000000000), + LogFileName(second.Add(time.Second), 0), + } + names := append([]string(nil), ordered...) + sort.Sort(sort.Reverse(sort.StringSlice(names))) + sort.Strings(names) + for i := range ordered { + if names[i] != ordered[i] { + t.Fatalf("sorted %v, want %v", names, ordered) + } + } +} + +func TestParseLogFileTimeAcceptsBothNamings(t *testing.T) { + second := time.Date(2026, 11, 30, 10, 0, 5, 0, time.UTC) + for _, name := range []string{"2026-11-30-10-00-05", LogFileName(second, 0), LogFileName(second, 123456)} { + got, err := ParseLogFileTime(name) + if err != nil || !got.Equal(second) { + t.Errorf("ParseLogFileTime(%q) = %v, %v", name, got, err) + } + if prefix := LogFileTimePrefix(name); prefix != "2026-11-30-10-00-05" { + t.Errorf("LogFileTimePrefix(%q) = %q", name, prefix) + } + } + for _, name := range []string{PartitionFenceName, "checkpoint.offset", "2026-11-30-10-00-05.parquet", "2026-11-30-10-00-05.", "2026-11-30-10-00-05x1", "2026-11-30-10-00"} { + if _, err := ParseLogFileTime(name); err == nil { + t.Errorf("ParseLogFileTime(%q) parsed a non-log file", name) + } + } +} diff --git a/weed/mq/topic/partition_fence.go b/weed/mq/topic/partition_fence.go new file mode 100644 index 0000000000..0b8b162bcb --- /dev/null +++ b/weed/mq/topic/partition_fence.go @@ -0,0 +1,29 @@ +package topic + +import ( + "sync/atomic" +) + +// PartitionFenceName is the partition directory entry naming the one broker allowed to write it. +const PartitionFenceName = ".fence" + +// PartitionFence is the fence this broker stored; every write requires its token unchanged. +type PartitionFence struct { + Path string + Epoch int64 + Token string + lost atomic.Bool +} + +func PartitionFencePath(t Topic, p Partition) string { + return PartitionDir(t, p) + "/" + PartitionFenceName +} + +// MarkLost records that another broker has taken the fence. +func (f *PartitionFence) MarkLost() { + f.lost.Store(true) +} + +func (f *PartitionFence) IsLost() bool { + return f.lost.Load() +} diff --git a/weed/pb/mq_broker.proto b/weed/pb/mq_broker.proto index 47e4aaa8c8..fd27411b0a 100644 --- a/weed/pb/mq_broker.proto +++ b/weed/pb/mq_broker.proto @@ -163,6 +163,7 @@ message BrokerPartitionAssignment { schema_pb.Partition partition = 1; string leader_broker = 2; string follower_broker = 3; + int64 epoch = 4; } message GetTopicConfigurationRequest { schema_pb.Topic topic = 1; diff --git a/weed/pb/mq_pb/mq_broker.pb.go b/weed/pb/mq_pb/mq_broker.pb.go index 6b5cf3c7f4..d537ab90bc 100644 --- a/weed/pb/mq_pb/mq_broker.pb.go +++ b/weed/pb/mq_pb/mq_broker.pb.go @@ -912,6 +912,7 @@ type BrokerPartitionAssignment struct { Partition *schema_pb.Partition `protobuf:"bytes,1,opt,name=partition,proto3" json:"partition,omitempty"` LeaderBroker string `protobuf:"bytes,2,opt,name=leader_broker,json=leaderBroker,proto3" json:"leader_broker,omitempty"` FollowerBroker string `protobuf:"bytes,3,opt,name=follower_broker,json=followerBroker,proto3" json:"follower_broker,omitempty"` + Epoch int64 `protobuf:"varint,4,opt,name=epoch,proto3" json:"epoch,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -967,6 +968,13 @@ func (x *BrokerPartitionAssignment) GetFollowerBroker() string { return "" } +func (x *BrokerPartitionAssignment) GetEpoch() int64 { + if x != nil { + return x.Epoch + } + return 0 +} + type GetTopicConfigurationRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Topic *schema_pb.Topic `protobuf:"bytes,1,opt,name=topic,proto3" json:"topic,omitempty"` @@ -4304,11 +4312,12 @@ const file_mq_broker_proto_rawDesc = "" + "\x05topic\x18\x01 \x01(\v2\x10.schema_pb.TopicR\x05topic\"\xaf\x01\n" + "\x1aLookupTopicBrokersResponse\x12&\n" + "\x05topic\x18\x01 \x01(\v2\x10.schema_pb.TopicR\x05topic\x12i\n" + - "\x1cbroker_partition_assignments\x18\x02 \x03(\v2'.messaging_pb.BrokerPartitionAssignmentR\x1abrokerPartitionAssignments\"\x9d\x01\n" + + "\x1cbroker_partition_assignments\x18\x02 \x03(\v2'.messaging_pb.BrokerPartitionAssignmentR\x1abrokerPartitionAssignments\"\xb3\x01\n" + "\x19BrokerPartitionAssignment\x122\n" + "\tpartition\x18\x01 \x01(\v2\x14.schema_pb.PartitionR\tpartition\x12#\n" + "\rleader_broker\x18\x02 \x01(\tR\fleaderBroker\x12'\n" + - "\x0ffollower_broker\x18\x03 \x01(\tR\x0efollowerBroker\"F\n" + + "\x0ffollower_broker\x18\x03 \x01(\tR\x0efollowerBroker\x12\x14\n" + + "\x05epoch\x18\x04 \x01(\x03R\x05epoch\"F\n" + "\x1cGetTopicConfigurationRequest\x12&\n" + "\x05topic\x18\x01 \x01(\v2\x10.schema_pb.TopicR\x05topic\"\xf0\x03\n" + "\x1dGetTopicConfigurationResponse\x12&\n" + diff --git a/weed/query/engine/engine.go b/weed/query/engine/engine.go index ec8707c0ca..81d2f462c4 100644 --- a/weed/query/engine/engine.go +++ b/weed/query/engine/engine.go @@ -1385,7 +1385,7 @@ func (e *SQLEngine) collectLiveLogFileNames(filerClient filer_pb.FilerClient, pa if entry != nil && !entry.IsDirectory { // Check if this is a log file (not a parquet file) fileName := entry.Name - if !strings.HasSuffix(fileName, ".parquet") && !strings.HasSuffix(fileName, ".metadata") { + if !strings.HasSuffix(fileName, ".parquet") && !strings.HasSuffix(fileName, ".metadata") && fileName != topic.PartitionFenceName { liveLogFiles = append(liveLogFiles, fileName) } } @@ -3881,7 +3881,7 @@ func (e *SQLEngine) computeLiveLogMinMax(partitionPath string, columnName string // Process each live log file err = filer_pb.ReadDirAllEntries(context.Background(), filerClient, util.FullPath(partitionPath), "", func(entry *filer_pb.Entry, isLast bool) error { // Skip parquet files and directories - if entry.IsDirectory || strings.HasSuffix(entry.Name, ".parquet") { + if entry.IsDirectory || strings.HasSuffix(entry.Name, ".parquet") || entry.Name == topic.PartitionFenceName { return nil } // Skip files that have been converted to parquet (deduplication) @@ -4094,11 +4094,7 @@ func (e *SQLEngine) convertLogEntryToRecordValue(logEntry *filer_pb.LogEntry) (* // extractTimestampFromFilename extracts timestamp from parquet filename // Format: YYYY-MM-DD-HH-MM-SS.parquet func (e *SQLEngine) extractTimestampFromFilename(filename string) int64 { - // Remove .parquet extension - filename = strings.TrimSuffix(filename, ".parquet") - - // Parse timestamp format: 2006-01-02-15-04-05 - t, err := time.Parse("2006-01-02-15-04-05", filename) + t, err := topic.ParseLogFileTime(strings.TrimSuffix(filename, ".parquet")) if err != nil { return 0 } @@ -4164,8 +4160,8 @@ func (e *SQLEngine) countLiveLogRowsExcludingParquetSources(ctx context.Context, totalRows := int64(0) err = filer_pb.ReadDirAllEntries(context.Background(), filerClient, util.FullPath(partitionPath), "", func(entry *filer_pb.Entry, isLast bool) error { - if entry.IsDirectory || strings.HasSuffix(entry.Name, ".parquet") { - return nil // Skip directories and parquet files + if entry.IsDirectory || strings.HasSuffix(entry.Name, ".parquet") || entry.Name == topic.PartitionFenceName { + return nil // Skip directories, parquet files, and the partition fence } // Skip files that have been converted to parquet diff --git a/weed/shell/command_mq_topic_truncate.go b/weed/shell/command_mq_topic_truncate.go index da4bd407aa..ed7becc2de 100644 --- a/weed/shell/command_mq_topic_truncate.go +++ b/weed/shell/command_mq_topic_truncate.go @@ -113,11 +113,12 @@ func (c *commandMqTopicTruncate) clearPartitionData(commandEnv *CommandEnv, part fileName := entry.Name - // Preserve configuration files + // Preserve configuration files and the partition fence if strings.HasSuffix(fileName, ".conf") || strings.HasSuffix(fileName, ".config") || fileName == "topic.conf" || - fileName == "partition.conf" { + fileName == "partition.conf" || + fileName == topic.PartitionFenceName { fmt.Fprintf(writer, " Preserving config file: %s\n", fileName) return nil }