tail/watch/inotify.go

120 lines
2.3 KiB
Go
Raw Normal View History

// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
package watch
import (
"fmt"
2015-07-01 23:15:15 +08:00
"os"
"path/filepath"
2015-09-30 22:48:17 +08:00
"github.com/hpcloud/tail/util"
"gopkg.in/fsnotify.v0"
"gopkg.in/tomb.v1"
)
// InotifyFileWatcher uses inotify to monitor file changes.
type InotifyFileWatcher struct {
Filename string
Size int64
2015-07-01 23:15:15 +08:00
w *fsnotify.Watcher
}
2015-07-01 23:15:15 +08:00
func NewInotifyFileWatcher(filename string, w *fsnotify.Watcher) *InotifyFileWatcher {
fw := &InotifyFileWatcher{filename, 0, w}
return fw
}
2013-09-23 15:03:51 +08:00
func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error {
dirname := filepath.Dir(fw.Filename)
// Watch for new files to be created in the parent directory.
2015-07-01 23:15:15 +08:00
err := fw.w.WatchFlags(dirname, fsnotify.FSN_CREATE)
if err != nil {
return err
}
2015-07-01 23:15:15 +08:00
defer fw.w.RemoveWatch(dirname)
// Do a real check now as the file might have been created before
// calling `WatchFlags` above.
if _, err = os.Stat(fw.Filename); !os.IsNotExist(err) {
// file exists, or stat returned an error.
return err
}
for {
select {
2015-07-01 23:15:15 +08:00
case evt, ok := <-fw.w.Event:
if !ok {
return fmt.Errorf("inotify watcher has been closed")
} else if evt.Name == fw.Filename {
return nil
}
case <-t.Dying():
return tomb.ErrDying
}
}
panic("unreachable")
}
2013-09-23 15:03:51 +08:00
func (fw *InotifyFileWatcher) ChangeEvents(t *tomb.Tomb, fi os.FileInfo) *FileChanges {
changes := NewFileChanges()
2013-09-23 15:03:51 +08:00
2015-07-01 23:15:15 +08:00
err := fw.w.Watch(fw.Filename)
if err != nil {
util.Fatal("Error watching %v: %v", fw.Filename, err)
}
fw.Size = fi.Size()
go func() {
2015-07-01 23:15:15 +08:00
defer fw.w.RemoveWatch(fw.Filename)
defer changes.Close()
for {
prevSize := fw.Size
var evt *fsnotify.FileEvent
var ok bool
select {
2015-07-01 23:15:15 +08:00
case evt, ok = <-fw.w.Event:
if !ok {
return
}
case <-t.Dying():
return
}
switch {
case evt.IsDelete():
fallthrough
case evt.IsRename():
changes.NotifyDeleted()
return
case evt.IsModify():
fi, err := os.Stat(fw.Filename)
if err != nil {
if os.IsNotExist(err) {
changes.NotifyDeleted()
return
}
// XXX: report this error back to the user
util.Fatal("Failed to stat file %v: %v", fw.Filename, err)
}
fw.Size = fi.Size()
if prevSize > 0 && prevSize > fw.Size {
changes.NotifyTruncated()
2013-09-23 15:03:51 +08:00
} else {
changes.NotifyModified()
}
prevSize = fw.Size
}
}
}()
return changes
}