-
Notifications
You must be signed in to change notification settings - Fork 0
/
logmerge.go
461 lines (371 loc) · 8.62 KB
/
logmerge.go
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
/*
Package logmerge provides a method to merge multiple log files by timestamp.
Example:
filePath := []string{"1.log", "2.log", "3.log"}
outputPath := "output.log"
getTime := func(line []byte) (int64, logmerge.Action, error) {
tm, err := time.Parse("20060102150405", string(line[:14]))
if err != nil {
return 0, logmerge.SKIP, nil
}
return tm.Unix(), logmerge.NOP, nil
}
err := logMerge.Merge(filepath, outputPath, getTime)
*/
package logmerge
import (
"bufio"
"compress/gzip"
"container/heap"
"context"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"github.com/pkg/errors"
)
// Action defined the read log behaviour.
type Action int
const (
// NOP: no extra option
NOP = iota
// SKIP: skip this line
SKIP
// STOP: stop file merging
STOP
)
var (
// NEED_TIMEHANDLER returned when the getTime function is nil.
NEED_TIMEHANDLER = errors.New("need time handler")
// NEED_ERRCHAN returned when using quick merge without err channel.
NEED_ERRCHAN = errors.New("need error channel")
)
/*
TimeHandler defined handlers for getting timestamp from each line.
*/
type TimeHandler = func([]byte) (int64, Action, error)
/*
FilterHandler defined handlers for modifying each line.
*/
type FilterHandler = func(string, []byte) ([]byte, Action, error)
type fileReader struct {
filename string
scanner *bufio.Scanner
timestamp int64
line []byte
eof bool
getTime TimeHandler
filter FilterHandler
}
/*
Option defined some option can set for merging.
*/
type Option struct {
SrcPath []string // Merge src File Path
DstPath string // The filePath merge to
SrcReader []io.Reader // Src files' io.Reader
DstWriter io.Writer // Destinated file's io.Writer
SrcGzip bool // Whether src file is in gzip format
DstGzip bool // Merge file in gzip format
DeleteSrc bool // Delete src file
GetTime TimeHandler // The function to getTime from each line
Filter FilterHandler // The function to process each line
Goroutine int // Quick merge's worker number
ErrChan chan error // Quick merge's error return
CTX context.Context // Quick merge's context
}
type quickMergeJob struct {
filename string
scanner *bufio.Scanner
writer chan []byte
filter FilterHandler
errChan chan error
ctx context.Context
}
type fileHeap struct {
readers []*fileReader
writer *bufio.Writer
}
func (fh fileHeap) Len() int { return len(fh.readers) }
func (fh fileHeap) Less(i, j int) bool {
return fh.readers[i].timestamp < fh.readers[j].timestamp
}
func (fh fileHeap) Swap(i, j int) {
fh.readers[i], fh.readers[j] = fh.readers[j], fh.readers[i]
}
func (fh *fileHeap) Push(h interface{}) {
(*fh).readers = append((*fh).readers, h.(*fileReader))
}
func (fh *fileHeap) Pop() interface{} {
n := len((*fh).readers)
fr := (*fh).readers[n-1]
(*fh).readers = (*fh).readers[:n-1]
return fr
}
func (fu *fileReader) readLine() error {
var action Action
var tm int64
var line []byte
var err error
scanner := fu.scanner
for {
if ok := scanner.Scan(); !ok {
if err = scanner.Err(); err != nil {
return errors.Wrap(err, "scanner err")
}
// EOF
fu.eof = true
return nil
}
line = scanner.Bytes()
tm, action, err = fu.getTime(line)
if action == SKIP {
continue
} else if action == STOP {
return err
}
if fu.filter != nil {
newline, action, err := fu.filter(fu.filename, line)
if action == SKIP {
continue
} else if action == STOP {
return err
}
line = newline
}
break
}
fu.timestamp = tm
fu.line = line
return nil
}
func (fh *fileHeap) merge() error {
writer := fh.writer
for (*fh).Len() > 0 {
fr := heap.Pop(fh).(*fileReader)
if _, err := writer.WriteString(string(fr.line) + "\n"); err != nil {
return errors.Wrap(err, "writer writeString")
}
writer.Flush()
err := fr.readLine()
if err != nil {
return err
}
if !fr.eof {
heap.Push(fh, fr)
}
}
return nil
}
func merge(readers []*bufio.Scanner, writer *bufio.Writer, getTime TimeHandler, filter FilterHandler) error {
fHeap := new(fileHeap)
heap.Init(fHeap)
for _, rd := range readers {
fr := &fileReader{
scanner: rd,
getTime: getTime,
filter: filter,
}
err := fr.readLine()
if err != nil {
return err
}
if !fr.eof {
heap.Push(fHeap, fr)
}
}
fHeap.writer = writer
return fHeap.merge()
}
func quickMerge(job *quickMergeJob) {
scanner := job.scanner
filter := job.filter
writer := job.writer
filename := job.filename
errChan := job.errChan
for {
select {
case <-job.ctx.Done():
return
default:
if ok := scanner.Scan(); !ok {
if err := scanner.Err(); err != nil {
errChan <- fmt.Errorf("scan %s error %s", filename, err.Error())
}
// EOF
return
}
line := scanner.Bytes()
if filter != nil {
newline, action, err := filter(filename, line)
if action == SKIP {
continue
} else if action == STOP {
errChan <- fmt.Errorf("filter: %s error %s", filename, err.Error())
close(writer)
return
}
line = newline
}
resline := make([]byte, len(line))
copy(resline, line)
writer <- resline
}
}
}
// Merge files to output file, and use getTime function to get timestamp.
func Merge(srcPath []string, dstPath string, getTime TimeHandler) error {
option := Option{
SrcPath: srcPath,
DstPath: dstPath,
GetTime: getTime,
}
return MergeByOption(option)
}
// Use option to control merge behaviour.
func MergeByOption(option Option) error {
if option.GetTime == nil {
return NEED_TIMEHANDLER
}
var scanners []*bufio.Scanner
for _, fp := range option.SrcPath {
fd, err := os.Open(fp)
if err != nil {
return err
}
defer fd.Close()
var s *bufio.Scanner
if option.SrcGzip {
gzReader, err := gzip.NewReader(fd)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("gzip newreader: %s ", fp))
}
defer gzReader.Close()
s = bufio.NewScanner(gzReader)
} else {
s = bufio.NewScanner(fd)
}
scanners = append(scanners, s)
}
var dstFd = option.DstWriter
if dstFd == nil {
fd, err := os.Create(option.DstPath)
if err != nil {
return err
}
defer fd.Close()
dstFd = fd
}
var writer *bufio.Writer
if option.DstGzip {
gzWriter := gzip.NewWriter(dstFd)
defer gzWriter.Close()
writer = bufio.NewWriter(gzWriter)
} else {
writer = bufio.NewWriter(dstFd)
}
err := merge(scanners, writer, option.GetTime, option.Filter)
if err != nil {
return err
}
if option.DeleteSrc {
for _, fp := range option.SrcPath {
os.Remove(fp)
}
}
return nil
}
// Quick merge used for without sorting
func QuickMerge(option Option) error {
var wg sync.WaitGroup
jobChan := make(chan *quickMergeJob, len(option.SrcPath))
writerChan := make(chan []byte, len(option.SrcPath)*100)
if option.ErrChan == nil {
return NEED_ERRCHAN
}
defer close(option.ErrChan)
if option.CTX == nil {
option.CTX = context.TODO()
}
finishedCount := 0
var mutex sync.Mutex
for i := 0; i < option.Goroutine; i++ {
wg.Add(1)
go func() {
for job := range jobChan {
quickMerge(job)
}
wg.Done()
mutex.Lock()
finishedCount++
if finishedCount == option.Goroutine {
close(writerChan)
}
mutex.Unlock()
}()
}
for _, fp := range option.SrcPath {
fd, err := os.Open(fp)
if err != nil {
option.ErrChan <- fmt.Errorf("open %s error: %s", fp, err.Error())
continue
}
defer fd.Close()
var scanner *bufio.Scanner
if option.SrcGzip {
gzReader, err := gzip.NewReader(fd)
if err != nil {
option.ErrChan <- fmt.Errorf("gzip.NewReader error: %s", err.Error())
continue
}
defer gzReader.Close()
scanner = bufio.NewScanner(gzReader)
} else {
scanner = bufio.NewScanner(fd)
}
var job = quickMergeJob{
scanner: scanner,
filename: filepath.Base(fp),
writer: writerChan,
filter: option.Filter,
errChan: option.ErrChan,
ctx: option.CTX,
}
jobChan <- &job
}
close(jobChan)
fd, err := os.Create(option.DstPath)
if err != nil {
option.ErrChan <- fmt.Errorf("create dst path %s error: %s", option.DstPath, err.Error())
return nil
}
defer fd.Close()
var writer *bufio.Writer
if option.DstGzip {
gzWriter := gzip.NewWriter(fd)
defer gzWriter.Close()
writer = bufio.NewWriter(gzWriter)
} else {
writer = bufio.NewWriter(fd)
}
loop:
for {
select {
case <-option.CTX.Done():
return nil
case line, ok := <-writerChan:
// chan closed
if !ok {
break loop
}
if _, err := writer.WriteString(string(line) + "\n"); err != nil {
option.ErrChan <- fmt.Errorf("write line error: %s", err.Error())
continue
}
writer.Flush()
}
}
wg.Wait()
return nil
}