forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventreader_fsnotify.go
105 lines (91 loc) · 2.34 KB
/
eventreader_fsnotify.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
// +build linux freebsd openbsd netbsd windows
package file_integrity
import (
"syscall"
"time"
"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
"github.com/elastic/beats/auditbeat/module/file_integrity/monitor"
"github.com/elastic/beats/libbeat/logp"
)
type reader struct {
watcher monitor.Watcher
config Config
eventC chan Event
log *logp.Logger
}
// NewEventReader creates a new EventProducer backed by fsnotify.
func NewEventReader(c Config) (EventProducer, error) {
watcher, err := monitor.New(c.Recursive)
if err != nil {
return nil, err
}
return &reader{
watcher: watcher,
config: c,
eventC: make(chan Event, 1),
log: logp.NewLogger(moduleName),
}, nil
}
func (r *reader) Start(done <-chan struct{}) (<-chan Event, error) {
for _, p := range r.config.Paths {
if err := r.watcher.Add(p); err != nil {
if err == syscall.EMFILE {
r.log.Warnw("Failed to add watch (check the max number of "+
"open files allowed with 'ulimit -a')",
"file_path", p, "error", err)
} else {
r.log.Warnw("Failed to add watch", "file_path", p, "error", err)
}
}
}
if err := r.watcher.Start(); err != nil {
return nil, errors.Wrap(err, "unable to start watcher")
}
go r.consumeEvents(done)
r.log.Infow("Started fsnotify watcher",
"file_path", r.config.Paths,
"recursive", r.config.Recursive)
return r.eventC, nil
}
func (r *reader) consumeEvents(done <-chan struct{}) {
defer close(r.eventC)
defer r.watcher.Close()
for {
select {
case <-done:
r.log.Debug("fsnotify reader terminated")
return
case event := <-r.watcher.EventChannel():
if event.Name == "" || r.config.IsExcludedPath(event.Name) {
continue
}
r.log.Debugw("Received fsnotify event",
"file_path", event.Name,
"event_flags", event.Op)
start := time.Now()
e := NewEvent(event.Name, opToAction(event.Op), SourceFSNotify,
r.config.MaxFileSizeBytes, r.config.HashTypes)
e.rtt = time.Since(start)
r.eventC <- e
case err := <-r.watcher.ErrorChannel():
r.log.Warnw("fsnotify watcher error", "error", err)
}
}
}
func opToAction(op fsnotify.Op) Action {
switch op {
case fsnotify.Create:
return Created
case fsnotify.Write:
return Updated
case fsnotify.Remove:
return Deleted
case fsnotify.Rename:
return Moved
case fsnotify.Chmod:
return AttributesModified
default:
return 0
}
}