1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
|
package log_buffer
import (
"bytes"
"fmt"
"time"
"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"
)
var (
ResumeError = fmt.Errorf("resume")
ResumeFromDiskError = fmt.Errorf("resumeFromDisk")
)
type MessagePosition struct {
Time time.Time // timestamp of the message
Offset int64 // Kafka offset for offset-based positioning, or batch index for timestamp-based
IsOffsetBased bool // true if this position is offset-based, false if timestamp-based
}
func NewMessagePosition(tsNs int64, offset int64) MessagePosition {
return MessagePosition{
Time: time.Unix(0, tsNs).UTC(),
Offset: offset,
IsOffsetBased: false, // timestamp-based by default
}
}
// NewMessagePositionFromOffset creates a MessagePosition that represents a specific offset
func NewMessagePositionFromOffset(offset int64) MessagePosition {
return MessagePosition{
Time: time.Time{}, // Zero time for offset-based positions
Offset: offset,
IsOffsetBased: true,
}
}
// GetOffset extracts the offset from an offset-based MessagePosition
func (mp MessagePosition) GetOffset() int64 {
if !mp.IsOffsetBased {
return -1 // Not an offset-based position
}
return mp.Offset // Offset is stored directly
}
func (logBuffer *LogBuffer) LoopProcessLogData(readerName string, startPosition MessagePosition, stopTsNs int64,
waitForDataFn func() bool, eachLogDataFn EachLogEntryFuncType) (lastReadPosition MessagePosition, isDone bool, err error) {
// Register for instant notifications (<1ms latency)
notifyChan := logBuffer.RegisterSubscriber(readerName)
defer logBuffer.UnregisterSubscriber(readerName)
// loop through all messages
var bytesBuf *bytes.Buffer
var batchIndex int64
lastReadPosition = startPosition
var entryCounter int64
defer func() {
if bytesBuf != nil {
logBuffer.ReleaseMemory(bytesBuf)
}
// println("LoopProcessLogData", readerName, "sent messages total", entryCounter)
}()
for {
if bytesBuf != nil {
logBuffer.ReleaseMemory(bytesBuf)
}
bytesBuf, batchIndex, err = logBuffer.ReadFromBuffer(lastReadPosition)
if err == ResumeFromDiskError {
time.Sleep(1127 * time.Millisecond)
return lastReadPosition, isDone, ResumeFromDiskError
}
readSize := 0
if bytesBuf != nil {
readSize = bytesBuf.Len()
}
glog.V(4).Infof("%s ReadFromBuffer at %v offset %d. Read bytes %v batchIndex %d", readerName, lastReadPosition, lastReadPosition.Offset, readSize, batchIndex)
if bytesBuf == nil {
if batchIndex >= 0 {
lastReadPosition = NewMessagePosition(lastReadPosition.Time.UnixNano(), batchIndex)
}
if stopTsNs != 0 {
isDone = true
return
}
lastTsNs := logBuffer.LastTsNs.Load()
for lastTsNs == logBuffer.LastTsNs.Load() {
if !waitForDataFn() {
isDone = true
return
}
// Wait for notification or timeout (instant wake-up when data arrives)
select {
case <-notifyChan:
// New data available, break and retry read
glog.V(3).Infof("%s: Woke up from notification (LoopProcessLogData)", readerName)
break
case <-time.After(10 * time.Millisecond):
// Timeout, check if timestamp changed
if lastTsNs != logBuffer.LastTsNs.Load() {
break
}
glog.V(4).Infof("%s: Notification timeout (LoopProcessLogData), polling", readerName)
}
}
if logBuffer.IsStopping() {
isDone = true
return
}
continue
}
buf := bytesBuf.Bytes()
// fmt.Printf("ReadFromBuffer %s by %v size %d\n", readerName, lastReadPosition, len(buf))
batchSize := 0
for pos := 0; pos+4 < len(buf); {
size := util.BytesToUint32(buf[pos : pos+4])
if pos+4+int(size) > len(buf) {
err = ResumeError
glog.Errorf("LoopProcessLogData: %s read buffer %v read %d entries [%d,%d) from [0,%d)", readerName, lastReadPosition, batchSize, pos, pos+int(size)+4, len(buf))
return
}
entryData := buf[pos+4 : pos+4+int(size)]
logEntry := &filer_pb.LogEntry{}
if err = proto.Unmarshal(entryData, logEntry); err != nil {
glog.Errorf("unexpected unmarshal mq_pb.Message: %v", err)
pos += 4 + int(size)
continue
}
// Handle offset-based filtering for offset-based start positions
if startPosition.IsOffsetBased {
startOffset := startPosition.GetOffset()
if logEntry.Offset < startOffset {
// Skip entries before the starting offset
pos += 4 + int(size)
batchSize++
continue
}
}
if stopTsNs != 0 && logEntry.TsNs > stopTsNs {
isDone = true
// println("stopTsNs", stopTsNs, "logEntry.TsNs", logEntry.TsNs)
return
}
lastReadPosition = NewMessagePosition(logEntry.TsNs, batchIndex)
if isDone, err = eachLogDataFn(logEntry); err != nil {
glog.Errorf("LoopProcessLogData: %s process log entry %d %v: %v", readerName, batchSize+1, logEntry, err)
return
}
if isDone {
glog.V(0).Infof("LoopProcessLogData2: %s process log entry %d", readerName, batchSize+1)
return
}
pos += 4 + int(size)
batchSize++
entryCounter++
}
glog.V(4).Infof("%s sent messages ts[%+v,%+v] size %d\n", readerName, startPosition, lastReadPosition, batchSize)
}
}
// LoopProcessLogDataWithOffset is similar to LoopProcessLogData but provides offset to the callback
func (logBuffer *LogBuffer) LoopProcessLogDataWithOffset(readerName string, startPosition MessagePosition, stopTsNs int64,
waitForDataFn func() bool, eachLogDataFn EachLogEntryWithOffsetFuncType) (lastReadPosition MessagePosition, isDone bool, err error) {
glog.V(4).Infof("LoopProcessLogDataWithOffset started for %s, startPosition=%v", readerName, startPosition)
// Register for instant notifications (<1ms latency)
notifyChan := logBuffer.RegisterSubscriber(readerName)
defer logBuffer.UnregisterSubscriber(readerName)
// loop through all messages
var bytesBuf *bytes.Buffer
var offset int64
lastReadPosition = startPosition
var entryCounter int64
defer func() {
if bytesBuf != nil {
logBuffer.ReleaseMemory(bytesBuf)
}
// println("LoopProcessLogDataWithOffset", readerName, "sent messages total", entryCounter)
}()
for {
// Check stopTsNs at the beginning of each iteration
// This ensures we exit immediately if the stop time is in the past
if stopTsNs != 0 && time.Now().UnixNano() > stopTsNs {
isDone = true
return
}
if bytesBuf != nil {
logBuffer.ReleaseMemory(bytesBuf)
}
bytesBuf, offset, err = logBuffer.ReadFromBuffer(lastReadPosition)
glog.V(4).Infof("ReadFromBuffer for %s returned bytesBuf=%v, offset=%d, err=%v", readerName, bytesBuf != nil, offset, err)
if err == ResumeFromDiskError {
// Try to read from disk if readFromDiskFn is available
if logBuffer.ReadFromDiskFn != nil {
// Wrap eachLogDataFn to match the expected signature
diskReadFn := func(logEntry *filer_pb.LogEntry) (bool, error) {
return eachLogDataFn(logEntry, logEntry.Offset)
}
lastReadPosition, isDone, err = logBuffer.ReadFromDiskFn(lastReadPosition, stopTsNs, diskReadFn)
if err != nil {
return lastReadPosition, isDone, err
}
if isDone {
return lastReadPosition, isDone, nil
}
// Continue to next iteration after disk read
}
// CRITICAL: Check if client is still connected after disk read
if !waitForDataFn() {
// Client disconnected - exit cleanly
glog.V(4).Infof("%s: Client disconnected after disk read", readerName)
return lastReadPosition, true, nil
}
// Wait for notification or timeout (instant wake-up when data arrives)
select {
case <-notifyChan:
// New data available, retry immediately
glog.V(3).Infof("%s: Woke up from notification after disk read", readerName)
case <-time.After(10 * time.Millisecond):
// Timeout, retry anyway (fallback for edge cases)
glog.V(4).Infof("%s: Notification timeout, polling", readerName)
}
// Continue to next iteration (don't return ResumeFromDiskError)
continue
}
readSize := 0
if bytesBuf != nil {
readSize = bytesBuf.Len()
}
glog.V(4).Infof("%s ReadFromBuffer at %v posOffset %d. Read bytes %v bufferOffset %d", readerName, lastReadPosition, lastReadPosition.Offset, readSize, offset)
if bytesBuf == nil {
// CRITICAL: Check if subscription is still active BEFORE waiting
// This prevents infinite loops when client has disconnected
if !waitForDataFn() {
glog.V(4).Infof("%s: waitForDataFn returned false, subscription ending", readerName)
return lastReadPosition, true, nil
}
if offset >= 0 {
lastReadPosition = NewMessagePosition(lastReadPosition.Time.UnixNano(), offset)
}
if stopTsNs != 0 {
isDone = true
return
}
// CRITICAL FIX: If we're reading offset-based and there's no data in LogBuffer,
// return ResumeFromDiskError to let Subscribe try reading from disk again.
// This prevents infinite blocking when all data is on disk (e.g., after restart).
if startPosition.IsOffsetBased {
glog.V(4).Infof("%s: No data in LogBuffer for offset-based read at %v, checking if client still connected", readerName, lastReadPosition)
// Check if client is still connected before busy-looping
if !waitForDataFn() {
glog.V(4).Infof("%s: Client disconnected, stopping offset-based read", readerName)
return lastReadPosition, true, nil
}
// Wait for notification or timeout (instant wake-up when data arrives)
select {
case <-notifyChan:
// New data available, retry immediately
glog.V(3).Infof("%s: Woke up from notification for offset-based read", readerName)
case <-time.After(10 * time.Millisecond):
// Timeout, retry anyway (fallback for edge cases)
glog.V(4).Infof("%s: Notification timeout for offset-based, polling", readerName)
}
return lastReadPosition, isDone, ResumeFromDiskError
}
lastTsNs := logBuffer.LastTsNs.Load()
for lastTsNs == logBuffer.LastTsNs.Load() {
if !waitForDataFn() {
glog.V(4).Infof("%s: Client disconnected during timestamp wait", readerName)
return lastReadPosition, true, nil
}
// Wait for notification or timeout (instant wake-up when data arrives)
select {
case <-notifyChan:
// New data available, break and retry read
glog.V(3).Infof("%s: Woke up from notification (main loop)", readerName)
break
case <-time.After(10 * time.Millisecond):
// Timeout, check if timestamp changed
if lastTsNs != logBuffer.LastTsNs.Load() {
break
}
glog.V(4).Infof("%s: Notification timeout (main loop), polling", readerName)
}
}
if logBuffer.IsStopping() {
glog.V(4).Infof("%s: LogBuffer is stopping", readerName)
return lastReadPosition, true, nil
}
continue
}
buf := bytesBuf.Bytes()
// fmt.Printf("ReadFromBuffer %s by %v size %d\n", readerName, lastReadPosition, len(buf))
glog.V(4).Infof("Processing buffer with %d bytes for %s", len(buf), readerName)
// If buffer is empty, check if client is still connected before looping
if len(buf) == 0 {
glog.V(4).Infof("Empty buffer for %s, checking if client still connected", readerName)
if !waitForDataFn() {
glog.V(4).Infof("%s: Client disconnected on empty buffer", readerName)
return lastReadPosition, true, nil
}
// Sleep to avoid busy-wait on empty buffer
time.Sleep(10 * time.Millisecond)
continue
}
batchSize := 0
for pos := 0; pos+4 < len(buf); {
size := util.BytesToUint32(buf[pos : pos+4])
if pos+4+int(size) > len(buf) {
err = ResumeError
glog.Errorf("LoopProcessLogDataWithOffset: %s read buffer %v read %d entries [%d,%d) from [0,%d)", readerName, lastReadPosition, batchSize, pos, pos+int(size)+4, len(buf))
return
}
entryData := buf[pos+4 : pos+4+int(size)]
logEntry := &filer_pb.LogEntry{}
if err = proto.Unmarshal(entryData, logEntry); err != nil {
glog.Errorf("unexpected unmarshal mq_pb.Message: %v", err)
pos += 4 + int(size)
continue
}
glog.V(4).Infof("Unmarshaled log entry %d: TsNs=%d, Offset=%d, Key=%s", batchSize+1, logEntry.TsNs, logEntry.Offset, string(logEntry.Key))
// Handle offset-based filtering for offset-based start positions
if startPosition.IsOffsetBased {
startOffset := startPosition.GetOffset()
glog.V(4).Infof("Offset-based filtering: logEntry.Offset=%d, startOffset=%d", logEntry.Offset, startOffset)
if logEntry.Offset < startOffset {
// Skip entries before the starting offset
glog.V(4).Infof("Skipping entry due to offset filter")
pos += 4 + int(size)
batchSize++
continue
}
}
if stopTsNs != 0 && logEntry.TsNs > stopTsNs {
glog.V(4).Infof("Stopping due to stopTsNs")
isDone = true
// println("stopTsNs", stopTsNs, "logEntry.TsNs", logEntry.TsNs)
return
}
// CRITICAL FIX: Use logEntry.Offset + 1 to move PAST the current entry
// This prevents infinite loops where we keep requesting the same offset
lastReadPosition = NewMessagePosition(logEntry.TsNs, logEntry.Offset+1)
glog.V(4).Infof("Calling eachLogDataFn for entry at offset %d, next position will be %d", logEntry.Offset, logEntry.Offset+1)
if isDone, err = eachLogDataFn(logEntry, logEntry.Offset); err != nil {
glog.Errorf("LoopProcessLogDataWithOffset: %s process log entry %d %v: %v", readerName, batchSize+1, logEntry, err)
return
}
if isDone {
glog.V(0).Infof("LoopProcessLogDataWithOffset: %s process log entry %d", readerName, batchSize+1)
return
}
pos += 4 + int(size)
batchSize++
entryCounter++
}
}
}
|