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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
|
package fs
import (
"bufio"
"bytes"
"context"
"io"
"os"
"time"
"github.com/mimecast/dtail/internal/config"
"github.com/mimecast/dtail/internal/constants"
"github.com/mimecast/dtail/internal/lcontext"
)
// LineProcessor interface for direct line-by-line processing
type LineProcessor interface {
ProcessLine(line []byte, lineNum int, filePath string, stats *stats, sourceID string) (result []byte, shouldSend bool)
Flush() []byte // For any buffered output (e.g., MapReduce)
Initialize(ctx context.Context) error
Cleanup() error
}
// LineWriter interface for writers that need sourceID information
type LineWriter interface {
io.Writer
WriteLine(data []byte, sourceID string, stats interface{}) error
}
// DirectProcessor processes files without channels for better performance
type DirectProcessor struct {
processor LineProcessor
output io.Writer
stats *stats
ltx lcontext.LContext
sourceID string // The globID for this file
}
// NewDirectProcessor creates a new direct processor
func NewDirectProcessor(processor LineProcessor, output io.Writer, globID string, ltx lcontext.LContext) *DirectProcessor {
return &DirectProcessor{
processor: processor,
output: output,
stats: &stats{}, // Create a new stats instance
ltx: ltx,
sourceID: globID,
}
}
// ProcessFile processes a file directly without channels
func (dp *DirectProcessor) ProcessFile(ctx context.Context, filePath string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
// Initialize processor
if err := dp.processor.Initialize(ctx); err != nil {
return err
}
defer dp.processor.Cleanup()
return dp.ProcessReader(ctx, file, filePath)
}
// ProcessReader processes an io.Reader directly without channels
func (dp *DirectProcessor) ProcessReader(ctx context.Context, reader io.Reader, filePath string) error {
// Check if we need to preserve line endings (for any processor in plain mode)
needsLineEndingPreservation := false
if catProcessor, ok := dp.processor.(*CatProcessor); ok && catProcessor.plain {
needsLineEndingPreservation = true
} else if grepProcessor, ok := dp.processor.(*GrepProcessor); ok && grepProcessor.plain {
needsLineEndingPreservation = true
}
// Note: MapProcessor doesn't have a plain mode that requires line ending preservation
if needsLineEndingPreservation {
return dp.processReaderPreservingLineEndings(ctx, reader, filePath)
}
scanner := bufio.NewScanner(reader)
// Set buffer size respecting MaxLineLength configuration
maxLineLength := config.Server.MaxLineLength
initialBufSize := constants.InitialBufferSize
if maxLineLength < initialBufSize {
initialBufSize = maxLineLength
}
scanner.Buffer(make([]byte, initialBufSize), maxLineLength)
lineNum := 0
for scanner.Scan() {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
lineNum++
line := scanner.Bytes()
// Update position stats
if dp.stats != nil {
dp.stats.updatePosition()
}
// Process line directly
if result, shouldSend := dp.processor.ProcessLine(line, lineNum, filePath, dp.stats, dp.sourceID); shouldSend {
// Check if output writer supports sourceID (for proper protocol formatting)
if lineWriter, ok := dp.output.(LineWriter); ok {
if err := lineWriter.WriteLine(result, dp.sourceID, dp.stats); err != nil {
return err
}
} else {
// Regular write path (e.g., stdout in serverless mode)
// Check if we need to add a newline
if _, isCat := dp.processor.(*CatProcessor); isCat {
// Scanner strips newlines, so we need to add them back for cat
// Combine the result with newline in a single write to avoid
// double color processing
resultWithNewline := append(result, '\n')
if _, err := dp.output.Write(resultWithNewline); err != nil {
return err
}
} else {
// For other processors, just write the result as-is
if _, err := dp.output.Write(result); err != nil {
return err
}
}
}
// Update transmission stats
if dp.stats != nil {
dp.stats.updateLineTransmitted()
}
}
}
// Flush any buffered output
if final := dp.processor.Flush(); len(final) > 0 {
if _, err := dp.output.Write(final); err != nil {
return err
}
}
return scanner.Err()
}
// processReaderPreservingLineEndings processes a reader while preserving original line endings
// and implementing line splitting for very long lines
func (dp *DirectProcessor) processReaderPreservingLineEndings(ctx context.Context, reader io.Reader, filePath string) error {
buf := make([]byte, 8192)
var remaining []byte
lineNum := 0
maxLineLength := config.Server.MaxLineLength
warnedAboutLongLine := false
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
n, err := reader.Read(buf)
if n > 0 {
data := append(remaining, buf[:n]...)
remaining = remaining[:0]
// Process complete lines
for {
// Find next line ending (LF or CRLF)
lfIndex := bytes.IndexByte(data, '\n')
if lfIndex == -1 {
// No complete line found
// Check if the accumulated data exceeds max line length
if len(data) >= maxLineLength {
if !warnedAboutLongLine {
// Note: we don't have server messages channel in direct processing mode
// so we'll just split without warning
warnedAboutLongLine = true
}
// Split at max line length, add LF
lineNum++
splitLine := make([]byte, maxLineLength+1)
copy(splitLine, data[:maxLineLength])
splitLine[maxLineLength] = '\n'
// Update position stats
if dp.stats != nil {
dp.stats.updatePosition()
}
// Process the split line
if result, shouldSend := dp.processor.ProcessLine(splitLine, lineNum, filePath, dp.stats, dp.sourceID); shouldSend {
if _, err := dp.output.Write(result); err != nil {
return err
}
// Update transmission stats
if dp.stats != nil {
dp.stats.updateLineTransmitted()
}
}
// Continue with remaining data
data = data[maxLineLength:]
continue
} else {
// Save for next iteration
remaining = append(remaining, data...)
break
}
}
// Extract the line including its original line ending (CRLF or LF)
line := data[:lfIndex+1] // Include the LF (and CR if present before it)
data = data[lfIndex+1:] // Continue with remaining data
// Reset warning flag for new line
warnedAboutLongLine = false
// Check if this line exceeds max length and needs to be split
if len(line) > maxLineLength {
// Split the long line into chunks
lineContent := line[:len(line)-1] // Remove the LF
lineEnding := line[len(line)-1:] // Keep the LF
for len(lineContent) > 0 {
lineNum++
var chunk []byte
if len(lineContent) > maxLineLength {
chunk = make([]byte, maxLineLength+1)
copy(chunk, lineContent[:maxLineLength])
chunk[maxLineLength] = '\n'
lineContent = lineContent[maxLineLength:]
} else {
chunk = make([]byte, len(lineContent)+len(lineEnding))
copy(chunk, lineContent)
copy(chunk[len(lineContent):], lineEnding)
lineContent = nil
}
// Process the chunk
if result, shouldSend := dp.processor.ProcessLine(chunk, lineNum, filePath, dp.stats, dp.sourceID); shouldSend {
// Update position stats only for lines that will be sent
if dp.stats != nil {
dp.stats.updatePosition()
dp.stats.updateLineMatched()
}
if _, err := dp.output.Write(result); err != nil {
return err
}
// Update transmission stats
if dp.stats != nil {
dp.stats.updateLineTransmitted()
}
}
}
} else {
// Normal line processing
lineNum++
// Process line directly (line includes original line ending)
if result, shouldSend := dp.processor.ProcessLine(line, lineNum, filePath, dp.stats, dp.sourceID); shouldSend {
// Update position stats only for lines that will be sent
if dp.stats != nil {
dp.stats.updatePosition()
dp.stats.updateLineMatched()
}
if _, err := dp.output.Write(result); err != nil {
return err
}
// Update transmission stats
if dp.stats != nil {
dp.stats.updateLineTransmitted()
}
}
}
}
}
if err == io.EOF {
// Process any remaining data as the last line, respecting line length limit
for len(remaining) > 0 {
lineNum++
var lineToProcess []byte
if len(remaining) > maxLineLength {
// Split the remaining data
lineToProcess = make([]byte, maxLineLength+1)
copy(lineToProcess, remaining[:maxLineLength])
lineToProcess[maxLineLength] = '\n'
remaining = remaining[maxLineLength:]
} else {
// Process all remaining data
lineToProcess = remaining
remaining = nil
}
// Update position stats
if dp.stats != nil {
dp.stats.updatePosition()
}
if result, shouldSend := dp.processor.ProcessLine(lineToProcess, lineNum, filePath, dp.stats, dp.sourceID); shouldSend {
if _, err := dp.output.Write(result); err != nil {
return err
}
// Update transmission stats
if dp.stats != nil {
dp.stats.updateLineTransmitted()
// DEBUG: Log stats
// fmt.Printf("DEBUG: After transmission - matchCount=%d, transmitCount=%d, percentage=%d\n",
// dp.stats.matchCount, dp.stats.transmitCount, dp.stats.transmittedPerc())
}
}
}
break
}
if err != nil {
return err
}
}
// Flush any buffered output
if final := dp.processor.Flush(); len(final) > 0 {
if _, err := dp.output.Write(final); err != nil {
return err
}
}
return nil
}
// ProcessFileWithTailing processes a file with tailing capability
func (dp *DirectProcessor) ProcessFileWithTailing(ctx context.Context, filePath string) error {
// Use the same logic as FollowingTailProcessor but with our DirectProcessor
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
// First, process existing content
if err := dp.ProcessReader(ctx, file, filePath); err != nil {
return err
}
// Then follow the file for new content
return dp.followFile(ctx, filePath)
}
// followFile implements file following logic similar to FollowingTailProcessor
func (dp *DirectProcessor) followFile(ctx context.Context, filePath string) error {
// Track our current position in the file
var lastSize int64
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(constants.ProcessorTimeoutDuration):
// Check if file has grown
fileInfo, err := os.Stat(filePath)
if err != nil {
continue
}
currentSize := fileInfo.Size()
if currentSize > lastSize {
// File has new content, read it
file, err := os.Open(filePath)
if err != nil {
continue
}
// Seek to where we left off
if _, err := file.Seek(lastSize, 0); err != nil {
file.Close()
continue
}
// Process new content
if err := dp.processNewContent(ctx, file, filePath); err != nil {
file.Close()
continue
}
lastSize = currentSize
file.Close()
}
}
}
}
// processNewContent processes new content that was added to the file
func (dp *DirectProcessor) processNewContent(ctx context.Context, file *os.File, filePath string) error {
scanner := bufio.NewScanner(file)
// Start line counting from where we left off (simplified approach)
lineNum := 1
for scanner.Scan() {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
lineBuf := scanner.Bytes()
if result, shouldSend := dp.processor.ProcessLine(lineBuf, lineNum, filePath, dp.stats, dp.sourceID); shouldSend {
if _, err := dp.output.Write(result); err != nil {
return err
}
// Update transmission stats
if dp.stats != nil {
dp.stats.updateLineTransmitted()
}
}
lineNum++
// Update position stats
if dp.stats != nil {
dp.stats.updatePosition()
}
}
return scanner.Err()
}
|