Add support for file truncation in InotifyFileWatcher

(cherry picked from commit 9de77aad8caca8102e7dd7c936d00ca3f0421ca7)
This commit is contained in:
Florian Weingarten 2013-05-10 14:18:00 -04:00 committed by Sridhar Ratnakumar
parent e9c3c07fbb
commit 1ff299bc29
2 changed files with 18 additions and 6 deletions

View File

@ -190,7 +190,7 @@ func (tail *Tail) tailFileSync() {
// File got deleted/renamed // File got deleted/renamed
if tail.ReOpen { if tail.ReOpen {
// TODO: no logging in a library? // TODO: no logging in a library?
log.Printf("Re-opening moved/deleted file %s ...", tail.Filename) log.Printf("Re-opening moved/deleted/truncated file %s ...", tail.Filename)
err := tail.reopen() err := tail.reopen()
if err != nil { if err != nil {
tail.close() tail.close()

View File

@ -24,10 +24,11 @@ type FileWatcher interface {
// InotifyFileWatcher uses inotify to monitor file changes. // InotifyFileWatcher uses inotify to monitor file changes.
type InotifyFileWatcher struct { type InotifyFileWatcher struct {
Filename string Filename string
Size int64
} }
func NewInotifyFileWatcher(filename string) *InotifyFileWatcher { func NewInotifyFileWatcher(filename string) *InotifyFileWatcher {
fw := &InotifyFileWatcher{filename} fw := &InotifyFileWatcher{filename, 0}
return fw return fw
} }
@ -65,19 +66,29 @@ func (fw *InotifyFileWatcher) ChangeEvents(_ os.FileInfo) chan bool {
ch := make(chan bool) ch := make(chan bool)
go func() { go func() {
defer w.Close()
defer w.RemoveWatch(fw.Filename)
defer close(ch)
for { for {
prevSize := fw.Size
evt := <-w.Event evt := <-w.Event
switch { switch {
case evt.IsDelete(): case evt.IsDelete():
fallthrough fallthrough
case evt.IsRename(): case evt.IsRename():
close(ch)
w.RemoveWatch(fw.Filename)
w.Close()
return return
case evt.IsModify(): case evt.IsModify():
fi, _ := os.Stat(fw.Filename)
fw.Size = fi.Size()
if prevSize > 0 && prevSize > fw.Size {
return
}
// send only if channel is empty. // send only if channel is empty.
select { select {
case ch <- true: case ch <- true:
@ -93,10 +104,11 @@ func (fw *InotifyFileWatcher) ChangeEvents(_ os.FileInfo) chan bool {
// PollingFileWatcher polls the file for changes. // PollingFileWatcher polls the file for changes.
type PollingFileWatcher struct { type PollingFileWatcher struct {
Filename string Filename string
Size int64
} }
func NewPollingFileWatcher(filename string) *PollingFileWatcher { func NewPollingFileWatcher(filename string) *PollingFileWatcher {
fw := &PollingFileWatcher{filename} fw := &PollingFileWatcher{filename, 0}
return fw return fw
} }