filer.sync: send log file chunk fids to clients for direct volume server reads (#8792)
* filer.sync: send log file chunk fids to clients for direct volume server reads Instead of the server reading persisted log files from volume servers, parsing entries, and streaming them over gRPC (serial bottleneck), clients that opt in via client_supports_metadata_chunks receive log file chunk references (fids) and read directly from volume servers in parallel. New proto messages: - LogFileChunkRef: chunk fids + timestamp + filer ID for one log file - SubscribeMetadataRequest.client_supports_metadata_chunks: client opt-in - SubscribeMetadataResponse.log_file_refs: server sends refs during backlog Server changes: - CollectLogFileRefs: lists log files and returns chunk refs without any volume server I/O (metadata-only operation) - SubscribeMetadata/SubscribeLocalMetadata: when client opts in, sends refs during persisted log phase, then falls back to normal streaming for in-memory events Client changes: - ReadLogFileRefs: reads log files from volume servers, parses entries, filters by path prefix, invokes processEventFn - MetadataFollowOption.LogFileReaderFn: factory for chunk readers, enables metadata chunks when non-nil - Both filer_pb_tail.go and meta_aggregator.go recv loops accumulate refs then process them at the disk→memory transition Backward compatible: old clients don't set the flag, get existing behavior. Ref: #8771 * filer.sync: merge entries across filers in timestamp order on client side ReadLogFileRefs now groups refs by filer ID and merges entries from multiple filers using a min-heap priority queue — the same algorithm the server uses in OrderedLogVisitor + LogEntryItemPriorityQueue. This ensures events are processed in correct timestamp order even when log files from different filers have interleaved timestamps. Single-filer case takes the fast path (no heap allocation). * filer.sync: integration tests for direct-read metadata chunks Three test categories: 1. Merge correctness (TestReadLogFileRefsMergeOrder): Verifies entries from 3 filers are delivered in strict timestamp order, matching the server-side OrderedLogVisitor guarantee. 2. Path filtering (TestReadLogFileRefsPathFilter): Verifies client-side path prefix filtering works correctly. 3. Throughput comparison (TestDirectReadVsServerSideThroughput): 3 filers × 7 files × 300 events = 6300 events, 2ms per file read: server-side: 6300 events 218ms 28,873 events/sec direct-read: 6300 events 51ms 123,566 events/sec (4.3x) parallel: 6300 events 17ms 378,628 events/sec (13.1x) Direct-read eliminates gRPC send overhead per event (4.3x). Parallel per-filer reading eliminates serial file I/O (13.1x). * filer.sync: parallel per-filer reads with prefetching in ReadLogFileRefs ReadLogFileRefs now has two levels of I/O overlap: 1. Cross-filer parallelism: one goroutine per filer reads its files concurrently. Entries feed into per-filer channels, merged by the main goroutine via min-heap (same ordering guarantee as the server's OrderedLogVisitor). 2. Within-filer prefetching: while the current file's entries are being consumed by the merge heap, the next file is already being read from the volume server in a background goroutine. Single-filer fast path avoids the heap and channels. Test results (3 filers × 7 files × 300 events, 2ms per file read): server-side sequential: 6300 events 212ms 29,760 events/sec parallel + prefetch: 6300 events 36ms 177,443 events/sec Speedup: 6.0x * filer.sync: address all review comments on metadata chunks PR Critical fixes: - sendLogFileRefs: bypass pipelinedSender, send directly on gRPC stream. Ref messages have TsNs=0 and were being incorrectly batched into the Events field by the adaptive batching logic, corrupting ref delivery. - readLogFileEntries: use io.ReadFull instead of reader.Read to prevent partial reads from corrupting size values or protobuf data. - Error handling: only skip chunk-not-found errors (matching server-side isChunkNotFoundError). Other I/O or decode failures are propagated so the follower can retry. High-priority fixes: - CollectLogFileRefs: remove incorrect +24h padding from stopTime. The extra day caused unnecessary log file refs to be collected. - Path filtering: ReadLogFileRefs now accepts PathFilter struct with PathPrefix, AdditionalPathPrefixes, and DirectoriesToWatch. Uses util.Join for path construction (avoids "//foo" on root). Excludes /.system/log/ internal entries. Matches server-side eachEventNotificationFn filtering logic. Medium-priority fixes: - CollectLogFileRefs: accept context.Context, propagate to ListDirectoryEntries calls for cancellation support. - NewChunkStreamReaderFromLookup: accept context.Context, propagate to doNewChunkStreamReader. Test fixes: - Check error returns from ReadLogFileRefs in all test call sites. --------- Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
@@ -391,12 +391,22 @@ message SubscribeMetadataRequest {
|
||||
int32 client_epoch = 9;
|
||||
repeated string directories = 10; // exact directory to watch
|
||||
bool client_supports_batching = 11; // client can unpack SubscribeMetadataResponse.events
|
||||
bool client_supports_metadata_chunks = 12; // client can read log file chunks from volume servers
|
||||
}
|
||||
message SubscribeMetadataResponse {
|
||||
string directory = 1;
|
||||
EventNotification event_notification = 2;
|
||||
int64 ts_ns = 3;
|
||||
repeated SubscribeMetadataResponse events = 4; // batch of additional events (backlog catch-up)
|
||||
repeated LogFileChunkRef log_file_refs = 5; // log file chunk refs for client direct-read
|
||||
}
|
||||
// A persisted log file that the client can read directly from volume servers.
|
||||
// The file format is: [4-byte size | protobuf LogEntry] repeated.
|
||||
// Each LogEntry.Data contains a marshaled SubscribeMetadataResponse.
|
||||
message LogFileChunkRef {
|
||||
repeated FileChunk chunks = 1; // chunk references (fids) to read from volume servers
|
||||
int64 file_ts_ns = 2; // minute-level timestamp of the log file
|
||||
string filer_id = 3; // filer signature suffix from log filename
|
||||
}
|
||||
|
||||
message TraverseBfsMetadataRequest {
|
||||
|
||||
@@ -40,6 +40,74 @@ func (f *Filer) collectPersistedLogBuffer(startPosition log_buffer.MessagePositi
|
||||
|
||||
}
|
||||
|
||||
// CollectLogFileRefs lists persisted log files and returns their chunk references
|
||||
// without reading any data from volume servers. The client can use the returned
|
||||
// fids to read log file data directly from volume servers in parallel.
|
||||
func (f *Filer) CollectLogFileRefs(ctx context.Context, startPosition log_buffer.MessagePosition, stopTsNs int64) (refs []*filer_pb.LogFileChunkRef, lastTsNs int64, err error) {
|
||||
if stopTsNs != 0 && startPosition.Time.UnixNano() > stopTsNs {
|
||||
return nil, 0, nil
|
||||
}
|
||||
|
||||
startDate := fmt.Sprintf("%04d-%02d-%02d", startPosition.Time.Year(), startPosition.Time.Month(), startPosition.Time.Day())
|
||||
startHourMinute := fmt.Sprintf("%02d-%02d", startPosition.Time.Hour(), startPosition.Time.Minute())
|
||||
var stopDate, stopHourMinute string
|
||||
if stopTsNs != 0 {
|
||||
stopTime := time.Unix(0, stopTsNs).UTC()
|
||||
stopDate = fmt.Sprintf("%04d-%02d-%02d", stopTime.Year(), stopTime.Month(), stopTime.Day())
|
||||
stopHourMinute = fmt.Sprintf("%02d-%02d", stopTime.Hour(), stopTime.Minute())
|
||||
}
|
||||
|
||||
dayEntries, _, listDayErr := f.ListDirectoryEntries(ctx, SystemLogDir, startDate, true, math.MaxInt32, "", "", "")
|
||||
if listDayErr != nil {
|
||||
return nil, 0, fmt.Errorf("fail to list log by day: %w", listDayErr)
|
||||
}
|
||||
|
||||
for _, dayEntry := range dayEntries {
|
||||
if stopDate != "" && strings.Compare(dayEntry.Name(), stopDate) > 0 {
|
||||
break
|
||||
}
|
||||
|
||||
hourMinuteEntries, _, listErr := f.ListDirectoryEntries(ctx, util.NewFullPath(SystemLogDir, dayEntry.Name()), "", false, math.MaxInt32, "", "", "")
|
||||
if listErr != nil {
|
||||
return nil, 0, fmt.Errorf("fail to list log %s: %w", dayEntry.Name(), listErr)
|
||||
}
|
||||
|
||||
for _, hmEntry := range hourMinuteEntries {
|
||||
hourMinute := util.FileNameBase(hmEntry.Name())
|
||||
if dayEntry.Name() == startDate && strings.Compare(hourMinute, startHourMinute) < 0 {
|
||||
continue
|
||||
}
|
||||
if dayEntry.Name() == stopDate && stopHourMinute != "" && strings.Compare(hourMinute, stopHourMinute) > 0 {
|
||||
break
|
||||
}
|
||||
|
||||
tsMinute := fmt.Sprintf("%s-%s", dayEntry.Name(), hourMinute)
|
||||
t, parseErr := time.Parse("2006-01-02-15-04", tsMinute)
|
||||
if parseErr != nil {
|
||||
glog.Errorf("failed to parse %s: %v", tsMinute, parseErr)
|
||||
continue
|
||||
}
|
||||
filerId := getFilerId(hmEntry.Name())
|
||||
if filerId == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
chunks := hmEntry.GetChunks()
|
||||
if len(chunks) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
refs = append(refs, &filer_pb.LogFileChunkRef{
|
||||
Chunks: chunks,
|
||||
FileTsNs: t.UnixNano(),
|
||||
FilerId: filerId,
|
||||
})
|
||||
lastTsNs = t.UnixNano()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (f *Filer) HasPersistedLogFiles(startPosition log_buffer.MessagePosition) (bool, error) {
|
||||
startDate := fmt.Sprintf("%04d-%02d-%02d", startPosition.Time.Year(), startPosition.Time.Month(), startPosition.Time.Day())
|
||||
dayEntries, _, listDayErr := f.ListDirectoryEntries(context.Background(), SystemLogDir, startDate, true, 1, "", "", "")
|
||||
|
||||
@@ -199,6 +199,12 @@ func (ma *MetaAggregator) doSubscribeToOneFiler(f *Filer, self pb.ServerAddress,
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
atomic.AddInt32(&ma.filer.UniqueFilerEpoch, 1)
|
||||
// Construct a log file reader that reads chunks via the peer filer's LookupVolume.
|
||||
lookupFn := LookupFn(filerClient{client})
|
||||
logFileReaderFn := func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
return NewChunkStreamReaderFromLookup(ctx, lookupFn, chunks), nil
|
||||
}
|
||||
|
||||
stream, err := client.SubscribeLocalMetadata(ctx, &filer_pb.SubscribeMetadataRequest{
|
||||
ClientName: "filer:" + string(self),
|
||||
PathPrefix: "/",
|
||||
@@ -206,6 +212,7 @@ func (ma *MetaAggregator) doSubscribeToOneFiler(f *Filer, self pb.ServerAddress,
|
||||
ClientId: ma.filer.UniqueFilerId,
|
||||
ClientEpoch: atomic.LoadInt32(&ma.filer.UniqueFilerEpoch),
|
||||
ClientSupportsBatching: true,
|
||||
ClientSupportsMetadataChunks: true,
|
||||
})
|
||||
if err != nil {
|
||||
glog.V(0).Infof("SubscribeLocalMetadata %v: %v", peer, err)
|
||||
@@ -222,6 +229,8 @@ func (ma *MetaAggregator) doSubscribeToOneFiler(f *Filer, self pb.ServerAddress,
|
||||
return nil
|
||||
}
|
||||
|
||||
var pendingRefs []*filer_pb.LogFileChunkRef
|
||||
|
||||
for {
|
||||
resp, listenErr := stream.Recv()
|
||||
if listenErr == io.EOF {
|
||||
@@ -232,9 +241,33 @@ func (ma *MetaAggregator) doSubscribeToOneFiler(f *Filer, self pb.ServerAddress,
|
||||
return listenErr
|
||||
}
|
||||
|
||||
// Accumulate log file chunk references
|
||||
if len(resp.LogFileRefs) > 0 {
|
||||
pendingRefs = append(pendingRefs, resp.LogFileRefs...)
|
||||
continue
|
||||
}
|
||||
|
||||
// Process accumulated refs (transition from disk to in-memory)
|
||||
if len(pendingRefs) > 0 {
|
||||
lastTs, readErr := pb.ReadLogFileRefs(pendingRefs, logFileReaderFn,
|
||||
lastTsNs, 0, pb.PathFilter{PathPrefix: "/"},
|
||||
func(event *filer_pb.SubscribeMetadataResponse) error {
|
||||
return processOne(event)
|
||||
})
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("read log file refs from %s: %w", peer, readErr)
|
||||
}
|
||||
if lastTs > 0 {
|
||||
lastTsNs = lastTs
|
||||
}
|
||||
pendingRefs = nil
|
||||
}
|
||||
|
||||
if resp.EventNotification != nil {
|
||||
if err := processOne(resp); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Process any additional batched events
|
||||
for _, batchedEvent := range resp.Events {
|
||||
if err := processOne(batchedEvent); err != nil {
|
||||
@@ -302,3 +335,22 @@ func (ma *MetaAggregator) updateOffset(f *Filer, peer pb.ServerAddress, peerSign
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// filerClient adapts a SeaweedFilerClient to the FilerClient interface
|
||||
// for use with LookupFn. Used by MetaAggregator to resolve volume IDs
|
||||
// on peer filers.
|
||||
type filerClient struct {
|
||||
client filer_pb.SeaweedFilerClient
|
||||
}
|
||||
|
||||
func (fc filerClient) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFilerClient) error) error {
|
||||
return fn(fc.client)
|
||||
}
|
||||
|
||||
func (fc filerClient) AdjustedUrl(location *filer_pb.Location) string {
|
||||
return location.Url
|
||||
}
|
||||
|
||||
func (fc filerClient) GetDataCenter() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -329,6 +329,12 @@ func NewChunkStreamReaderFromFiler(ctx context.Context, masterClient *wdclient.M
|
||||
return doNewChunkStreamReader(ctx, lookupFileIdFn, chunks)
|
||||
}
|
||||
|
||||
// NewChunkStreamReaderFromLookup creates a ChunkStreamReader from a lookup function.
|
||||
// Used by clients that already have a LookupFileIdFunctionType (e.g., from FilerSource).
|
||||
func NewChunkStreamReaderFromLookup(ctx context.Context, lookupFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
|
||||
return doNewChunkStreamReader(ctx, lookupFn, chunks)
|
||||
}
|
||||
|
||||
func NewChunkStreamReader(filerClient filer_pb.FilerClient, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
|
||||
|
||||
lookupFileIdFn := LookupFn(filerClient)
|
||||
|
||||
@@ -391,12 +391,22 @@ message SubscribeMetadataRequest {
|
||||
int32 client_epoch = 9;
|
||||
repeated string directories = 10; // exact directory to watch
|
||||
bool client_supports_batching = 11; // client can unpack SubscribeMetadataResponse.events
|
||||
bool client_supports_metadata_chunks = 12; // client can read log file chunks from volume servers
|
||||
}
|
||||
message SubscribeMetadataResponse {
|
||||
string directory = 1;
|
||||
EventNotification event_notification = 2;
|
||||
int64 ts_ns = 3;
|
||||
repeated SubscribeMetadataResponse events = 4; // batch of additional events (backlog catch-up)
|
||||
repeated LogFileChunkRef log_file_refs = 5; // log file chunk refs for client direct-read
|
||||
}
|
||||
// A persisted log file that the client can read directly from volume servers.
|
||||
// The file format is: [4-byte size | protobuf LogEntry] repeated.
|
||||
// Each LogEntry.Data contains a marshaled SubscribeMetadataResponse.
|
||||
message LogFileChunkRef {
|
||||
repeated FileChunk chunks = 1; // chunk references (fids) to read from volume servers
|
||||
int64 file_ts_ns = 2; // minute-level timestamp of the log file
|
||||
string filer_id = 3; // filer signature suffix from log filename
|
||||
}
|
||||
|
||||
message TraverseBfsMetadataRequest {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
382
weed/pb/filer_pb_direct_read.go
Normal file
382
weed/pb/filer_pb_direct_read.go
Normal file
@@ -0,0 +1,382 @@
|
||||
package pb
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// LogFileReaderFn creates an io.ReadCloser for a set of file chunks.
|
||||
type LogFileReaderFn func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error)
|
||||
|
||||
// PathFilter holds subscription path filtering parameters, matching the
|
||||
// server-side eachEventNotificationFn filtering logic.
|
||||
type PathFilter struct {
|
||||
PathPrefix string
|
||||
AdditionalPathPrefixes []string
|
||||
DirectoriesToWatch []string
|
||||
}
|
||||
|
||||
// ReadLogFileRefs reads log file data directly from volume servers using the
|
||||
// chunk references, merges entries from multiple filers in timestamp order
|
||||
// (same algorithm as the server's OrderedLogVisitor), applies path filtering,
|
||||
// and invokes processEventFn for each matching event.
|
||||
//
|
||||
// Filers are read in parallel (one goroutine per filer). Within each filer,
|
||||
// the next file is prefetched while the current file's entries are consumed.
|
||||
func ReadLogFileRefs(
|
||||
refs []*filer_pb.LogFileChunkRef,
|
||||
newReader LogFileReaderFn,
|
||||
startTsNs, stopTsNs int64,
|
||||
filter PathFilter,
|
||||
processEventFn ProcessMetadataFunc,
|
||||
) (lastTsNs int64, err error) {
|
||||
|
||||
if len(refs) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Group refs by filer ID, preserving order within each filer.
|
||||
perFiler := make(map[string][]*filer_pb.LogFileChunkRef)
|
||||
var filerOrder []string
|
||||
for _, ref := range refs {
|
||||
if len(ref.Chunks) == 0 {
|
||||
continue
|
||||
}
|
||||
if _, seen := perFiler[ref.FilerId]; !seen {
|
||||
filerOrder = append(filerOrder, ref.FilerId)
|
||||
}
|
||||
perFiler[ref.FilerId] = append(perFiler[ref.FilerId], ref)
|
||||
}
|
||||
|
||||
if len(filerOrder) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// Single filer fast path: no merge heap needed.
|
||||
if len(filerOrder) == 1 {
|
||||
return readFilerFilesWithPrefetch(perFiler[filerOrder[0]], newReader, startTsNs, stopTsNs, filter, processEventFn)
|
||||
}
|
||||
|
||||
// Multiple filers: read each in parallel with prefetching, merge via min-heap.
|
||||
return readMultiFilersMerged(filerOrder, perFiler, newReader, startTsNs, stopTsNs, filter, processEventFn)
|
||||
}
|
||||
|
||||
// readFilerFilesWithPrefetch reads files for a single filer, prefetching the
|
||||
// next file while processing entries from the current one.
|
||||
func readFilerFilesWithPrefetch(
|
||||
refs []*filer_pb.LogFileChunkRef,
|
||||
newReader LogFileReaderFn,
|
||||
startTsNs, stopTsNs int64,
|
||||
filter PathFilter,
|
||||
processEventFn ProcessMetadataFunc,
|
||||
) (lastTsNs int64, err error) {
|
||||
|
||||
type prefetchResult struct {
|
||||
entries []*filer_pb.LogEntry
|
||||
err error
|
||||
}
|
||||
|
||||
startPrefetch := func(ref *filer_pb.LogFileChunkRef) chan prefetchResult {
|
||||
ch := make(chan prefetchResult, 1)
|
||||
go func() {
|
||||
entries, readErr := readLogFileEntries(newReader, ref.Chunks, startTsNs, stopTsNs)
|
||||
ch <- prefetchResult{entries, readErr}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
|
||||
var pendingCh chan prefetchResult
|
||||
if len(refs) > 0 {
|
||||
pendingCh = startPrefetch(refs[0])
|
||||
}
|
||||
|
||||
for i, ref := range refs {
|
||||
result := <-pendingCh
|
||||
|
||||
// Start prefetching next file while we process current
|
||||
if i+1 < len(refs) {
|
||||
pendingCh = startPrefetch(refs[i+1])
|
||||
}
|
||||
|
||||
if result.err != nil {
|
||||
if isChunkNotFound(result.err) {
|
||||
glog.V(0).Infof("skip log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
|
||||
continue
|
||||
}
|
||||
return lastTsNs, fmt.Errorf("read log file filer=%s ts=%d: %w", ref.FilerId, ref.FileTsNs, result.err)
|
||||
}
|
||||
|
||||
for _, logEntry := range result.entries {
|
||||
lastTsNs, err = processOneLogEntry(logEntry, filter, processEventFn)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// readMultiFilersMerged reads files from multiple filers in parallel (one goroutine
|
||||
// per filer with prefetching), then merges entries in timestamp order via min-heap.
|
||||
func readMultiFilersMerged(
|
||||
filerOrder []string,
|
||||
perFiler map[string][]*filer_pb.LogFileChunkRef,
|
||||
newReader LogFileReaderFn,
|
||||
startTsNs, stopTsNs int64,
|
||||
filter PathFilter,
|
||||
processEventFn ProcessMetadataFunc,
|
||||
) (lastTsNs int64, err error) {
|
||||
|
||||
type filerStream struct {
|
||||
filerId string
|
||||
entryCh chan *filer_pb.LogEntry
|
||||
}
|
||||
|
||||
streams := make([]filerStream, len(filerOrder))
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i, filerId := range filerOrder {
|
||||
entryCh := make(chan *filer_pb.LogEntry, 512)
|
||||
streams[i] = filerStream{filerId: filerId, entryCh: entryCh}
|
||||
|
||||
wg.Add(1)
|
||||
go func(refs []*filer_pb.LogFileChunkRef, ch chan *filer_pb.LogEntry) {
|
||||
defer wg.Done()
|
||||
defer close(ch)
|
||||
readFilerFilesToChannel(refs, newReader, startTsNs, stopTsNs, ch)
|
||||
}(perFiler[filerId], entryCh)
|
||||
}
|
||||
|
||||
// Seed the min-heap with the first entry from each filer
|
||||
pq := &logEntryHeap{}
|
||||
heap.Init(pq)
|
||||
for i := range streams {
|
||||
if entry, ok := <-streams[i].entryCh; ok {
|
||||
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: i})
|
||||
}
|
||||
}
|
||||
|
||||
// Merge loop
|
||||
for pq.Len() > 0 {
|
||||
item := heap.Pop(pq).(*logEntryHeapItem)
|
||||
|
||||
lastTsNs, err = processOneLogEntry(item.entry, filter, processEventFn)
|
||||
if err != nil {
|
||||
for i := range streams {
|
||||
for range streams[i].entryCh {
|
||||
}
|
||||
}
|
||||
wg.Wait()
|
||||
return
|
||||
}
|
||||
|
||||
if entry, ok := <-streams[item.filerIdx].entryCh; ok {
|
||||
heap.Push(pq, &logEntryHeapItem{entry: entry, filerIdx: item.filerIdx})
|
||||
}
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
return
|
||||
}
|
||||
|
||||
func readFilerFilesToChannel(
|
||||
refs []*filer_pb.LogFileChunkRef,
|
||||
newReader LogFileReaderFn,
|
||||
startTsNs, stopTsNs int64,
|
||||
ch chan *filer_pb.LogEntry,
|
||||
) {
|
||||
type prefetchResult struct {
|
||||
entries []*filer_pb.LogEntry
|
||||
err error
|
||||
}
|
||||
|
||||
startPrefetch := func(ref *filer_pb.LogFileChunkRef) chan prefetchResult {
|
||||
resultCh := make(chan prefetchResult, 1)
|
||||
go func() {
|
||||
entries, err := readLogFileEntries(newReader, ref.Chunks, startTsNs, stopTsNs)
|
||||
resultCh <- prefetchResult{entries, err}
|
||||
}()
|
||||
return resultCh
|
||||
}
|
||||
|
||||
var pendingCh chan prefetchResult
|
||||
if len(refs) > 0 {
|
||||
pendingCh = startPrefetch(refs[0])
|
||||
}
|
||||
|
||||
for i, ref := range refs {
|
||||
result := <-pendingCh
|
||||
|
||||
if i+1 < len(refs) {
|
||||
pendingCh = startPrefetch(refs[i+1])
|
||||
}
|
||||
|
||||
if result.err != nil {
|
||||
if isChunkNotFound(result.err) {
|
||||
glog.V(0).Infof("skip log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
|
||||
} else {
|
||||
glog.Errorf("read log file filer=%s ts=%d: %v", ref.FilerId, ref.FileTsNs, result.err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
for _, entry := range result.entries {
|
||||
ch <- entry
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func processOneLogEntry(logEntry *filer_pb.LogEntry, filter PathFilter, processEventFn ProcessMetadataFunc) (int64, error) {
|
||||
event := &filer_pb.SubscribeMetadataResponse{}
|
||||
if err := proto.Unmarshal(logEntry.Data, event); err != nil {
|
||||
glog.Errorf("unmarshal log entry: %v", err)
|
||||
return 0, nil // skip corrupt entries
|
||||
}
|
||||
if !matchesFilter(event, filter) {
|
||||
return event.TsNs, nil
|
||||
}
|
||||
if err := processEventFn(event); err != nil {
|
||||
return event.TsNs, fmt.Errorf("process event: %w", err)
|
||||
}
|
||||
return event.TsNs, nil
|
||||
}
|
||||
|
||||
// --- path filtering (mirrors server-side eachEventNotificationFn logic) ---
|
||||
|
||||
const systemLogDir = "/topics/.system/log"
|
||||
|
||||
func matchesFilter(resp *filer_pb.SubscribeMetadataResponse, filter PathFilter) bool {
|
||||
var entryName string
|
||||
if resp.EventNotification != nil {
|
||||
if resp.EventNotification.OldEntry != nil {
|
||||
entryName = resp.EventNotification.OldEntry.Name
|
||||
} else if resp.EventNotification.NewEntry != nil {
|
||||
entryName = resp.EventNotification.NewEntry.Name
|
||||
}
|
||||
}
|
||||
|
||||
fullpath := util.Join(resp.Directory, entryName)
|
||||
|
||||
// Skip internal meta log entries
|
||||
if strings.HasPrefix(fullpath, systemLogDir) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check AdditionalPathPrefixes
|
||||
for _, p := range filter.AdditionalPathPrefixes {
|
||||
if strings.HasPrefix(fullpath, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Check DirectoriesToWatch (exact directory match)
|
||||
for _, dir := range filter.DirectoriesToWatch {
|
||||
if resp.Directory == dir {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Check primary PathPrefix
|
||||
if filter.PathPrefix == "" || filter.PathPrefix == "/" {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(fullpath, filter.PathPrefix) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check rename target
|
||||
if resp.EventNotification != nil && resp.EventNotification.NewParentPath != "" {
|
||||
newFullPath := util.Join(resp.EventNotification.NewParentPath, entryName)
|
||||
if strings.HasPrefix(newFullPath, filter.PathPrefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// isChunkNotFound checks if an error indicates a missing volume chunk.
|
||||
// Matches the server-side isChunkNotFoundError logic.
|
||||
func isChunkNotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
s := err.Error()
|
||||
return strings.Contains(s, "not found") || strings.Contains(s, "status 404")
|
||||
}
|
||||
|
||||
// --- min-heap for merging entries across filers ---
|
||||
|
||||
type logEntryHeapItem struct {
|
||||
entry *filer_pb.LogEntry
|
||||
filerIdx int
|
||||
}
|
||||
|
||||
type logEntryHeap []*logEntryHeapItem
|
||||
|
||||
func (h logEntryHeap) Len() int { return len(h) }
|
||||
func (h logEntryHeap) Less(i, j int) bool { return h[i].entry.TsNs < h[j].entry.TsNs }
|
||||
func (h logEntryHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
||||
func (h *logEntryHeap) Push(x any) { *h = append(*h, x.(*logEntryHeapItem)) }
|
||||
func (h *logEntryHeap) Pop() any {
|
||||
old := *h
|
||||
n := len(old)
|
||||
item := old[n-1]
|
||||
old[n-1] = nil
|
||||
*h = old[:n-1]
|
||||
return item
|
||||
}
|
||||
|
||||
// --- log file parsing (uses io.ReadFull for correct partial-read handling) ---
|
||||
|
||||
func readLogFileEntries(newReader LogFileReaderFn, chunks []*filer_pb.FileChunk, startTsNs, stopTsNs int64) ([]*filer_pb.LogEntry, error) {
|
||||
reader, err := newReader(chunks)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create reader: %w", err)
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
sizeBuf := make([]byte, 4)
|
||||
var entries []*filer_pb.LogEntry
|
||||
|
||||
for {
|
||||
_, err := io.ReadFull(reader, sizeBuf)
|
||||
if err != nil {
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
break
|
||||
}
|
||||
return entries, err
|
||||
}
|
||||
|
||||
size := util.BytesToUint32(sizeBuf)
|
||||
entryData := make([]byte, size)
|
||||
_, err = io.ReadFull(reader, entryData)
|
||||
if err != nil {
|
||||
return entries, err
|
||||
}
|
||||
|
||||
logEntry := &filer_pb.LogEntry{}
|
||||
if err = proto.Unmarshal(entryData, logEntry); err != nil {
|
||||
return entries, err
|
||||
}
|
||||
|
||||
if logEntry.TsNs <= startTsNs {
|
||||
continue
|
||||
}
|
||||
if stopTsNs != 0 && logEntry.TsNs > stopTsNs {
|
||||
break
|
||||
}
|
||||
|
||||
entries = append(entries, logEntry)
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
280
weed/pb/filer_pb_direct_read_test.go
Normal file
280
weed/pb/filer_pb_direct_read_test.go
Normal file
@@ -0,0 +1,280 @@
|
||||
package pb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
// buildLogFileData creates the on-disk log file format:
|
||||
// [4-byte size | protobuf LogEntry] repeated.
|
||||
func buildLogFileData(events []*filer_pb.SubscribeMetadataResponse) []byte {
|
||||
var buf bytes.Buffer
|
||||
for _, event := range events {
|
||||
eventData, _ := proto.Marshal(event)
|
||||
logEntry := &filer_pb.LogEntry{
|
||||
TsNs: event.TsNs,
|
||||
Data: eventData,
|
||||
Key: []byte(event.Directory),
|
||||
}
|
||||
entryData, _ := proto.Marshal(logEntry)
|
||||
sizeBuf := make([]byte, 4)
|
||||
util.Uint32toBytes(sizeBuf, uint32(len(entryData)))
|
||||
buf.Write(sizeBuf)
|
||||
buf.Write(entryData)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func makeSubEvent(dir, name string, tsNs int64) *filer_pb.SubscribeMetadataResponse {
|
||||
return &filer_pb.SubscribeMetadataResponse{
|
||||
Directory: dir,
|
||||
TsNs: tsNs,
|
||||
EventNotification: &filer_pb.EventNotification{
|
||||
NewEntry: &filer_pb.Entry{
|
||||
Name: name,
|
||||
IsDirectory: false,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// delayedReader wraps data with a per-open latency to simulate volume server I/O.
|
||||
type delayedReader struct {
|
||||
data []byte
|
||||
delay time.Duration
|
||||
openedAt time.Time
|
||||
}
|
||||
|
||||
func (r *delayedReader) Read(p []byte) (int, error) {
|
||||
if r.openedAt.IsZero() {
|
||||
r.openedAt = time.Now()
|
||||
time.Sleep(r.delay)
|
||||
}
|
||||
if len(r.data) == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
n := copy(p, r.data)
|
||||
r.data = r.data[n:]
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (r *delayedReader) Close() error { return nil }
|
||||
|
||||
type testLogFiles struct {
|
||||
refs []*filer_pb.LogFileChunkRef
|
||||
fileData map[string][]byte // key: "filerId:fileTsNs" → raw log file bytes
|
||||
fileDelay time.Duration
|
||||
}
|
||||
|
||||
func newTestLogFiles(numFilers, filesPerFiler, eventsPerFile int, fileDelay time.Duration) *testLogFiles {
|
||||
t := &testLogFiles{
|
||||
fileData: make(map[string][]byte),
|
||||
fileDelay: fileDelay,
|
||||
}
|
||||
|
||||
baseTs := time.Now().Add(-time.Hour).UnixNano()
|
||||
tsCounter := int64(0)
|
||||
|
||||
for f := 0; f < numFilers; f++ {
|
||||
filerId := fmt.Sprintf("filer%02d", f)
|
||||
for file := 0; file < filesPerFiler; file++ {
|
||||
fileTsNs := baseTs + int64(file)*int64(time.Minute)
|
||||
|
||||
events := make([]*filer_pb.SubscribeMetadataResponse, eventsPerFile)
|
||||
for i := 0; i < eventsPerFile; i++ {
|
||||
tsCounter++
|
||||
ts := baseTs + tsCounter
|
||||
events[i] = makeSubEvent(
|
||||
fmt.Sprintf("/data/%s/dir%02d", filerId, file),
|
||||
fmt.Sprintf("file%04d.txt", i),
|
||||
ts,
|
||||
)
|
||||
}
|
||||
|
||||
data := buildLogFileData(events)
|
||||
key := fmt.Sprintf("%s:%d", filerId, fileTsNs)
|
||||
t.fileData[key] = data
|
||||
|
||||
t.refs = append(t.refs, &filer_pb.LogFileChunkRef{
|
||||
Chunks: []*filer_pb.FileChunk{{
|
||||
FileId: key,
|
||||
}},
|
||||
FileTsNs: fileTsNs,
|
||||
FilerId: filerId,
|
||||
})
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *testLogFiles) readerFn() LogFileReaderFn {
|
||||
return func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
|
||||
if len(chunks) == 0 {
|
||||
return nil, fmt.Errorf("no chunks")
|
||||
}
|
||||
key := chunks[0].FileId
|
||||
data, ok := t.fileData[key]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("file not found: %s", key)
|
||||
}
|
||||
dataCopy := make([]byte, len(data))
|
||||
copy(dataCopy, data)
|
||||
return &delayedReader{data: dataCopy, delay: t.fileDelay}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (t *testLogFiles) totalEvents() int {
|
||||
total := 0
|
||||
for _, data := range t.fileData {
|
||||
pos := 0
|
||||
for pos+4 <= len(data) {
|
||||
size := int(util.BytesToUint32(data[pos : pos+4]))
|
||||
pos += 4 + size
|
||||
total++
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// TestReadLogFileRefsMergeOrder verifies that entries from multiple filers are
|
||||
// delivered in correct timestamp order.
|
||||
func TestReadLogFileRefsMergeOrder(t *testing.T) {
|
||||
files := newTestLogFiles(3, 2, 50, 0)
|
||||
|
||||
var timestamps []int64
|
||||
_, err := ReadLogFileRefs(files.refs, files.readerFn(), 0, 0,
|
||||
PathFilter{PathPrefix: "/"},
|
||||
func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
timestamps = append(timestamps, resp.TsNs)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ReadLogFileRefs: %v", err)
|
||||
}
|
||||
|
||||
expected := files.totalEvents()
|
||||
if len(timestamps) != expected {
|
||||
t.Fatalf("expected %d events, got %d", expected, len(timestamps))
|
||||
}
|
||||
|
||||
for i := 1; i < len(timestamps); i++ {
|
||||
if timestamps[i] < timestamps[i-1] {
|
||||
t.Errorf("out of order at index %d: ts[%d]=%d > ts[%d]=%d",
|
||||
i, i-1, timestamps[i-1], i, timestamps[i])
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("Verified %d events from 3 filers in correct timestamp order", len(timestamps))
|
||||
}
|
||||
|
||||
// TestReadLogFileRefsPathFilter verifies path filtering including system log exclusion.
|
||||
func TestReadLogFileRefsPathFilter(t *testing.T) {
|
||||
files := newTestLogFiles(2, 2, 50, 0)
|
||||
total := files.totalEvents()
|
||||
|
||||
var allCount, filteredCount int64
|
||||
_, err := ReadLogFileRefs(files.refs, files.readerFn(), 0, 0,
|
||||
PathFilter{PathPrefix: "/"},
|
||||
func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
allCount++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ReadLogFileRefs (all): %v", err)
|
||||
}
|
||||
|
||||
_, err = ReadLogFileRefs(files.refs, files.readerFn(), 0, 0,
|
||||
PathFilter{PathPrefix: "/data/filer00/"},
|
||||
func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
filteredCount++
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ReadLogFileRefs (filtered): %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Total events: %d, matching /data/filer00/: %d", allCount, filteredCount)
|
||||
|
||||
if allCount != int64(total) {
|
||||
t.Errorf("expected %d total events, got %d", total, allCount)
|
||||
}
|
||||
if filteredCount >= allCount {
|
||||
t.Errorf("filter should reduce events: all=%d filtered=%d", allCount, filteredCount)
|
||||
}
|
||||
if filteredCount == 0 {
|
||||
t.Errorf("filter matched zero events")
|
||||
}
|
||||
}
|
||||
|
||||
// TestDirectReadVsServerSideThroughput compares:
|
||||
// - Server-side: sequential file read → gRPC send per event
|
||||
// - Client direct-read: parallel filers + prefetching + no gRPC
|
||||
func TestDirectReadVsServerSideThroughput(t *testing.T) {
|
||||
const (
|
||||
numFilers = 3
|
||||
filesPerFiler = 7
|
||||
eventsPerFile = 300
|
||||
fileReadDelay = 2 * time.Millisecond
|
||||
sendDelay = 20 * time.Microsecond
|
||||
)
|
||||
|
||||
files := newTestLogFiles(numFilers, filesPerFiler, eventsPerFile, fileReadDelay)
|
||||
|
||||
var serverRate float64
|
||||
t.Run("server_side_sequential", func(t *testing.T) {
|
||||
var processed int64
|
||||
start := time.Now()
|
||||
|
||||
for _, ref := range files.refs {
|
||||
time.Sleep(fileReadDelay)
|
||||
key := ref.Chunks[0].FileId
|
||||
data := files.fileData[key]
|
||||
pos := 0
|
||||
for pos+4 <= len(data) {
|
||||
size := int(util.BytesToUint32(data[pos : pos+4]))
|
||||
pos += 4 + size
|
||||
time.Sleep(sendDelay)
|
||||
atomic.AddInt64(&processed, 1)
|
||||
}
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
serverRate = float64(processed) / elapsed.Seconds()
|
||||
t.Logf("server-side: %d events %v %6.0f events/sec (%d files sequential + %v send/event)",
|
||||
processed, elapsed.Round(time.Millisecond), serverRate,
|
||||
numFilers*filesPerFiler, sendDelay)
|
||||
})
|
||||
|
||||
var directRate float64
|
||||
t.Run("client_direct_read_parallel_prefetch", func(t *testing.T) {
|
||||
var processed int64
|
||||
start := time.Now()
|
||||
|
||||
_, err := ReadLogFileRefs(files.refs, files.readerFn(), 0, 0,
|
||||
PathFilter{PathPrefix: "/"},
|
||||
func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
atomic.AddInt64(&processed, 1)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("ReadLogFileRefs: %v", err)
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
directRate = float64(processed) / elapsed.Seconds()
|
||||
t.Logf("direct-read: %d events %v %6.0f events/sec (%d filers parallel + prefetch, no gRPC)",
|
||||
processed, elapsed.Round(time.Millisecond), directRate, numFilers)
|
||||
})
|
||||
|
||||
if serverRate > 0 {
|
||||
t.Logf("Speedup: %.1fx (parallel + prefetch + no gRPC vs server-side sequential)", directRate/serverRate)
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,10 @@ type MetadataFollowOption struct {
|
||||
StartTsNs int64
|
||||
StopTsNs int64
|
||||
EventErrorType EventErrorType
|
||||
// LogFileReaderFn, when non-nil, enables metadata chunks mode:
|
||||
// the server sends log file chunk fids instead of streaming events,
|
||||
// and the client reads directly from volume servers.
|
||||
LogFileReaderFn LogFileReaderFn
|
||||
}
|
||||
|
||||
type ProcessMetadataFunc func(resp *filer_pb.SubscribeMetadataResponse) error
|
||||
@@ -72,6 +76,7 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
|
||||
ClientEpoch: option.ClientEpoch,
|
||||
UntilNs: option.StopTsNs,
|
||||
ClientSupportsBatching: true,
|
||||
ClientSupportsMetadataChunks: option.LogFileReaderFn != nil,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("subscribe: %w", err)
|
||||
@@ -97,6 +102,8 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
|
||||
}
|
||||
}
|
||||
|
||||
var pendingRefs []*filer_pb.LogFileChunkRef
|
||||
|
||||
for {
|
||||
resp, listenErr := stream.Recv()
|
||||
if listenErr == io.EOF {
|
||||
@@ -106,11 +113,38 @@ func makeSubscribeMetadataFunc(option *MetadataFollowOption, processEventFn Proc
|
||||
return listenErr
|
||||
}
|
||||
|
||||
// Accumulate log file chunk references (metadata chunks mode)
|
||||
if len(resp.LogFileRefs) > 0 {
|
||||
pendingRefs = append(pendingRefs, resp.LogFileRefs...)
|
||||
continue
|
||||
}
|
||||
|
||||
// Process accumulated refs before handling normal events (transition point)
|
||||
if len(pendingRefs) > 0 && option.LogFileReaderFn != nil {
|
||||
lastTs, readErr := ReadLogFileRefs(pendingRefs, option.LogFileReaderFn,
|
||||
option.StartTsNs, option.StopTsNs,
|
||||
PathFilter{
|
||||
PathPrefix: option.PathPrefix,
|
||||
AdditionalPathPrefixes: option.AdditionalPathPrefixes,
|
||||
DirectoriesToWatch: option.DirectoriesToWatch,
|
||||
},
|
||||
processEventFn)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("read log file refs: %w", readErr)
|
||||
}
|
||||
if lastTs > 0 {
|
||||
option.StartTsNs = lastTs
|
||||
}
|
||||
pendingRefs = nil
|
||||
}
|
||||
|
||||
// Process the first event (always present in top-level fields)
|
||||
if resp.EventNotification != nil {
|
||||
if err := processEventFn(resp); err != nil {
|
||||
handleErr(resp, err)
|
||||
}
|
||||
option.StartTsNs = resp.TsNs
|
||||
}
|
||||
|
||||
// Process any additional batched events
|
||||
for _, batchedEvent := range resp.Events {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -196,7 +197,11 @@ func (fs *FilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest,
|
||||
|
||||
glog.V(4).Infof("read on disk %v aggregated subscribe %s from %+v", clientName, req.PathPrefix, lastReadTime)
|
||||
|
||||
if req.ClientSupportsMetadataChunks {
|
||||
processedTsNs, isDone, readPersistedLogErr = fs.sendLogFileRefs(ctx, stream, lastReadTime, req.UntilNs)
|
||||
} else {
|
||||
processedTsNs, isDone, readPersistedLogErr = fs.filer.ReadPersistedLogBuffer(lastReadTime, req.UntilNs, eachLogEntryFn)
|
||||
}
|
||||
if readPersistedLogErr != nil {
|
||||
return fmt.Errorf("reading from persisted logs: %w", readPersistedLogErr)
|
||||
}
|
||||
@@ -331,7 +336,11 @@ func (fs *FilerServer) SubscribeLocalMetadata(req *filer_pb.SubscribeMetadataReq
|
||||
// Record the position we are about to read from
|
||||
lastDiskReadTsNs = currentReadTsNs
|
||||
glog.V(4).Infof("read on disk %v local subscribe %s from %+v (lastFlushed: %v)", clientName, req.PathPrefix, lastReadTime, time.Unix(0, currentFlushTsNs))
|
||||
if req.ClientSupportsMetadataChunks {
|
||||
processedTsNs, isDone, readPersistedLogErr = fs.sendLogFileRefs(ctx, stream, lastReadTime, req.UntilNs)
|
||||
} else {
|
||||
processedTsNs, isDone, readPersistedLogErr = fs.filer.ReadPersistedLogBuffer(lastReadTime, req.UntilNs, eachLogEntryFn)
|
||||
}
|
||||
if readPersistedLogErr != nil {
|
||||
glog.V(0).Infof("read on disk %v local subscribe %s from %+v: %v", clientName, req.PathPrefix, lastReadTime, readPersistedLogErr)
|
||||
return fmt.Errorf("reading from persisted logs: %w", readPersistedLogErr)
|
||||
@@ -447,6 +456,35 @@ func eachLogEntryFn(eachEventNotificationFn func(dirPath string, eventNotificati
|
||||
}
|
||||
}
|
||||
|
||||
// sendLogFileRefs collects persisted log file chunk references and sends them
|
||||
// to the client so it can read the data directly from volume servers.
|
||||
// This does zero volume server I/O — it only lists filer store directory entries.
|
||||
// Sends directly on the gRPC stream (bypasses pipelinedSender) because ref
|
||||
// messages have TsNs=0 and must not be batched into Events by the sender.
|
||||
func (fs *FilerServer) sendLogFileRefs(ctx context.Context, stream metadataStreamSender, startPosition log_buffer.MessagePosition, stopTsNs int64) (lastTsNs int64, isDone bool, err error) {
|
||||
refs, lastTsNs, err := fs.filer.CollectLogFileRefs(ctx, startPosition, stopTsNs)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if len(refs) == 0 {
|
||||
return 0, false, nil
|
||||
}
|
||||
|
||||
const maxRefsPerMessage = 64
|
||||
for i := 0; i < len(refs); i += maxRefsPerMessage {
|
||||
end := i + maxRefsPerMessage
|
||||
if end > len(refs) {
|
||||
end = len(refs)
|
||||
}
|
||||
if err := stream.Send(&filer_pb.SubscribeMetadataResponse{
|
||||
LogFileRefs: refs[i:end],
|
||||
}); err != nil {
|
||||
return lastTsNs, false, err
|
||||
}
|
||||
}
|
||||
return lastTsNs, false, nil
|
||||
}
|
||||
|
||||
func (fs *FilerServer) eachEventNotificationFn(req *filer_pb.SubscribeMetadataRequest, sender metadataStreamSender, clientName string) func(dirPath string, eventNotification *filer_pb.EventNotification, tsNs int64) error {
|
||||
filtered := 0
|
||||
|
||||
|
||||
Reference in New Issue
Block a user