mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
mq: resume inside the file holding the resume point, and start offset reads near the offset (#13209)
* mq logstore: resume a timestamp read inside the file that holds the resume point A disk read by timestamp listed the partition from the file named after the resume second and dropped every earlier name, so the file that started before that second but still held messages after the resume point was skipped and its remaining messages were never delivered. The reader now keeps a sparse index of the partition's log file names, starts listing at the last mark before the resume second, and reads the last file starting before that second along with every later one; its entries up to the resume point are already filtered by timestamp. This covers names with and without the offset suffix. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: read a log file's offset range in one place The disk reader decoded offset_min and offset_max inline in three places, by string literal rather than the mq constants. A single logFileOffsets helper now reads both, so the reader and the offset index added next agree on what a file records. No behavior change: the flush writes both attributes together. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: start an offset read at the indexed file holding the offset A disk read by offset listed the whole partition directory on every call and filtered the files by their offset ranges, so a lagging consumer paid for the partition's entire history on each read. The reader's sparse index of log file names now also keeps each mark's first offset, and an offset read lists from the last mark starting at or before its offset; offsets grow with names, so no earlier file can hold it. The index is extended by every listing past the last name it has seen, so after the first read a call lists at most one stride of files before its own plus the files after it. When no mark with an offset range is at or before the offset, as with files that record none, the read still lists from the first file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: never name a log file before the newest one in its partition A log file is named by its window's start second, taken from the writing broker's clock. A new leader whose clock is behind the previous one's wrote windows whose names sorted before older files holding lower offsets, so names no longer followed offsets. An offset read listing from an indexed file then skipped the new windows, and a read starting below such a file passed over it without notice; no reader-side check can see a file that sorts before where it starts listing. The partition fence now carries the newest log file time: the leader seeds it from the listing it already pages to continue the partition's offsets, which now also reports the newest log file name, legacy names included and compacted files, the fence and directories excluded. Each flush names its window no earlier than that time and advances it. Files sharing a second still sort by their min offset suffix. Timestamp reads resuming past the old leader's names now list such windows too, though entries timestamped before the resume point are still filtered out by timestamp. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound a log file by its first message time, not its name Now that a window can be named after a later second than its messages to keep names in offset order, the disk reader's stop filter, which dropped every file whose name second was after the stop time, missed windows whose messages were inside a time-bounded read. A flush now records the window's first message timestamp on the log file as ts_min, the attribute parquet files already carry, and the stop filter compares that when present. Files without it were written before names could be moved later, so their name still bounds them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: read every offset candidate, not a binary-searched suffix An offset read binary-searched its candidate files by offset range and dropped those before the hit, assuming name order matched offset order. A directory written under clock skew holds a file that sorts before files with lower offsets, and the search skipped it even on a full listing. The listing already drops files whose range ends before the offset, so in an ordered directory the search removed nothing but offset-less legacy files, which are filtered per entry anyway. The search is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: list from the start once a partition's names leave offset order An offset read lists from the indexed file starting at or before its offset, which is right only while names sort in offset order. Directories written under clock skew before log file names were kept ordered hold files sorting before files with lower offsets, and a read listing from a later mark passed over them. The index now remembers the highest offset it has seen in name order, and once a file starts below it the partition is unordered and every offset read lists from the first file, as before the index existed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq broker: name a takeover's file no earlier than the newest one stored A follower taking over named its file by its first entry's time, so a follower whose clock is behind its lost leader's wrote a name sorting before files holding lower offsets. It now takes the newest stored name from the listing it already reads for the high-water mark and names its file no earlier, as a leader's flush does. * mq: resume a timestamp read in every earlier file holding later messages A timestamp read kept only the last file sorting before the resume second, assuming names bound message times. A window named no earlier than the newest stored file can sort after a file it does not follow in time: a slow leader's window of older messages took that last place and the file before it, still holding messages after the resume point, was never read. A flush, and a follower's takeover write, now also record the window's last message time as ts_max, the attribute parquet files carry. Of the files sorting before the resume second, every one whose last message is at or after the resume time is read; files without it were named by their first message and keep the old rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: return the latest time a timestamp read delivered A timestamp read returned the last processed file's last message time as its position, and each chunk's result replaced the file's. Files are read in name order, and a slow leader's window can sort after a file holding later messages, so the position went back and the next read delivered those later messages again; a trailing chunk that delivered nothing also reset a file's time to zero. The position is now the highest time delivered across chunks and files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: deliver an offset read's files in offset order An offset read processed its candidate files in name order. In a partition written under clock skew a file sorts before files with lower offsets, so its entries were delivered first, and a reader taking only the first few entries, as the chunked offset read does, got the wrong ones. The files that record an offset range are now read in order of their first offset, each in a place one of them held, so files without a range keep their position. In an ordered partition this changes nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: list a timestamp resume from the start once a name was clamped A timestamp resume listed from the index's last mark before the resume second. Once a window is named later than its first message to keep names in offset order, many such windows can share one clamped second, and the marks among them sorted after an earlier file still holding messages past the resume point, so that file was never listed and never reached the check of its last message time. The index now notes a file whose name is later than its first message, and from then on a timestamp resume lists from the first file. Partitions without such a name keep using the index. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: start a timestamp resume at a mark bounded by message times A timestamp resume listed from the index's last mark sorting before the resume second, falling back to the first file once a clamped name was seen. That still assumed names bound earlier files' messages: windows whose messages overlap within one second, none of them clamped, could push a mark past an earlier file holding messages after the resume point, and the resume skipped it. Each mark now records the latest message time of every file sorting before it, from ts_max, or for a file without it the end of the next file's start second, since such files were named by their first message and ended before the next began. A resume starts at the last mark whose earlier files all end before the resume time, so the files it skips hold nothing it still has to deliver, whatever the names or clocks. The clamped-name flag is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: leave an older file unbounded when the next name was clamped A file without a recorded last message time was bounded by the end of the next file's start second, on the reasoning that it ended before the next began. When the next file is a slower leader's window clamped into that second, its name says nothing about when its messages, or the older file's, end; the older file was bounded too early, a later mark qualified, and a resume past it skipped its remaining messages. The next file now bounds it only when its name is not later than its first message; otherwise the older file stays unbounded, no mark after it qualifies, and a resume lists from before it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq logstore: fetch by offset through the log buffer over out-of-order names The out-of-order name tests drove the disk reader directly. A fetch goes through the log buffer's disk chunk on top of it, so this reads a few offsets at a time through ReadMessagesAtOffset over a partition whose names sort out of offset order, and checks each fetch returns its own offsets. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
746cae3895
commit
3beca7d956
15 files changed
+873
-157
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
||||
@@ -83,17 +84,20 @@ func (b *MessageQueueBroker) takeOverPartition(t topic.Topic, p topic.Partition,
|
||||
stopRenewing := b.keepFenceRenewed(fence)
|
||||
defer stopRenewing()
|
||||
// with the fence moved, nothing else adds to what is stored
|
||||
var highWaterMark int64
|
||||
var stored mq.OffsetRange
|
||||
if err := retryLogWrite(ctx, topic.PartitionDir(t, p), func() (err error) {
|
||||
_, highWaterMark, err = b.getOffsetRangeFromChunkMetadata(t, p)
|
||||
stored, err = b.getOffsetRangeFromChunkMetadata(t, p)
|
||||
return err
|
||||
}); err != nil {
|
||||
glog.Errorf("take over %v %v epoch %d: %v", t, p, init.Epoch, err)
|
||||
return
|
||||
}
|
||||
fence.NoteLogFileTime(stored.NewestLogFileTime())
|
||||
_, highWaterMark := stored.Bounds()
|
||||
held = dropStored(held, highWaterMark-1)
|
||||
if len(held) > 0 {
|
||||
var data []byte
|
||||
minTsNs, maxTsNs := held[0].TsNs, held[0].TsNs
|
||||
for _, entry := range held {
|
||||
encoded, err := entry.MarshalVT()
|
||||
if err != nil {
|
||||
@@ -102,10 +106,12 @@ func (b *MessageQueueBroker) takeOverPartition(t topic.Topic, p topic.Partition,
|
||||
}
|
||||
data = binary.BigEndian.AppendUint32(data, uint32(len(encoded)))
|
||||
data = append(data, encoded...)
|
||||
minTsNs, maxTsNs = min(minTsNs, entry.TsNs), max(maxTsNs, entry.TsNs)
|
||||
}
|
||||
first, last := held[0], held[len(held)-1]
|
||||
targetFile := topic.PartitionDir(t, p) + "/" + topic.LogFileName(time.Unix(0, first.TsNs), first.Offset)
|
||||
if err := b.writeLogFile(ctx, fence, targetFile, data, first.Offset, last.Offset); err != nil {
|
||||
startTime, stopTime := time.Unix(0, minTsNs).UTC(), time.Unix(0, maxTsNs).UTC()
|
||||
targetFile := topic.PartitionDir(t, p) + "/" + topic.LogFileName(fence.LogFileTime(startTime), first.Offset)
|
||||
if err := b.writeLogFile(ctx, fence, targetFile, startTime, stopTime, data, first.Offset, last.Offset); err != nil {
|
||||
glog.Errorf("take over %v %v epoch %d: store offsets %d-%d: %v", t, p, init.Epoch, first.Offset, last.Offset, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -14,10 +14,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,
|
||||
|
||||
@@ -55,6 +55,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 {
|
||||
@@ -166,6 +168,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()
|
||||
@@ -200,8 +210,14 @@ func (f *fencingFiler) putLogFile(start time.Time, minOffset, maxOffset int64, f
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -132,8 +132,8 @@ func TestLogStartStaysBelowAnUnrangedParquetFile(t *testing.T) {
|
||||
t.Errorf("log start %d after the purge, want 0: the parquet file still holds 50..99", lso)
|
||||
}
|
||||
|
||||
earliest, _, err := b.getOffsetRangeFromChunkMetadata(fenceTestTopic, fenceTestPartition)
|
||||
if err != nil || earliest != 0 {
|
||||
stored, err := b.getOffsetRangeFromChunkMetadata(fenceTestTopic, fenceTestPartition)
|
||||
if earliest, _ := stored.Bounds(); err != nil || earliest != 0 {
|
||||
t.Errorf("stored earliest offset %d, %v; want 0", earliest, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,3 +476,34 @@ func TestPairBrokenBeforeRegistrationEndsOnceRegistered(t *testing.T) {
|
||||
t.Fatal("ended generation still registered")
|
||||
}
|
||||
}
|
||||
|
||||
// A follower taking over names its file no earlier than the newest one stored, so
|
||||
// names keep offset order when its clock is behind its lost leader's.
|
||||
func TestTakeoverNamesSortAfterTheNewestStoredLogFile(t *testing.T) {
|
||||
f, follower := newFencingFiler(t)
|
||||
leaderAddr := "127.0.0.1:18888"
|
||||
fencePath := topic.PartitionFencePath(fenceTestTopic, fenceTestPartition)
|
||||
dir := topic.PartitionDir(fenceTestTopic, fenceTestPartition)
|
||||
f.put(fencePath, fenceAt(leaderAddr, "1", time.Now().Unix(), false))
|
||||
ahead := topic.LogFileName(time.Now().Add(time.Hour), 0)
|
||||
f.put(dir+"/"+ahead, &filer_pb.Entry{Name: ahead, Attributes: &filer_pb.FuseAttributes{}, Extended: rangeExtended(0, 4)})
|
||||
|
||||
var held []*filer_pb.LogEntry
|
||||
for offset := int64(0); offset < 10; offset++ {
|
||||
held = append(held, &filer_pb.LogEntry{TsNs: time.Now().UnixNano(), Key: []byte("k"), Data: []byte("v"), Offset: offset})
|
||||
}
|
||||
follower.takeOverPartition(fenceTestTopic, fenceTestPartition, &mq_pb.PublishFollowMeRequest_InitMessage{Epoch: 1, Leader: leaderAddr}, held)
|
||||
|
||||
var names []string
|
||||
f.mu.Lock()
|
||||
for path := range f.entries {
|
||||
if d, name := util.FullPath(path).DirAndName(); d == dir && name != topic.PartitionFenceName {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
f.mu.Unlock()
|
||||
sort.Strings(names)
|
||||
if len(names) != 2 || names[0] != ahead {
|
||||
t.Fatalf("stored %v, want the takeover's file after %s", names, ahead)
|
||||
}
|
||||
}
|
||||
@@ -233,14 +233,16 @@ func (b *MessageQueueBroker) ensureTopicActiveAssignments(t topic.Topic, conf *m
|
||||
}
|
||||
|
||||
// initializePartitionOffsetFromExistingData continues the partition's offsets above
|
||||
// what is already stored, and starts its log at the earliest stored offset. A
|
||||
// partition whose stored offsets cannot be read is not served.
|
||||
// what is already stored, starts its log at the earliest stored offset, 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 {
|
||||
var earliestOffset int64
|
||||
err := localPartition.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) {
|
||||
r, err := b.getOffsetRangeFromChunkMetadata(t, partition)
|
||||
localPartition.Fence.NoteLogFileTime(r.NewestLogFileTime())
|
||||
var highWaterMark int64
|
||||
var err error
|
||||
earliestOffset, highWaterMark, err = b.getOffsetRangeFromChunkMetadata(t, partition)
|
||||
earliestOffset, highWaterMark = r.Bounds()
|
||||
return highWaterMark - 1, err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -251,13 +253,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
|
||||
|
||||
@@ -32,13 +32,13 @@ 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 {
|
||||
ctx = context.Background()
|
||||
}
|
||||
if err := b.writeLogFile(ctx, fence, targetFile, buf, minOffset, maxOffset); err != nil {
|
||||
if err := b.writeLogFile(ctx, fence, targetFile, startTime, stopTime, 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))
|
||||
|
||||
@@ -29,9 +29,10 @@ func offsetRange(offsetArgs []int64) (minOffset, maxOffset int64, ok bool) {
|
||||
return minOffset, maxOffset, minOffset >= 0 && maxOffset >= minOffset
|
||||
}
|
||||
|
||||
// writeLogFile stores one window as a new file while fence is still the partition's fence.
|
||||
// writeLogFile stores one window, whose messages are from startTime to stopTime, 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 {
|
||||
func (b *MessageQueueBroker) writeLogFile(ctx context.Context, fence *topic.PartitionFence, targetFile string, startTime, stopTime time.Time, data []byte, offsetArgs ...int64) error {
|
||||
if fence == nil {
|
||||
return fmt.Errorf("%s: this broker holds no fence: %w", targetFile, errFenceLost)
|
||||
}
|
||||
@@ -66,12 +67,15 @@ func (b *MessageQueueBroker) writeLogFile(ctx context.Context, fence *topic.Part
|
||||
Gid: uint32(os.Getgid()),
|
||||
},
|
||||
}
|
||||
// the name may be later than the window's messages, so readers bound by time use these
|
||||
entry.Extended = map[string][]byte{
|
||||
mq.ExtendedAttrTimestampMin: binary.BigEndian.AppendUint64(nil, uint64(startTime.UnixNano())),
|
||||
mq.ExtendedAttrTimestampMax: binary.BigEndian.AppendUint64(nil, uint64(stopTime.UnixNano())),
|
||||
}
|
||||
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)),
|
||||
}
|
||||
entry.Extended[mq.ExtendedAttrOffsetMin] = binary.BigEndian.AppendUint64(nil, uint64(minOffset))
|
||||
entry.Extended[mq.ExtendedAttrOffsetMax] = binary.BigEndian.AppendUint64(nil, uint64(maxOffset))
|
||||
entry.Extended[mq.ExtendedAttrBufferStart] = binary.BigEndian.AppendUint64(nil, uint64(minOffset))
|
||||
}
|
||||
|
||||
condition := fenceTokenCondition(fence.Token())
|
||||
|
||||
@@ -5,17 +5,21 @@ 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"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_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"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestOffsetRangeIncludesFirstWindow(t *testing.T) {
|
||||
@@ -148,7 +152,7 @@ func TestFlushWritesOneFencedFilePerWindow(t *testing.T) {
|
||||
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} {
|
||||
for key, want := range map[string]uint64{mq.ExtendedAttrOffsetMin: 200, mq.ExtendedAttrOffsetMax: 399, mq.ExtendedAttrBufferStart: 200, mq.ExtendedAttrTimestampMin: uint64(start.UnixNano()), mq.ExtendedAttrTimestampMax: uint64(start.Add(time.Second).UnixNano())} {
|
||||
if got := written.Extended[key]; len(got) != 8 || binary.BigEndian.Uint64(got) != want {
|
||||
t.Errorf("%s = %v, want %d", key, got, want)
|
||||
}
|
||||
@@ -230,7 +234,7 @@ func TestFlushStopsWhenTheFenceIsTaken(t *testing.T) {
|
||||
|
||||
func TestFollowerCannotWriteWithoutAFence(t *testing.T) {
|
||||
f, b := newFencingFiler(t)
|
||||
err := b.writeLogFile(context.Background(), nil, topic.PartitionDir(fenceTestTopic, fenceTestPartition)+"/x", []byte("data"))
|
||||
err := b.writeLogFile(context.Background(), nil, topic.PartitionDir(fenceTestTopic, fenceTestPartition)+"/x", time.Now(), time.Now(), []byte("data"))
|
||||
if !errors.Is(err, errFenceLost) {
|
||||
t.Fatalf("wrote without a fence: %v", err)
|
||||
}
|
||||
@@ -238,3 +242,86 @@ 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, &mq_pb.BrokerPartitionAssignment{Partition: fenceTestPartition.ToPbPartition(), Epoch: 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)
|
||||
}
|
||||
|
||||
// the window's name is later than its messages, which a time-bounded read still finds
|
||||
var got []int64
|
||||
if _, _, err := read(log_buffer.NewMessagePosition(now.Add(-time.Minute).UnixNano(), -2), now.Add(time.Millisecond).UnixNano(), func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
got = append(got, logEntry.Offset)
|
||||
return false, nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(got, []int64{2, 3}) {
|
||||
t.Errorf("time-bounded read %v, want the new leader's window", got)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
package logstore
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq"
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
@@ -18,8 +23,152 @@ import (
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// logFileIndexStride is how many log files one logFileIndex mark stands for.
|
||||
const logFileIndexStride = 64
|
||||
|
||||
// logFileIndex marks every logFileIndexStride-th log file name of a partition, so a
|
||||
// read can list from near its position instead of from the first file.
|
||||
type logFileIndex struct {
|
||||
sync.Mutex
|
||||
marks []logFileMark
|
||||
lastName string
|
||||
unmarked int
|
||||
// maxOffset is the highest offset recorded so far; a later name starting below it
|
||||
// makes the partition unordered, as files written under clock skew can be
|
||||
maxOffset int64
|
||||
unordered bool
|
||||
// lastTsNs bounds the messages of every file added; while open, the last file added
|
||||
// records no last message time and is bounded only once the next file is seen
|
||||
lastTsNs int64
|
||||
open bool
|
||||
}
|
||||
|
||||
type logFileMark struct {
|
||||
name string
|
||||
minOffset int64
|
||||
hasOffsets bool
|
||||
// earlierTsNs bounds the messages of every file sorting before this one
|
||||
earlierTsNs int64
|
||||
}
|
||||
|
||||
// add records log files in listing order, as listed from a mark or from the start.
|
||||
func (x *logFileIndex) add(entries []*filer_pb.Entry) {
|
||||
x.Lock()
|
||||
defer x.Unlock()
|
||||
for _, entry := range entries {
|
||||
if entry.Name <= x.lastName {
|
||||
continue
|
||||
}
|
||||
minOffset, maxOffset, hasOffsets := logFileOffsets(entry)
|
||||
if hasOffsets {
|
||||
x.unordered = x.unordered || minOffset < x.maxOffset
|
||||
x.maxOffset = max(x.maxOffset, maxOffset)
|
||||
}
|
||||
if x.open {
|
||||
// a file without its last message time was named by its first and ended before the
|
||||
// next file began, which only a next name not moved later than its messages tells
|
||||
nameEndTsNs := int64(math.MaxInt64)
|
||||
if nameTime, err := topic.ParseLogFileTime(entry.Name); err == nil {
|
||||
if firstTsNs, ok := logFileTsNs(entry, mq.ExtendedAttrTimestampMin); !ok || firstTsNs >= nameTime.UnixNano() {
|
||||
nameEndTsNs = nameTime.Add(time.Second).UnixNano() - 1
|
||||
}
|
||||
}
|
||||
x.lastTsNs, x.open = max(x.lastTsNs, nameEndTsNs), false
|
||||
}
|
||||
if len(x.marks) == 0 || x.unmarked >= logFileIndexStride-1 {
|
||||
x.marks = append(x.marks, logFileMark{name: entry.Name, minOffset: minOffset, hasOffsets: hasOffsets, earlierTsNs: x.lastTsNs})
|
||||
x.unmarked = 0
|
||||
} else {
|
||||
x.unmarked++
|
||||
}
|
||||
if lastTsNs, ok := logFileTsNs(entry, mq.ExtendedAttrTimestampMax); ok {
|
||||
x.lastTsNs = max(x.lastTsNs, lastTsNs)
|
||||
} else {
|
||||
x.open = true
|
||||
}
|
||||
x.lastName = entry.Name
|
||||
}
|
||||
}
|
||||
|
||||
// markBefore is the last mark before which every file ends before tsNs, or "" for the
|
||||
// start, so a listing from it skips nothing at or after tsNs whatever the names say.
|
||||
func (x *logFileIndex) markBefore(tsNs int64) string {
|
||||
x.Lock()
|
||||
defer x.Unlock()
|
||||
if i := sort.Search(len(x.marks), func(i int) bool { return x.marks[i].earlierTsNs >= tsNs }); i > 0 {
|
||||
return x.marks[i-1].name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// markAtOffset is the last marked file starting at or before offset, or "" for the start.
|
||||
// Where offsets grow with names, no earlier file can hold offset, including one with no
|
||||
// offset range; an unordered partition is always read from the start.
|
||||
func (x *logFileIndex) markAtOffset(offset int64) string {
|
||||
x.Lock()
|
||||
defer x.Unlock()
|
||||
if x.unordered {
|
||||
return ""
|
||||
}
|
||||
for i := len(x.marks) - 1; i >= 0; i-- {
|
||||
if m := x.marks[i]; m.hasOffsets && m.minOffset <= offset {
|
||||
return m.name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// logFileOffsets is the offset range a log file records, if it records one.
|
||||
func logFileOffsets(entry *filer_pb.Entry) (minOffset, maxOffset int64, ok bool) {
|
||||
minBytes, maxBytes := entry.Extended[mq.ExtendedAttrOffsetMin], entry.Extended[mq.ExtendedAttrOffsetMax]
|
||||
if len(minBytes) != 8 || len(maxBytes) != 8 {
|
||||
return 0, 0, false
|
||||
}
|
||||
return int64(binary.BigEndian.Uint64(minBytes)), int64(binary.BigEndian.Uint64(maxBytes)), true
|
||||
}
|
||||
|
||||
// logFileStartsAfter reports whether a log file's first message is after stopTime. A name
|
||||
// can be later than that message; files recording no first message time were named by it.
|
||||
func logFileStartsAfter(entry *filer_pb.Entry, stopTime time.Time) bool {
|
||||
if firstTsNs, ok := logFileTsNs(entry, mq.ExtendedAttrTimestampMin); ok {
|
||||
return firstTsNs > stopTime.UnixNano()
|
||||
}
|
||||
return topic.LogFileTimePrefix(entry.Name) > stopTime.UTC().Format(topic.TIME_FORMAT)
|
||||
}
|
||||
|
||||
// sortByOffset orders the files recording an offset range by their first offset within
|
||||
// the places they hold, so files without a range stay where they are. Names follow
|
||||
// offsets except where files were written under clock skew.
|
||||
func sortByOffset(files []*filer_pb.Entry) {
|
||||
var places []int
|
||||
var ranged []*filer_pb.Entry
|
||||
for i, file := range files {
|
||||
if _, _, ok := logFileOffsets(file); ok {
|
||||
places = append(places, i)
|
||||
ranged = append(ranged, file)
|
||||
}
|
||||
}
|
||||
slices.SortStableFunc(ranged, func(a, b *filer_pb.Entry) int {
|
||||
aMin, _, _ := logFileOffsets(a)
|
||||
bMin, _, _ := logFileOffsets(b)
|
||||
return cmp.Compare(aMin, bMin)
|
||||
})
|
||||
for i, place := range places {
|
||||
files[place] = ranged[i]
|
||||
}
|
||||
}
|
||||
|
||||
// logFileTsNs is the message time a log file records under key, if it records one.
|
||||
func logFileTsNs(entry *filer_pb.Entry, key string) (int64, bool) {
|
||||
if b := entry.Extended[key]; len(b) == 8 {
|
||||
return int64(binary.BigEndian.Uint64(b)), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p topic.Partition) log_buffer.LogReadFromDiskFuncType {
|
||||
partitionDir := topic.PartitionDir(t, p)
|
||||
index := &logFileIndex{}
|
||||
|
||||
// Create a small cache for recently-read file chunks (3 files, 60s TTL)
|
||||
// This significantly reduces Filer load when multiple consumers are catching up
|
||||
@@ -116,7 +265,10 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
continue
|
||||
}
|
||||
// Positive cache hit - data exists
|
||||
if processedTsNs, err = eachChunkFn(cachedData, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased); err != nil {
|
||||
var chunkTsNs int64
|
||||
chunkTsNs, err = eachChunkFn(cachedData, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased)
|
||||
processedTsNs = max(processedTsNs, chunkTsNs)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("eachChunkFn failed on cached data: %v", err)
|
||||
return
|
||||
}
|
||||
@@ -136,7 +288,10 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
// Store in cache for future reads
|
||||
fileCache.Put(cacheKey, data, startOffset)
|
||||
|
||||
if processedTsNs, err = eachChunkFn(data, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased); err != nil {
|
||||
var chunkTsNs int64
|
||||
chunkTsNs, err = eachChunkFn(data, eachLogEntryFn, starTsNs, stopTsNs, startOffset, isOffsetBased)
|
||||
processedTsNs = max(processedTsNs, chunkTsNs)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("eachChunkFn failed: %v", err)
|
||||
return
|
||||
}
|
||||
@@ -158,8 +313,9 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
}
|
||||
|
||||
return func(startPosition log_buffer.MessagePosition, stopTsNs int64, eachLogEntryFn log_buffer.EachLogEntryFuncType) (lastReadPosition log_buffer.MessagePosition, isDone bool, err error) {
|
||||
startFileName := startPosition.Time.UTC().Format(topic.TIME_FORMAT)
|
||||
resumeFileName := startPosition.Time.UTC().Format(topic.TIME_FORMAT)
|
||||
startTsNs := startPosition.Time.UnixNano()
|
||||
startFileName := index.markBefore(startTsNs)
|
||||
stopTime := time.Unix(0, stopTsNs)
|
||||
var processedTsNs int64
|
||||
|
||||
@@ -168,17 +324,16 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
var startOffset int64
|
||||
if isOffsetBased {
|
||||
startOffset = startPosition.Offset
|
||||
// CRITICAL FIX: For offset-based reads, ignore startFileName (which is based on Time)
|
||||
// and list all files from the beginning to find the right offset
|
||||
startFileName = ""
|
||||
startFileName = index.markAtOffset(startOffset)
|
||||
glog.V(1).Infof("disk read start: topic=%s partition=%s startOffset=%d",
|
||||
t.Name, p, startOffset)
|
||||
}
|
||||
|
||||
// OPTIMIZATION: For offset-based reads, collect all files with their offset ranges first
|
||||
// Then use binary search to find the right file, and skip files that don't contain the offset
|
||||
// For offset-based reads, skip files whose offset range ends before the offset
|
||||
var candidateFiles []*filer_pb.Entry
|
||||
var foundStartFile bool
|
||||
var listed []*filer_pb.Entry
|
||||
var beforeResume *filer_pb.Entry
|
||||
|
||||
err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// First pass: collect all relevant files with their metadata
|
||||
@@ -194,7 +349,8 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
if strings.HasSuffix(entry.Name, ".offset") {
|
||||
return nil
|
||||
}
|
||||
if stopTsNs != 0 && topic.LogFileTimePrefix(entry.Name) > stopTime.UTC().Format(topic.TIME_FORMAT) {
|
||||
listed = append(listed, entry)
|
||||
if stopTsNs != 0 && logFileStartsAfter(entry, stopTime) {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -202,33 +358,33 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
if isOffsetBased {
|
||||
glog.V(3).Infof("found file %s", entry.Name)
|
||||
// Check if file has offset range metadata
|
||||
if minOffsetBytes, hasMin := entry.Extended["offset_min"]; hasMin && len(minOffsetBytes) == 8 {
|
||||
if maxOffsetBytes, hasMax := entry.Extended["offset_max"]; hasMax && len(maxOffsetBytes) == 8 {
|
||||
fileMinOffset := int64(binary.BigEndian.Uint64(minOffsetBytes))
|
||||
fileMaxOffset := int64(binary.BigEndian.Uint64(maxOffsetBytes))
|
||||
if fileMinOffset, fileMaxOffset, ok := logFileOffsets(entry); ok {
|
||||
// Skip files that don't contain our offset range
|
||||
if startOffset > fileMaxOffset {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Skip files that don't contain our offset range
|
||||
if startOffset > fileMaxOffset {
|
||||
return nil
|
||||
}
|
||||
|
||||
// If we haven't found the start file yet, check if this file contains it
|
||||
if !foundStartFile && startOffset >= fileMinOffset && startOffset <= fileMaxOffset {
|
||||
foundStartFile = true
|
||||
}
|
||||
// If we haven't found the start file yet, check if this file contains it
|
||||
if !foundStartFile && startOffset >= fileMinOffset && startOffset <= fileMaxOffset {
|
||||
foundStartFile = true
|
||||
}
|
||||
}
|
||||
// If file doesn't have offset metadata, include it (might be old format)
|
||||
} else {
|
||||
// Timestamp-based filtering
|
||||
topicName := t.Name
|
||||
if dotIndex := strings.LastIndex(topicName, "."); dotIndex != -1 {
|
||||
topicName = topicName[dotIndex+1:]
|
||||
}
|
||||
isSystemTopic := strings.HasPrefix(topicName, "_")
|
||||
if !isSystemTopic && startPosition.Time.Unix() > 86400 && entry.Name < startPosition.Time.UTC().Format(topic.TIME_FORMAT) {
|
||||
} else if entry.Name < resumeFileName {
|
||||
lastTsNs, recorded := logFileTsNs(entry, mq.ExtendedAttrTimestampMax)
|
||||
if !recorded {
|
||||
// such a file is named by its first message, so of these only the last can still hold the resume point
|
||||
beforeResume = entry
|
||||
return nil
|
||||
}
|
||||
// a name moved later bounds nothing, so its file's own last message decides
|
||||
if lastTsNs < startTsNs {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if beforeResume != nil {
|
||||
candidateFiles = append(candidateFiles, beforeResume)
|
||||
beforeResume = nil
|
||||
}
|
||||
|
||||
// Add file to candidates for processing
|
||||
@@ -243,6 +399,13 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
glog.Errorf("failed to list directory %s: %v", partitionDir, err)
|
||||
return
|
||||
}
|
||||
if beforeResume != nil {
|
||||
candidateFiles = append(candidateFiles, beforeResume)
|
||||
}
|
||||
index.add(listed)
|
||||
if isOffsetBased {
|
||||
sortByOffset(candidateFiles)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("found %d candidate files for topic=%s partition=%s offset=%d",
|
||||
len(candidateFiles), t.Name, p, startOffset)
|
||||
@@ -252,45 +415,6 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
return startPosition, isDone, nil
|
||||
}
|
||||
|
||||
// OPTIMIZATION: For offset-based reads with many files, use binary search to find start file
|
||||
if isOffsetBased && len(candidateFiles) > 10 {
|
||||
// Binary search to find the first file that might contain our offset
|
||||
left, right := 0, len(candidateFiles)-1
|
||||
startIdx := 0
|
||||
|
||||
for left <= right {
|
||||
mid := (left + right) / 2
|
||||
entry := candidateFiles[mid]
|
||||
|
||||
if minOffsetBytes, hasMin := entry.Extended["offset_min"]; hasMin && len(minOffsetBytes) == 8 {
|
||||
if maxOffsetBytes, hasMax := entry.Extended["offset_max"]; hasMax && len(maxOffsetBytes) == 8 {
|
||||
fileMinOffset := int64(binary.BigEndian.Uint64(minOffsetBytes))
|
||||
fileMaxOffset := int64(binary.BigEndian.Uint64(maxOffsetBytes))
|
||||
|
||||
if startOffset < fileMinOffset {
|
||||
// Our offset is before this file, search left
|
||||
right = mid - 1
|
||||
} else if startOffset > fileMaxOffset {
|
||||
// Our offset is after this file, search right
|
||||
left = mid + 1
|
||||
startIdx = left
|
||||
} else {
|
||||
// Found the file containing our offset
|
||||
startIdx = mid
|
||||
break
|
||||
}
|
||||
} else {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Process files starting from the found index
|
||||
candidateFiles = candidateFiles[startIdx:]
|
||||
}
|
||||
|
||||
// Second pass: process the filtered files
|
||||
// CRITICAL: For offset-based reads, process ALL candidate files in one call
|
||||
// This prevents multiple ReadFromDiskFn calls with 1.127s overhead each
|
||||
@@ -302,7 +426,8 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
return lastReadPosition, isDone, err
|
||||
}
|
||||
if fileTsNs > 0 {
|
||||
processedTsNs = fileTsNs
|
||||
// files sort by name, which a slow leader's window can hold out of time order
|
||||
processedTsNs = max(processedTsNs, fileTsNs)
|
||||
filesProcessed++
|
||||
}
|
||||
|
||||
@@ -310,11 +435,8 @@ func GenLogOnDiskReadFunc(filerClient filer_pb.FilerClient, t topic.Topic, p top
|
||||
// We need to continue reading ALL files to avoid multiple disk read calls
|
||||
if isOffsetBased {
|
||||
// Extract the last offset from the file's extended attributes
|
||||
if maxOffsetBytes, hasMax := entry.Extended["offset_max"]; hasMax && len(maxOffsetBytes) == 8 {
|
||||
fileMaxOffset := int64(binary.BigEndian.Uint64(maxOffsetBytes))
|
||||
if fileMaxOffset > lastProcessedOffset {
|
||||
lastProcessedOffset = fileMaxOffset
|
||||
}
|
||||
if _, fileMaxOffset, ok := logFileOffsets(entry); ok && fileMaxOffset > lastProcessedOffset {
|
||||
lastProcessedOffset = fileMaxOffset
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,15 +2,19 @@ package logstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"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"
|
||||
@@ -24,15 +28,38 @@ import (
|
||||
|
||||
type listingFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
sync.Mutex
|
||||
entries []*filer_pb.Entry
|
||||
volumeUrl string
|
||||
listed int
|
||||
}
|
||||
|
||||
func (f *listingFiler) add(entries ...*filer_pb.Entry) {
|
||||
f.Lock()
|
||||
defer f.Unlock()
|
||||
f.entries = append(f.entries, entries...)
|
||||
sort.Slice(f.entries, func(i, j int) bool { return f.entries[i].Name < f.entries[j].Name })
|
||||
}
|
||||
|
||||
func (f *listingFiler) takeListed() int {
|
||||
f.Lock()
|
||||
defer f.Unlock()
|
||||
listed := f.listed
|
||||
f.listed = 0
|
||||
return listed
|
||||
}
|
||||
|
||||
func (f *listingFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
|
||||
for _, entry := range f.entries {
|
||||
f.Lock()
|
||||
entries := slices.Clone(f.entries)
|
||||
f.Unlock()
|
||||
for _, entry := range entries {
|
||||
if entry.Name < req.StartFromFileName || (!req.InclusiveStartFrom && entry.Name == req.StartFromFileName) {
|
||||
continue
|
||||
}
|
||||
f.Lock()
|
||||
f.listed++
|
||||
f.Unlock()
|
||||
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -59,9 +86,17 @@ func (c listingFilerClient) AdjustedUrl(location *filer_pb.Location) string { re
|
||||
func (c listingFilerClient) GetDataCenter() string { return "" }
|
||||
|
||||
func logChunk(t *testing.T, tsNs ...int64) []byte {
|
||||
var buf []byte
|
||||
var entries []*filer_pb.LogEntry
|
||||
for _, ts := range tsNs {
|
||||
data, err := proto.Marshal(&filer_pb.LogEntry{TsNs: ts, Key: []byte("k")})
|
||||
entries = append(entries, &filer_pb.LogEntry{TsNs: ts, Key: []byte("k")})
|
||||
}
|
||||
return encodeLogEntries(t, entries...)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -72,37 +107,39 @@ func logChunk(t *testing.T, tsNs ...int64) []byte {
|
||||
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])
|
||||
type chunkServer struct {
|
||||
*httptest.Server
|
||||
sync.Mutex
|
||||
chunks map[string][]byte
|
||||
fetched map[string]int
|
||||
}
|
||||
|
||||
func serveChunks(t *testing.T, chunks map[string][]byte) *chunkServer {
|
||||
c := &chunkServer{chunks: chunks, fetched: map[string]int{}}
|
||||
c.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
c.Lock()
|
||||
c.fetched[r.URL.Path]++
|
||||
c.Unlock()
|
||||
w.Write(c.chunks[r.URL.Path])
|
||||
}))
|
||||
defer volume.Close()
|
||||
t.Cleanup(c.Close)
|
||||
return c
|
||||
}
|
||||
|
||||
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 })
|
||||
func (c *chunkServer) fetchCount(fileId string) int {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
return c.fetched["/"+fileId]
|
||||
}
|
||||
|
||||
func (c *chunkServer) file(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(c.chunks["/"+fileId]))}}}
|
||||
}
|
||||
|
||||
func serveFiler(t *testing.T, volume *chunkServer, entries ...*filer_pb.Entry) (*listingFiler, listingFilerClient) {
|
||||
filer := &listingFiler{volumeUrl: strings.TrimPrefix(volume.URL, "http://")}
|
||||
filer.add(entries...)
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -110,25 +147,375 @@ func TestReadFromDiskKeepsAFileStartingInTheStopSecond(t *testing.T) {
|
||||
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)}
|
||||
t.Cleanup(server.Stop)
|
||||
return filer, 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) {
|
||||
func testPartitionReader(client listingFilerClient) log_buffer.LogReadFromDiskFuncType {
|
||||
return GenLogOnDiskReadFunc(client, topic.NewTopic("test", "t"), topic.Partition{RingSize: 2520, RangeStop: 2520, UnixTimeNs: 1})
|
||||
}
|
||||
|
||||
func readTimestamps(t *testing.T, read log_buffer.LogReadFromDiskFuncType, start log_buffer.MessagePosition, stopTsNs int64) (got []int64) {
|
||||
t.Helper()
|
||||
if _, _, err := read(start, stopTsNs, func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
got = append(got, logEntry.TsNs)
|
||||
return false, nil
|
||||
})
|
||||
if err != nil {
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
// 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)
|
||||
volume := serveChunks(t, 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()),
|
||||
})
|
||||
_, client := serveFiler(t, volume,
|
||||
&filer_pb.Entry{Name: topic.PartitionFenceName, Attributes: &filer_pb.FuseAttributes{}},
|
||||
volume.file("2026-11-30-10-00-04", "3,01"),
|
||||
volume.file(topic.LogFileName(second, 5), "3,02"),
|
||||
volume.file(topic.LogFileName(second.Add(time.Second), 9), "3,03"),
|
||||
)
|
||||
|
||||
got := readTimestamps(t, testPartitionReader(client), log_buffer.NewMessagePosition(second.Add(-10*time.Second).UnixNano(), -2), second.Add(500*time.Millisecond).UnixNano())
|
||||
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] {
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("read %v, want %v", got, want)
|
||||
}
|
||||
fetchedLock.Lock()
|
||||
defer fetchedLock.Unlock()
|
||||
if fetched["/3,03"] != 0 {
|
||||
if volume.fetchCount("3,03") != 0 {
|
||||
t.Error("read a file starting after the stop second")
|
||||
}
|
||||
}
|
||||
|
||||
// A window from a leader with a slower clock is named no earlier than the file before
|
||||
// it, so it can sort after that file within the resume second's predecessors while
|
||||
// holding older messages; the earlier file's later messages are still read.
|
||||
func TestReadFromDiskResumesPastAClampedName(t *testing.T) {
|
||||
second := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
|
||||
timeAttrs := func(minTs, maxTs time.Time, minOffset, maxOffset int64) map[string][]byte {
|
||||
return map[string][]byte{
|
||||
mq.ExtendedAttrTimestampMin: binary.BigEndian.AppendUint64(nil, uint64(minTs.UnixNano())),
|
||||
mq.ExtendedAttrTimestampMax: binary.BigEndian.AppendUint64(nil, uint64(maxTs.UnixNano())),
|
||||
mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(minOffset)),
|
||||
mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(maxOffset)),
|
||||
}
|
||||
}
|
||||
slow := second.Add(-time.Minute)
|
||||
volume := serveChunks(t, map[string][]byte{
|
||||
"/3,01": logChunk(t, second.UnixNano(), second.Add(4*time.Second).UnixNano()),
|
||||
"/3,02": logChunk(t, slow.UnixNano()),
|
||||
})
|
||||
a := volume.file(topic.LogFileName(second, 0), "3,01")
|
||||
a.Extended = timeAttrs(second, second.Add(4*time.Second), 0, 1)
|
||||
b := volume.file(topic.LogFileName(second, 2), "3,02")
|
||||
b.Extended = timeAttrs(slow, slow, 2, 2)
|
||||
_, client := serveFiler(t, volume, a, b)
|
||||
|
||||
got := readTimestamps(t, testPartitionReader(client), log_buffer.NewMessagePosition(second.Add(2*time.Second).UnixNano(), -2), 0)
|
||||
if want := []int64{second.Add(4 * time.Second).UnixNano()}; !slices.Equal(got, want) {
|
||||
t.Errorf("resumed at 10:00:02, read %v, want %v", got, want)
|
||||
}
|
||||
if volume.fetchCount("3,02") != 0 {
|
||||
t.Error("read a file whose messages all precede the resume point")
|
||||
}
|
||||
}
|
||||
|
||||
// Enough windows sorting after an earlier file push the index's marks past it, while
|
||||
// it still holds messages after the resume point; a resume still reads it.
|
||||
func TestReadFromDiskResumesPastManyLaterSortingFiles(t *testing.T) {
|
||||
second := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
first time.Time
|
||||
// the earlier file predates recorded message times
|
||||
older bool
|
||||
}{
|
||||
{"names clamped to a slow leader's later second", second.Add(-time.Minute), false},
|
||||
{"messages overlapping in one second", second.Add(100 * time.Millisecond), false},
|
||||
{"names clamped after a file without its message times", second.Add(-time.Minute), true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
timeAttrs := func(minTs, maxTs time.Time) map[string][]byte {
|
||||
return map[string][]byte{
|
||||
mq.ExtendedAttrTimestampMin: binary.BigEndian.AppendUint64(nil, uint64(minTs.UnixNano())),
|
||||
mq.ExtendedAttrTimestampMax: binary.BigEndian.AppendUint64(nil, uint64(maxTs.UnixNano())),
|
||||
}
|
||||
}
|
||||
volume := serveChunks(t, map[string][]byte{"/3,01": logChunk(t, second.UnixNano(), second.Add(4*time.Second).UnixNano())})
|
||||
a := volume.file(topic.LogFileName(second, 0), "3,01")
|
||||
if tc.older {
|
||||
a.Name = second.Format(topic.TIME_FORMAT)
|
||||
} else {
|
||||
a.Extended = timeAttrs(second, second.Add(4*time.Second))
|
||||
}
|
||||
files := []*filer_pb.Entry{a}
|
||||
for i := range logFileIndexStride + 6 {
|
||||
ts := tc.first.Add(time.Duration(i) * time.Millisecond)
|
||||
fileId := fmt.Sprintf("3,1%03x", i)
|
||||
volume.chunks["/"+fileId] = logChunk(t, ts.UnixNano())
|
||||
file := volume.file(topic.LogFileName(second, int64(2+i)), fileId)
|
||||
file.Extended = timeAttrs(ts, ts)
|
||||
files = append(files, file)
|
||||
}
|
||||
_, client := serveFiler(t, volume, files...)
|
||||
read := testPartitionReader(client)
|
||||
readTimestamps(t, read, log_buffer.NewMessagePosition(second.Add(-time.Hour).UnixNano(), -2), 0)
|
||||
|
||||
got := readTimestamps(t, read, log_buffer.NewMessagePosition(second.Add(2*time.Second).UnixNano(), -2), 0)
|
||||
if want := []int64{second.Add(4 * time.Second).UnixNano()}; !slices.Equal(got, want) {
|
||||
t.Errorf("resumed at 10:00:02 with the partition indexed, read %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// When a slow leader's window sorts after a file holding later messages, the read
|
||||
// returns the latest time it delivered, so the next read does not deliver it again.
|
||||
func TestReadFromDiskReturnsTheLatestDeliveredTime(t *testing.T) {
|
||||
second := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
|
||||
at := func(ms int) time.Time { return second.Add(time.Duration(ms) * time.Millisecond) }
|
||||
timeAttrs := func(minTs, maxTs time.Time) map[string][]byte {
|
||||
return map[string][]byte{
|
||||
mq.ExtendedAttrTimestampMin: binary.BigEndian.AppendUint64(nil, uint64(minTs.UnixNano())),
|
||||
mq.ExtendedAttrTimestampMax: binary.BigEndian.AppendUint64(nil, uint64(maxTs.UnixNano())),
|
||||
}
|
||||
}
|
||||
volume := serveChunks(t, map[string][]byte{
|
||||
"/3,01": logChunk(t, at(0).UnixNano(), at(4000).UnixNano()),
|
||||
"/3,02": logChunk(t, at(-60000).UnixNano(), at(3000).UnixNano()),
|
||||
})
|
||||
a := volume.file(topic.LogFileName(second, 0), "3,01")
|
||||
a.Extended = timeAttrs(at(0), at(4000))
|
||||
b := volume.file(topic.LogFileName(second, 2), "3,02")
|
||||
b.Extended = timeAttrs(at(-60000), at(3000))
|
||||
_, client := serveFiler(t, volume, a, b)
|
||||
read := testPartitionReader(client)
|
||||
|
||||
var got []int64
|
||||
collect := func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
got = append(got, logEntry.TsNs)
|
||||
return false, nil
|
||||
}
|
||||
position, _, err := read(log_buffer.NewMessagePosition(at(2000).UnixNano(), -2), 0, collect)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := []int64{at(4000).UnixNano(), at(3000).UnixNano()}; !slices.Equal(got, want) {
|
||||
t.Fatalf("resumed at 10:00:02, read %v, want %v", got, want)
|
||||
}
|
||||
if position.Time.Before(at(4000)) {
|
||||
t.Errorf("returned position %v, before the delivered %v", position.Time, at(4000))
|
||||
}
|
||||
|
||||
got = nil
|
||||
if _, _, err := read(position, 0, collect); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Errorf("read from the returned position delivered %v again", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Resuming inside a window must read the rest of the file that started before the
|
||||
// resume second, and nothing from files that ended before it.
|
||||
func TestReadFromDiskResumesInsideAnEarlierFile(t *testing.T) {
|
||||
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
|
||||
at := func(ms int) int64 { return base.Add(time.Duration(ms) * time.Millisecond).UnixNano() }
|
||||
for _, legacy := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "offset names", true: "legacy names"}[legacy], func(t *testing.T) {
|
||||
name := func(sec int, minOffset int64) string {
|
||||
if legacy {
|
||||
return base.Add(time.Duration(sec) * time.Second).Format(topic.TIME_FORMAT)
|
||||
}
|
||||
return topic.LogFileName(base.Add(time.Duration(sec)*time.Second), minOffset)
|
||||
}
|
||||
volume := serveChunks(t, map[string][]byte{
|
||||
"/3,01": logChunk(t, at(2100), at(2900)),
|
||||
"/3,02": logChunk(t, at(4200), at(4800), at(5300), at(5600), at(6400)),
|
||||
"/3,03": logChunk(t, at(7100)),
|
||||
})
|
||||
_, client := serveFiler(t, volume,
|
||||
&filer_pb.Entry{Name: topic.PartitionFenceName, Attributes: &filer_pb.FuseAttributes{}},
|
||||
volume.file(name(2, 0), "3,01"),
|
||||
volume.file(name(4, 2), "3,02"),
|
||||
volume.file(name(7, 7), "3,03"),
|
||||
)
|
||||
read := testPartitionReader(client)
|
||||
|
||||
// once from cold and once with the reader having listed the partition before
|
||||
for range 2 {
|
||||
got := readTimestamps(t, read, log_buffer.NewMessagePosition(at(5000), -2), 0)
|
||||
if want := []int64{at(5300), at(5600), at(6400), at(7100)}; !slices.Equal(got, want) {
|
||||
t.Errorf("resumed at 5.0s, read %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
if volume.fetchCount("3,01") != 0 {
|
||||
t.Error("read a file that ended before the resume point")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// offsetLogFiles makes count log files of two offsets each, from file first on;
|
||||
// legacy files are named by their second alone and record no offset range.
|
||||
func offsetLogFiles(t *testing.T, volume *chunkServer, first, count int, legacy bool) (files []*filer_pb.Entry) {
|
||||
base := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC)
|
||||
for i := first; i < first+count; i++ {
|
||||
minOffset := int64(2 * i)
|
||||
start := base.Add(time.Duration(i) * time.Second)
|
||||
fileId := fmt.Sprintf("3,%04x", i)
|
||||
volume.Lock()
|
||||
volume.chunks["/"+fileId] = encodeLogEntries(t,
|
||||
&filer_pb.LogEntry{TsNs: start.UnixNano(), Offset: minOffset},
|
||||
&filer_pb.LogEntry{TsNs: start.Add(time.Millisecond).UnixNano(), Offset: minOffset + 1})
|
||||
volume.Unlock()
|
||||
if legacy {
|
||||
files = append(files, volume.file(start.Format(topic.TIME_FORMAT), fileId))
|
||||
continue
|
||||
}
|
||||
file := volume.file(topic.LogFileName(start, minOffset), fileId)
|
||||
file.Extended = map[string][]byte{
|
||||
mq.ExtendedAttrOffsetMin: binary.BigEndian.AppendUint64(nil, uint64(minOffset)),
|
||||
mq.ExtendedAttrOffsetMax: binary.BigEndian.AppendUint64(nil, uint64(minOffset+1)),
|
||||
}
|
||||
files = append(files, file)
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
func readOffsets(t *testing.T, read log_buffer.LogReadFromDiskFuncType, startOffset int64) (got []int64) {
|
||||
t.Helper()
|
||||
if _, _, err := read(log_buffer.NewMessagePositionFromOffset(startOffset), 0, func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
got = append(got, logEntry.Offset)
|
||||
return false, nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func offsetsFrom(from, to int64) (offsets []int64) {
|
||||
for o := from; o < to; o++ {
|
||||
offsets = append(offsets, o)
|
||||
}
|
||||
return offsets
|
||||
}
|
||||
|
||||
// After its first read lists the partition, a reader starts later offset reads
|
||||
// near the offset instead of listing every file again.
|
||||
func TestReadFromDiskByOffsetListsFromNearTheOffset(t *testing.T) {
|
||||
const files = 10 * logFileIndexStride
|
||||
volume := serveChunks(t, map[string][]byte{})
|
||||
filer, client := serveFiler(t, volume, offsetLogFiles(t, volume, 0, files, false)...)
|
||||
filer.add(&filer_pb.Entry{Name: topic.PartitionFenceName, Attributes: &filer_pb.FuseAttributes{}})
|
||||
read := testPartitionReader(client)
|
||||
|
||||
if got := readOffsets(t, read, 2*files-4); !slices.Equal(got, offsetsFrom(2*files-4, 2*files)) {
|
||||
t.Fatalf("cold read %v", got)
|
||||
}
|
||||
filer.takeListed()
|
||||
|
||||
if got := readOffsets(t, read, 2*files-3); !slices.Equal(got, offsetsFrom(2*files-3, 2*files)) {
|
||||
t.Errorf("read %v", got)
|
||||
}
|
||||
if listed := filer.takeListed(); listed > 2*logFileIndexStride {
|
||||
t.Errorf("listed %d entries to read the last file of %d", listed, files)
|
||||
}
|
||||
|
||||
filer.add(offsetLogFiles(t, volume, files, 3, false)...)
|
||||
if got := readOffsets(t, read, 2*files+1); !slices.Equal(got, offsetsFrom(2*files+1, 2*files+6)) {
|
||||
t.Errorf("read after more flushes %v", got)
|
||||
}
|
||||
if listed := filer.takeListed(); listed > 2*logFileIndexStride {
|
||||
t.Errorf("listed %d entries to read files flushed after the index was built", listed)
|
||||
}
|
||||
|
||||
if got := readOffsets(t, read, 5); !slices.Equal(got, offsetsFrom(5, 2*files+6)) {
|
||||
t.Errorf("read from an early offset returned %d offsets", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// Files that record no offset range are still read by offset.
|
||||
func TestReadFromDiskByOffsetReadsLegacyFiles(t *testing.T) {
|
||||
volume := serveChunks(t, map[string][]byte{})
|
||||
_, client := serveFiler(t, volume, append(offsetLogFiles(t, volume, 0, 3, true), offsetLogFiles(t, volume, 3, 2*logFileIndexStride, false)...)...)
|
||||
read := testPartitionReader(client)
|
||||
end := int64(2 * (3 + 2*logFileIndexStride))
|
||||
for range 2 {
|
||||
if got := readOffsets(t, read, 3); !slices.Equal(got, offsetsFrom(3, end)) {
|
||||
t.Errorf("read %d offsets from 3, want %d", len(got), end-3)
|
||||
}
|
||||
}
|
||||
if got := readOffsets(t, read, end-1); !slices.Equal(got, []int64{end - 1}) {
|
||||
t.Errorf("read %v from the last offset", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A directory written under clock skew holds a file sorting before files with
|
||||
// lower offsets; reading by offset still finds that file.
|
||||
func TestReadFromDiskByOffsetFindsAFileSortingBeforeLowerOffsets(t *testing.T) {
|
||||
const files = 2 * logFileIndexStride
|
||||
volume := serveChunks(t, map[string][]byte{})
|
||||
skewed := offsetLogFiles(t, volume, files, 1, false)[0]
|
||||
skewed.Name = topic.LogFileName(time.Date(2026, 11, 30, 9, 0, 0, 0, time.UTC), 2*files)
|
||||
_, client := serveFiler(t, volume, append(offsetLogFiles(t, volume, 0, files, false), skewed)...)
|
||||
read := testPartitionReader(client)
|
||||
|
||||
if got := readOffsets(t, read, 0); !slices.Equal(got, offsetsFrom(0, 2*files+2)) {
|
||||
t.Errorf("read %v from 0, want offsets 0 to %d in order", got[:min(len(got), 4)], 2*files+1)
|
||||
}
|
||||
if got := readOffsets(t, read, 2*files); !slices.Equal(got, offsetsFrom(2*files, 2*files+2)) {
|
||||
t.Errorf("read %v from the skewed file once the reader had listed the partition", got)
|
||||
}
|
||||
|
||||
// a reader taking only the first few entries, as a chunked read does
|
||||
var got []int64
|
||||
if _, _, err := read(log_buffer.NewMessagePositionFromOffset(0), 0, func(logEntry *filer_pb.LogEntry) (bool, error) {
|
||||
if len(got) == 3 {
|
||||
return true, nil
|
||||
}
|
||||
got = append(got, logEntry.Offset)
|
||||
return false, nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(got, []int64{0, 1, 2}) {
|
||||
t.Errorf("first three entries from 0 were %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A fetch goes through the log buffer's disk chunk on top of this reader; over a
|
||||
// partition whose names sort out of offset order it must still return each offset.
|
||||
func TestFetchByOffsetOverFilesSortingOutOfOffsetOrder(t *testing.T) {
|
||||
const files = 2 * logFileIndexStride
|
||||
volume := serveChunks(t, map[string][]byte{})
|
||||
skewed := offsetLogFiles(t, volume, files, 1, false)[0]
|
||||
skewed.Name = topic.LogFileName(time.Date(2026, 11, 30, 9, 0, 0, 0, time.UTC), 2*files)
|
||||
_, client := serveFiler(t, volume, append(offsetLogFiles(t, volume, 0, files, false), skewed)...)
|
||||
|
||||
lb := log_buffer.NewLogBuffer("test", time.Hour, nil, nil, func() {})
|
||||
defer lb.ShutdownLogBuffer()
|
||||
lb.ReadFromDiskFn = testPartitionReader(client)
|
||||
if err := lb.InitializeOffsetFromExistingData(func() (int64, error) { return 2*files + 1, nil }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, start := range []int64{0, 1, 2 * files, 2*files - 1} {
|
||||
messages, next, _, _, err := lb.ReadMessagesAtOffset(start, 3, 1<<20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got []int64
|
||||
for _, m := range messages {
|
||||
got = append(got, m.Offset)
|
||||
}
|
||||
want := offsetsFrom(start, min(start+3, 2*files+2))
|
||||
if !slices.Equal(got, want) || next != want[len(want)-1]+1 {
|
||||
t.Errorf("fetch at %d returned %v, next %d; want %v", start, got, next, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-9
@@ -6,15 +6,18 @@ import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"strings"
|
||||
"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
|
||||
// data files that record no range, which may hold offsets below every recorded one
|
||||
unrangedLog bool
|
||||
unrangedParquet [][]string
|
||||
@@ -41,11 +44,15 @@ func (r *OffsetRange) Add(entry *filer_pb.Entry) {
|
||||
r.unrangedLog = 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
|
||||
}
|
||||
if r.names == nil {
|
||||
r.names = make(map[string]bool)
|
||||
}
|
||||
@@ -65,6 +72,11 @@ 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
|
||||
}
|
||||
|
||||
func (r *OffsetRange) hasUnknownOffsets() bool {
|
||||
if r.unrangedLog {
|
||||
return true
|
||||
@@ -84,15 +96,10 @@ func (r *OffsetRange) hasUnknownOffsets() bool {
|
||||
|
||||
// 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 {
|
||||
r.Add(entry)
|
||||
return nil
|
||||
}, "", false, math.MaxInt32)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
earliestOffset, highWaterMark = r.Bounds()
|
||||
return
|
||||
return r, err
|
||||
}
|
||||
@@ -7,7 +7,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"
|
||||
@@ -76,6 +78,26 @@ func TestOffsetRangeWithUnrangedFiles(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 {
|
||||
@@ -123,11 +145,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)
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package topic
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PartitionFenceName is the partition directory entry naming the one broker allowed to write it.
|
||||
@@ -15,6 +16,9 @@ type PartitionFence struct {
|
||||
mu sync.Mutex
|
||||
token string
|
||||
lost atomic.Bool
|
||||
|
||||
logFileTimeLock sync.Mutex
|
||||
newestLogFileTime time.Time
|
||||
}
|
||||
|
||||
func NewPartitionFence(path string, epoch int64, token string) *PartitionFence {
|
||||
@@ -47,3 +51,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
|
||||
}
|
||||
Reference in new issue
Block a user