diff --git a/weed/mq/broker/broker_log_buffer_offset.go b/weed/mq/broker/broker_log_buffer_offset.go index ba1248b807..5e515dff89 100644 --- a/weed/mq/broker/broker_log_buffer_offset.go +++ b/weed/mq/broker/broker_log_buffer_offset.go @@ -12,10 +12,11 @@ func (b *MessageQueueBroker) GetPartitionOffsetInfoInternal(t topic.Topic, p top highWaterMark = localPartition.LogBuffer.GetOffset() activeSubscriptions = int64(localPartition.Subscribers.Size()) } else { - var err error - if earliestOffset, highWaterMark, err = b.getOffsetRangeFromChunkMetadata(t, p); err != nil { + r, err := b.getOffsetRangeFromChunkMetadata(t, p) + if err != nil { return nil, err } + earliestOffset, highWaterMark = r.Bounds() } return &PartitionOffsetInfo{ Topic: t, diff --git a/weed/mq/broker/broker_partition_fence_test.go b/weed/mq/broker/broker_partition_fence_test.go index 8fba7a0f4c..5fa9715e0b 100644 --- a/weed/mq/broker/broker_partition_fence_test.go +++ b/weed/mq/broker/broker_partition_fence_test.go @@ -52,6 +52,8 @@ type fencingFiler struct { uploads atomic.Int32 // uploads wait for it while set uploadGate chan struct{} + // the volume server answers reads of these file ids + chunks map[string][]byte } func (f *fencingFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error { @@ -154,6 +156,14 @@ func (f *fencingFiler) AssignVolume(context.Context, *filer_pb.AssignVolumeReque return &filer_pb.AssignVolumeResponse{FileId: "3,01637037d6", Location: &filer_pb.Location{Url: strings.TrimPrefix(f.volume.URL, "http://")}}, nil } +func (f *fencingFiler) 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: strings.TrimPrefix(f.volume.URL, "http://")}}} + } + return resp, nil +} + func (f *fencingFiler) transactions() []*filer_pb.ObjectTransactionRequest { f.mu.Lock() defer f.mu.Unlock() @@ -173,8 +183,14 @@ func (f *fencingFiler) put(path string, entry *filer_pb.Entry) { } func newFencingFiler(t *testing.T) (*fencingFiler, *MessageQueueBroker) { - f := &fencingFiler{entries: map[string]*filer_pb.Entry{}, outcome: map[string]*filer_pb.ObjectTransactionResponse{}} + f := &fencingFiler{entries: map[string]*filer_pb.Entry{}, outcome: map[string]*filer_pb.ObjectTransactionResponse{}, chunks: map[string][]byte{}} f.volume = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + f.mu.Lock() + defer f.mu.Unlock() + _, _ = w.Write(f.chunks[strings.TrimPrefix(r.URL.Path, "/")]) + return + } f.uploads.Add(1) if f.uploadGate != nil { <-f.uploadGate diff --git a/weed/mq/broker/broker_topic_conf_read_write.go b/weed/mq/broker/broker_topic_conf_read_write.go index b118052032..b89f772e99 100644 --- a/weed/mq/broker/broker_topic_conf_read_write.go +++ b/weed/mq/broker/broker_topic_conf_read_write.go @@ -230,10 +230,13 @@ func (b *MessageQueueBroker) ensureTopicActiveAssignments(t topic.Topic, conf *m } // initializePartitionOffsetFromExistingData continues the partition's offsets above -// what is already stored. A partition whose stored offsets cannot be read is not served. +// what is already stored, and names its windows no earlier than the newest stored +// log file. A partition whose stored offsets cannot be read is not served. func (b *MessageQueueBroker) initializePartitionOffsetFromExistingData(localPartition *topic.LocalPartition, t topic.Topic, partition topic.Partition) error { err := localPartition.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) { - _, highWaterMark, err := b.getOffsetRangeFromChunkMetadata(t, partition) + r, err := b.getOffsetRangeFromChunkMetadata(t, partition) + localPartition.Fence.NoteLogFileTime(r.NewestLogFileTime()) + _, highWaterMark := r.Bounds() return highWaterMark - 1, err }) if err != nil { @@ -243,13 +246,13 @@ func (b *MessageQueueBroker) initializePartitionOffsetFromExistingData(localPart } // getOffsetRangeFromChunkMetadata reads the offset range recorded on the partition's files. -func (b *MessageQueueBroker) getOffsetRangeFromChunkMetadata(t topic.Topic, partition topic.Partition) (earliestOffset int64, highWaterMark int64, err error) { +func (b *MessageQueueBroker) getOffsetRangeFromChunkMetadata(t topic.Topic, partition topic.Partition) (r mq.OffsetRange, err error) { if b.fca == nil { - return 0, 0, fmt.Errorf("filer client accessor not available") + return r, fmt.Errorf("filer client accessor not available") } err = b.fca.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { var scanErr error - earliestOffset, highWaterMark, scanErr = mq.ReadOffsetRange(context.Background(), client, topic.PartitionDir(t, partition)) + r, scanErr = mq.ReadOffsetRange(context.Background(), client, topic.PartitionDir(t, partition)) return scanErr }) return diff --git a/weed/mq/broker/broker_topic_partition_read_write.go b/weed/mq/broker/broker_topic_partition_read_write.go index de4005fb74..f935663a3e 100644 --- a/weed/mq/broker/broker_topic_partition_read_write.go +++ b/weed/mq/broker/broker_topic_partition_read_write.go @@ -32,7 +32,7 @@ func (b *MessageQueueBroker) genLogFlushFunc(t topic.Topic, p topic.Partition, f startTime, stopTime = startTime.UTC(), stopTime.UTC() - targetFile := fmt.Sprintf("%s/%s", partitionDir, topic.LogFileName(startTime, minOffset)) + targetFile := fmt.Sprintf("%s/%s", partitionDir, topic.LogFileName(fence.LogFileTime(startTime), minOffset)) ctx := b.flushCtx if ctx == nil { diff --git a/weed/mq/broker/broker_write_test.go b/weed/mq/broker/broker_write_test.go index 012ea2ae2e..8029da8c25 100644 --- a/weed/mq/broker/broker_write_test.go +++ b/weed/mq/broker/broker_write_test.go @@ -5,10 +5,12 @@ import ( "encoding/binary" "errors" "net" + "slices" "testing" "time" "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" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" @@ -16,6 +18,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/util/log_buffer" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/proto" ) func TestOffsetRangeIncludesFirstWindow(t *testing.T) { @@ -238,3 +241,74 @@ func TestFollowerCannotWriteWithoutAFence(t *testing.T) { t.Error("a refused write reached the filer") } } + +func encodeLogEntries(t *testing.T, entries ...*filer_pb.LogEntry) []byte { + var buf []byte + for _, entry := range entries { + data, err := proto.Marshal(entry) + if err != nil { + t.Fatal(err) + } + buf = binary.BigEndian.AppendUint32(buf, uint32(len(data))) + buf = append(buf, data...) + } + return buf +} + +// A leader whose clock is behind the previous leader's still names its windows to +// sort after every stored log file, so an offset read listing from a file it +// indexed earlier finds them. +func TestFlushNamesSortAfterTheNewestStoredLogFile(t *testing.T) { + f, b := newFencingFiler(t) + b.localTopicManager = topic.NewLocalTopicManager() + partitionDir := topic.PartitionDir(fenceTestTopic, fenceTestPartition) + ahead := time.Now().UTC().Add(time.Hour).Truncate(time.Second) + + stored := topic.LogFileName(ahead, 0) + storedChunk := encodeLogEntries(t, &filer_pb.LogEntry{TsNs: ahead.UnixNano(), Offset: 0}, &filer_pb.LogEntry{TsNs: ahead.UnixNano() + 1, Offset: 1}) + f.put(partitionDir+"/"+stored, &filer_pb.Entry{Name: stored, Attributes: &filer_pb.FuseAttributes{}, + Chunks: []*filer_pb.FileChunk{{FileId: "3,02", Size: uint64(len(storedChunk))}}, + Extended: map[string][]byte{ + mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, 0), + mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, 1), + }}) + // a compacted file sorting later does not hold back the names of new windows + compacted := topic.LogFileName(ahead.Add(time.Hour), 0) + ".parquet" + f.put(partitionDir+"/"+compacted, &filer_pb.Entry{Name: compacted, Attributes: &filer_pb.FuseAttributes{}}) + now := time.Now().UTC() + window := encodeLogEntries(t, &filer_pb.LogEntry{TsNs: now.UnixNano(), Offset: 2}, &filer_pb.LogEntry{TsNs: now.UnixNano() + 1, Offset: 3}) + f.mu.Lock() + f.chunks["3,02"] = storedChunk + f.chunks["3,01637037d6"] = window + f.mu.Unlock() + + read := logstore.GenLogOnDiskReadFunc(b, fenceTestTopic, fenceTestPartition) + readOffsets := func(from int64) (got []int64) { + t.Helper() + if _, _, err := read(log_buffer.NewMessagePositionFromOffset(from), 0, func(logEntry *filer_pb.LogEntry) (bool, error) { + got = append(got, logEntry.Offset) + return false, nil + }); err != nil { + t.Fatal(err) + } + return got + } + if got := readOffsets(0); !slices.Equal(got, []int64{0, 1}) { + t.Fatalf("read %v before the new leader flushed", got) + } + + localPartition, err := b.newLeaderPartition(fenceTestTopic, fenceTestPartition, 1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(localPartition.LogBuffer.ShutdownLogBuffer) + flush := b.genLogFlushFunc(fenceTestTopic, fenceTestPartition, localPartition.Fence) + flush(localPartition.LogBuffer, now, now.Add(time.Millisecond), window, 2, 3) + + if want := topic.LogFileName(ahead, 2); f.entry(partitionDir+"/"+want) == nil { + t.Errorf("no window named %s to sort after the stored %s", want, stored) + } + if got := readOffsets(2); !slices.Equal(got, []int64{2, 3}) { + t.Errorf("read %v from the new leader's window", got) + } +} diff --git a/weed/mq/kafka/integration/broker_client.go b/weed/mq/kafka/integration/broker_client.go index 51d3a69785..ba331bb368 100644 --- a/weed/mq/kafka/integration/broker_client.go +++ b/weed/mq/kafka/integration/broker_client.go @@ -317,8 +317,8 @@ func (bc *BrokerClient) getOffsetRangeFromChunkMetadata(topic string, partition partitionPath := fmt.Sprintf("%s/%s", versionPath, partitionDir) err = bc.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - var scanErr error - earliestOffset, highWaterMark, scanErr = mq.ReadOffsetRange(context.Background(), client, partitionPath) + r, scanErr := mq.ReadOffsetRange(context.Background(), client, partitionPath) + earliestOffset, highWaterMark = r.Bounds() return scanErr }) if err != nil { diff --git a/weed/mq/offset_range.go b/weed/mq/offset_range.go index bdda40fe33..418477807a 100644 --- a/weed/mq/offset_range.go +++ b/weed/mq/offset_range.go @@ -4,27 +4,38 @@ import ( "context" "encoding/binary" "math" + "time" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" ) -// OffsetRange accumulates the offset ranges recorded on a partition's files. +// OffsetRange accumulates the offset ranges recorded on a partition's files, +// and the newest start second a log file is named by. type OffsetRange struct { earliest, latest int64 hasEarliest, hasLatest bool + newestLogFileTime time.Time } -func (r *OffsetRange) Add(extended map[string][]byte) { - if b, ok := extended[ExtendedAttrOffsetMin]; ok && len(b) == 8 { +func (r *OffsetRange) Add(entry *filer_pb.Entry) { + if entry.IsDirectory { + return + } + if b, ok := entry.Extended[ExtendedAttrOffsetMin]; ok && len(b) == 8 { if v := int64(binary.BigEndian.Uint64(b)); !r.hasEarliest || v < r.earliest { r.earliest, r.hasEarliest = v, true } } - if b, ok := extended[ExtendedAttrOffsetMax]; ok && len(b) == 8 { + if b, ok := entry.Extended[ExtendedAttrOffsetMax]; ok && len(b) == 8 { if v := int64(binary.BigEndian.Uint64(b)); !r.hasLatest || v > r.latest { r.latest, r.hasLatest = v, true } } + // compacted files, the fence and other entries do not parse as log file names + if t, err := topic.ParseLogFileTime(entry.Name); err == nil && t.After(r.newestLogFileTime) { + r.newestLogFileTime = t + } } // Bounds is the earliest recorded offset and the offset after the latest, @@ -39,19 +50,17 @@ func (r *OffsetRange) Bounds() (earliestOffset, highWaterMark int64) { return } +// NewestLogFileTime is the latest start second naming a log file, zero when there is none. +func (r *OffsetRange) NewestLogFileTime() time.Time { + return r.newestLogFileTime +} + // ReadOffsetRange scans every file of a partition directory, not just the // filer's default listing page, for the offset ranges they record. -func ReadOffsetRange(ctx context.Context, client filer_pb.SeaweedFilerClient, partitionDir string) (earliestOffset, highWaterMark int64, err error) { - var r OffsetRange +func ReadOffsetRange(ctx context.Context, client filer_pb.SeaweedFilerClient, partitionDir string) (r OffsetRange, err error) { err = filer_pb.SeaweedList(ctx, client, partitionDir, "", func(entry *filer_pb.Entry, isLast bool) error { - if !entry.IsDirectory { - r.Add(entry.Extended) - } + r.Add(entry) return nil }, "", false, math.MaxInt32) - if err != nil { - return 0, 0, err - } - earliestOffset, highWaterMark = r.Bounds() - return + return r, err } diff --git a/weed/mq/offset_range_test.go b/weed/mq/offset_range_test.go index 62f55df5f9..012456faa3 100644 --- a/weed/mq/offset_range_test.go +++ b/weed/mq/offset_range_test.go @@ -6,7 +6,9 @@ import ( "fmt" "net" "testing" + "time" + "github.com/seaweedfs/seaweedfs/weed/mq/topic" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" @@ -34,7 +36,7 @@ func TestOffsetRangeBounds(t *testing.T) { } { var r OffsetRange for _, f := range tc.files { - r.Add(f) + r.Add(&filer_pb.Entry{Extended: f}) } if earliest, hwm := r.Bounds(); earliest != tc.earliest || hwm != tc.hwm { t.Errorf("%s: Bounds() = %d, %d; want %d, %d", tc.name, earliest, hwm, tc.earliest, tc.hwm) @@ -42,6 +44,26 @@ func TestOffsetRangeBounds(t *testing.T) { } } +// Log files count by their start second under either naming; compacted files, +// the fence and directories do not count. +func TestOffsetRangeNewestLogFileTime(t *testing.T) { + newest := time.Date(2026, 11, 30, 10, 0, 7, 0, time.UTC) + var r OffsetRange + for _, entry := range []*filer_pb.Entry{ + {Name: topic.PartitionFenceName}, + {Name: topic.LogFileName(newest.Add(-2*time.Second), 0)}, + {Name: newest.Format(topic.TIME_FORMAT)}, + {Name: topic.LogFileName(newest.Add(-time.Second), 9)}, + {Name: topic.LogFileName(newest.Add(time.Hour), 20) + ".parquet"}, + {Name: newest.Add(time.Hour).Format(topic.TIME_FORMAT), IsDirectory: true}, + } { + r.Add(entry) + } + if got := r.NewestLogFileTime(); !got.Equal(newest) { + t.Errorf("NewestLogFileTime() = %v, want %v", got, newest) + } +} + // listingFiler lists a directory the way the filer does: an unset limit means its // default page of 1000. type listingFiler struct { @@ -89,11 +111,11 @@ func TestReadOffsetRangeScansPastTheDefaultPage(t *testing.T) { } defer conn.Close() - earliest, hwm, err := ReadOffsetRange(context.Background(), filer_pb.NewSeaweedFilerClient(conn), "/topics/test/t/v1/0000-2520") + r, err := ReadOffsetRange(context.Background(), filer_pb.NewSeaweedFilerClient(conn), "/topics/test/t/v1/0000-2520") if err != nil { t.Fatal(err) } - if earliest != 0 || hwm != 25000 { + if earliest, hwm := r.Bounds(); earliest != 0 || hwm != 25000 { t.Fatalf("ReadOffsetRange = %d, %d; want 0, 25000", earliest, hwm) } } diff --git a/weed/mq/topic/partition_fence.go b/weed/mq/topic/partition_fence.go index 0b8b162bcb..e8a0689dd9 100644 --- a/weed/mq/topic/partition_fence.go +++ b/weed/mq/topic/partition_fence.go @@ -1,7 +1,9 @@ package topic import ( + "sync" "sync/atomic" + "time" ) // PartitionFenceName is the partition directory entry naming the one broker allowed to write it. @@ -13,6 +15,9 @@ type PartitionFence struct { Epoch int64 Token string lost atomic.Bool + + logFileTimeLock sync.Mutex + newestLogFileTime time.Time } func PartitionFencePath(t Topic, p Partition) string { @@ -27,3 +32,30 @@ func (f *PartitionFence) MarkLost() { func (f *PartitionFence) IsLost() bool { return f.lost.Load() } + +// NoteLogFileTime records a log file already named by start second t. +func (f *PartitionFence) NoteLogFileTime(t time.Time) { + if f == nil { + return + } + f.logFileTimeLock.Lock() + defer f.logFileTimeLock.Unlock() + if t.After(f.newestLogFileTime) { + f.newestLogFileTime = t + } +} + +// LogFileTime is the time to name a window starting at startTime by. It is never +// before a log file already named, so names keep offset order across leaders' clocks. +func (f *PartitionFence) LogFileTime(startTime time.Time) time.Time { + if f == nil { + return startTime + } + f.logFileTimeLock.Lock() + defer f.logFileTimeLock.Unlock() + if startTime.Before(f.newestLogFileTime) { + return f.newestLogFileTime + } + f.newestLogFileTime = startTime + return startTime +}