-
Notifications
You must be signed in to change notification settings - Fork 1
/
tail.go
482 lines (431 loc) · 11 KB
/
tail.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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package tail
import (
"bufio"
"context"
"fmt"
"io"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/masahide/ftailer/watch"
)
var (
// ErrStop tailを停止
ErrStop = fmt.Errorf("tail should now stop")
)
const (
NewLineNotify int = iota
NewFileNotify
TickerNotify
)
type Line struct {
Time time.Time
Text []byte
Filename string
Offset int64
OpenTime time.Time
Err error // Error from tail
NotifyType int
}
// newLine returns a Line with present time.
func newLine(text []byte) *Line {
return &Line{Text: text, Time: time.Now(), Err: nil}
}
// SeekInfo represents arguments to `os.Seek`
type SeekInfo struct {
Offset int64
Whence int // os.SEEK_*
}
// Config is used to specify how a file must be tailed.
type Config struct {
// File-specifc
Location *SeekInfo // Seek to this location before tailing
ReOpen bool // Reopen recreated files (tail -F)
ReOpenDelay time.Duration // Reopen Delay
MustExist bool // Fail early if the file does not exist
Poll bool // Poll for file changes instead of using inotify
TruncateReOpen bool // copytruncate rotate
RenameReOpen bool // rename rotate
LinesChanSize int // Lines channel size
// Generic IO
NotifyInterval time.Duration // Notice interval of the elapsed time
}
type Tail struct {
Filename string
Lines chan *Line
Config
tracker *watch.InotifyTracker
ticker *time.Ticker
openTime time.Time
WorkLimit chan bool
watcher watch.FileWatcher
changes *watch.FileChanges
Ctx context.Context
Cancel context.CancelFunc
reader *bufio.Reader
file *os.File
mu sync.RWMutex
//lastDelChReceived time.Time // Last delete channel received time
}
// TailFile begins tailing the file. Output stream is made available
// via the `Tail.Lines` channel. To handle errors during tailing,
// invoke the `Wait` or `Err` method after finishing reading from the
// `Lines` channel.
func TailFile(ctx context.Context, filename string, config Config, w chan bool) (*Tail, error) {
t := &Tail{
Filename: filename,
Lines: make(chan *Line, config.LinesChanSize),
Config: config,
WorkLimit: w,
}
t.Ctx, t.Cancel = context.WithCancel(ctx)
if t.Poll {
t.watcher = watch.NewPollingFileWatcher(filename)
} else {
t.tracker = watch.NewInotifyTracker()
w, err := t.tracker.NewWatcher(ctx)
if err != nil {
return nil, err
}
dw, err := t.tracker.NewWatcher(ctx)
if err != nil {
return nil, err
}
dirname := filepath.Dir(t.Filename)
// Watch for new files to be created in the parent directory.
err = dw.Watch(dirname)
if err != nil {
return nil, err
}
log.Printf("start InotifyFileWatcher: %s", filename)
t.watcher = watch.NewInotifyFileWatcher(filename, dw, w, t.ReOpenDelay)
}
if t.MustExist {
file, err := os.Open(t.Filename)
if err != nil {
return nil, err
}
t.setFile(file)
}
go t.tailFileSync()
return t, nil
}
func (tail *Tail) getFile() *os.File {
tail.mu.RLock()
defer tail.mu.RUnlock()
return tail.file
}
func (tail *Tail) setFile(file *os.File) {
tail.mu.Lock()
defer tail.mu.Unlock()
tail.file = file
}
func (tail *Tail) fileStat() (os.FileInfo, error) {
tail.mu.Lock()
defer tail.mu.Unlock()
return tail.file.Stat()
}
func (tail *Tail) fileSeek(offset int64, whence int) (ret int64, err error) {
tail.mu.Lock()
defer tail.mu.Unlock()
return tail.file.Seek(offset, whence)
}
func (tail *Tail) fileClose() (err error) {
tail.mu.Lock()
defer tail.mu.Unlock()
return tail.file.Close()
}
func (tail *Tail) readerBuffered() int {
tail.mu.RLock()
defer tail.mu.RUnlock()
return tail.reader.Buffered()
}
func (tail *Tail) readerReset(r io.Reader) {
tail.mu.Lock()
defer tail.mu.Unlock()
tail.reader.Reset(r)
}
func (tail *Tail) setReader(r io.Reader) {
tail.mu.Lock()
defer tail.mu.Unlock()
tail.reader = bufio.NewReader(r)
}
func (tail *Tail) readerReadBytes(delim byte) (line []byte, err error) {
tail.mu.Lock()
defer tail.mu.Unlock()
return tail.reader.ReadBytes(delim)
}
// Tell Return the file's current position, like stdio's ftell().
func (tail *Tail) Tell() (offset int64, err error) {
return tail.tell()
}
func (tail *Tail) tell() (offset int64, err error) {
if tail.getFile() == nil {
return
}
offset, err = tail.fileSeek(0, os.SEEK_CUR)
if err == nil {
offset -= int64(tail.readerBuffered())
}
return
}
func (tail *Tail) close() {
if tail.getFile() != nil {
if err := tail.fileClose(); err != nil {
log.Printf("tail.file.Close err:%s", err)
}
}
tail.setFile(nil)
}
func (tail *Tail) reopen(ctx context.Context) error {
if tail.getFile() != nil {
if err := tail.fileClose(); err != nil {
log.Printf("reopen error. file.Close:%s", err)
return err
}
}
for {
file, err := os.Open(tail.Filename)
if err != nil {
if os.IsNotExist(err) {
log.Printf("Waiting for %s to appear...", tail.Filename)
if err := tail.watcher.BlockUntilExists(ctx); err != nil {
return fmt.Errorf("Failed to detect creation of %s: %s", tail.Filename, err)
}
continue
}
return fmt.Errorf("Unable to open file %s: %s", tail.Filename, err)
}
tail.setFile(file)
break
}
return nil
}
func (tail *Tail) readLine() ([]byte, error) {
select {
case tail.WorkLimit <- true:
defer func() { <-tail.WorkLimit }()
case <-tail.Ctx.Done():
return nil, tail.Ctx.Err()
}
line, err := tail.readerReadBytes(byte('\n'))
if err != nil {
// Note ReadString "returns the data read before the error" in
// case of an error, including EOF, so we return it as is. The
// caller is expected to process it if err is EOF.
return line, err
}
//line = bytes.TrimRight(line, "\n")
return line, err
}
func (tail *Tail) tailFileSync() {
// defer tail.Done()
defer tail.Cancel()
defer tail.close()
tail.ticker = &time.Ticker{}
if tail.NotifyInterval != 0 {
tail.ticker = time.NewTicker(tail.NotifyInterval)
}
defer tail.ticker.Stop()
if !tail.MustExist {
// deferred first open.
err := tail.reopen(tail.Ctx)
if err != nil {
log.Printf("tail.reopen() err: %s", err)
return
}
}
// Seek to requested location on first open of the file.
offset := int64(0)
if tail.Location != nil {
offset = tail.Location.Offset
_, err := tail.fileSeek(offset, tail.Location.Whence)
log.Printf("Seeked %s - %+v\n", tail.Filename, tail.Location)
if err != nil {
log.Printf("Seek error on %s: %s", tail.Filename, err)
return
}
}
tail.openReader()
select {
case tail.Lines <- &Line{NotifyType: NewFileNotify, Filename: tail.Filename, Offset: offset, Time: time.Now(), OpenTime: tail.openTime}:
case <-tail.Ctx.Done():
return
}
// Read line by line.
for {
err := tail.readSend()
if err == io.EOF {
// When EOF is reached, wait for more data to become
// available. Wait strategy is based on the `tail.watcher`
// implementation (inotify or polling).
err := tail.waitForChanges(tail.Ctx)
if err != nil {
if err != ErrStop {
log.Printf("tail.waitForChanges() err: %s", err)
}
return
}
} else if err != nil {
// non-EOF error
log.Printf("Error reading %s: %s", tail.Filename, err)
tail.Cancel()
return
}
select {
case <-tail.Ctx.Done():
return
default:
}
}
}
func (tail *Tail) readSend() error {
offset, err := tail.tell()
if err != nil {
log.Printf("tail.tell() err: %s", err)
return err
}
line, err := tail.readLine()
// Process `line` even if err is EOF.
if err == nil {
err = tail.sendLine(line)
if err != nil {
log.Printf("tail.sendLine() err: %s", err)
return err
}
return nil
}
if err != io.EOF {
return err
}
if len(line) != 0 {
// this has the potential to never return the last line if
// it's not followed by a newline; seems a fair trade here
err := tail.seekTo(SeekInfo{Offset: offset, Whence: 0})
if err != nil {
log.Printf("tail.seekTo() err: %s", err)
return err
}
}
return io.EOF
}
// waitForChanges waits until the file has been appended, deleted,
// moved or truncated. When moved or deleted - the file will be
// reopened if ReOpen is true. Truncated files are always reopened.
func (tail *Tail) waitForChanges(ctx context.Context) error {
if tail.changes == nil {
st, err := tail.fileStat()
if err != nil {
return err
}
tail.changes = tail.watcher.ChangeEvents(ctx, st)
}
for {
select {
case <-tail.ticker.C:
offset, err := tail.tell()
if err != nil {
return err
}
select {
case tail.Lines <- &Line{NotifyType: TickerNotify, Time: time.Now(), Filename: tail.Filename, OpenTime: tail.openTime, Offset: offset}:
case <-ctx.Done():
return nil
}
continue
case mode := <-tail.changes.Modified:
switch mode {
case watch.None, watch.Modified:
return nil
case watch.Rotated:
if err := tail.readSendAll(); err != nil {
return err
}
if tail.ReOpen {
log.Printf("Rotated event file %s. Re-opening ...", tail.Filename)
tail.changes = nil
if err := tail.reopen(ctx); err != nil {
return err
}
log.Printf("Successfully reopened %s", tail.Filename)
tail.openReader()
select {
case tail.Lines <- &Line{NotifyType: NewFileNotify, Filename: tail.Filename, Offset: 0, Time: time.Now(), OpenTime: tail.openTime}:
case <-ctx.Done():
}
return nil
}
tail.changes = nil
log.Printf("Stopping tail as file no longer exists: %s", tail.Filename)
return ErrStop
default:
log.Printf("tail.changes.Modified: mode:%v", mode)
if err := tail.readSendAll(); err != nil {
return err
}
return ErrStop
}
case <-ctx.Done():
return ErrStop
}
}
}
func (tail *Tail) readSendAll() error {
for {
err := tail.readSend()
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return nil
}
func (tail *Tail) openReader() {
tail.setReader(tail.getFile())
fi, err := os.Stat(tail.Filename)
if err != nil {
tail.openTime = time.Now()
return
}
tail.openTime = fi.ModTime()
}
func (tail *Tail) seekEnd() error {
return tail.seekTo(SeekInfo{Offset: 0, Whence: 2})
}
func (tail *Tail) seekTo(pos SeekInfo) error {
_, err := tail.fileSeek(pos.Offset, pos.Whence)
if err != nil {
return fmt.Errorf("Seek error on %s: %s", tail.Filename, err)
}
// Reset the read buffer whenever the file is re-seek'ed
tail.readerReset(tail.getFile())
return nil
}
// sendLine sends the line(s) to Lines channel, splitting longer lines
// if necessary. Return false if rate limit is reached.
func (tail *Tail) sendLine(line []byte) error {
now := time.Now()
offset, err := tail.tell()
if err != nil {
//tail.Kill(err)
return err
}
select {
case tail.Lines <- &Line{NotifyType: NewLineNotify, Text: line, Time: now, Filename: tail.Filename, OpenTime: tail.openTime, Offset: offset}:
case <-tail.Ctx.Done():
}
return nil
}
// Cleanup removes inotify watches added by the tail package. This function is
// meant to be invoked from a process's exit handler. Linux kernel may not
// automatically remove inotify watches after the process exits.
func (tail *Tail) Cleanup(ctx context.Context) {
if tail.tracker != nil {
tail.tracker.CloseAll(ctx)
}
tail.Cancel()
}