-
Notifications
You must be signed in to change notification settings - Fork 248
/
poller.go
330 lines (275 loc) · 6.65 KB
/
poller.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
// Adapted from https://github.com/gohugoio/hugo
// Apache License 2.0
// Copyright Hugo Authors
// Package filenotify is adapted from https://github.com/moby/moby/tree/master/pkg/filenotify, Apache-2.0 License.
// Hopefully this can be replaced with an external package sometime in the future, see https://github.com/fsnotify/fsnotify/issues/9
package filenotify
import (
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/fsnotify/fsnotify"
)
var (
// errPollerClosed is returned when the poller is closed
errPollerClosed = errors.New("poller is closed")
// errNoSuchWatch is returned when trying to remove a watch that doesn't exist
errNoSuchWatch = errors.New("watch does not exist")
)
// filePoller is used to poll files for changes, especially in cases where fsnotify
// can't be run (e.g. when inotify handles are exhausted)
// filePoller satisfies the FileWatcher interface
type filePoller struct {
// the duration between polls.
interval time.Duration
// watches is the list of files currently being polled, close the associated channel to stop the watch
watches map[string]struct{}
// Will be closed when done.
done chan struct{}
// events is the channel to listen to for watch events
events chan fsnotify.Event
// errors is the channel to listen to for watch errors
errors chan error
// mu locks the poller for modification
mu sync.Mutex
// closed is used to specify when the poller has already closed
closed bool
}
// Add adds a filename to the list of watches
// once added the file is polled for changes in a separate goroutine
func (w *filePoller) Add(name string) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.closed {
return errPollerClosed
}
item, err := newItemToWatch(name)
if err != nil {
return err
}
if item.left.FileInfo == nil {
return os.ErrNotExist
}
if w.watches == nil {
w.watches = make(map[string]struct{})
}
if _, exists := w.watches[name]; exists {
return fmt.Errorf("watch exists")
}
w.watches[name] = struct{}{}
go w.watch(item)
return nil
}
// Remove stops and removes watch with the specified name
func (w *filePoller) Remove(name string) error {
w.mu.Lock()
defer w.mu.Unlock()
return w.remove(name)
}
func (w *filePoller) remove(name string) error {
if w.closed {
return errPollerClosed
}
_, exists := w.watches[name]
if !exists {
return errNoSuchWatch
}
delete(w.watches, name)
return nil
}
// Events returns the event channel
// This is used for notifications on events about watched files
func (w *filePoller) Events() <-chan fsnotify.Event {
return w.events
}
// Errors returns the errors channel
// This is used for notifications about errors on watched files
func (w *filePoller) Errors() <-chan error {
return w.errors
}
// Close closes the poller
// All watches are stopped, removed, and the poller cannot be added to
func (w *filePoller) Close() error {
w.mu.Lock()
defer w.mu.Unlock()
if w.closed {
return nil
}
w.closed = true
close(w.done)
for name := range w.watches {
w.remove(name)
}
return nil
}
// sendEvent publishes the specified event to the events channel
func (w *filePoller) sendEvent(e fsnotify.Event) error {
select {
case w.events <- e:
case <-w.done:
return fmt.Errorf("closed")
}
return nil
}
// sendErr publishes the specified error to the errors channel
func (w *filePoller) sendErr(e error) error {
select {
case w.errors <- e:
case <-w.done:
return fmt.Errorf("closed")
}
return nil
}
// watch watches item for changes until done is closed.
func (w *filePoller) watch(item *itemToWatch) {
ticker := time.NewTicker(w.interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
case <-w.done:
return
}
evs, err := item.checkForChanges()
if err != nil {
if err := w.sendErr(err); err != nil {
return
}
}
item.left, item.right = item.right, item.left
for _, ev := range evs {
if err := w.sendEvent(ev); err != nil {
return
}
}
}
}
// recording records the state of a file or a dir.
type recording struct {
os.FileInfo
// Set if FileInfo is a dir.
entries map[string]os.FileInfo
}
func (r *recording) clear() {
r.FileInfo = nil
if r.entries != nil {
for k := range r.entries {
delete(r.entries, k)
}
}
}
func (r *recording) record(filename string) error {
r.clear()
fi, err := os.Stat(filename)
if err != nil && !os.IsNotExist(err) {
return err
}
if fi == nil {
return nil
}
r.FileInfo = fi
// If fi is a dir, we watch the files inside that directory (not recursively).
// This matches the behaviour of fsnotity.
if fi.IsDir() {
f, err := os.Open(filename)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
defer f.Close()
fis, err := f.Readdir(-1)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
for _, fi := range fis {
r.entries[fi.Name()] = fi
}
}
return nil
}
// itemToWatch may be a file or a dir.
type itemToWatch struct {
// Full path to the filename.
filename string
// Snapshots of the stat state of this file or dir.
left *recording
right *recording
}
func newItemToWatch(filename string) (*itemToWatch, error) {
r := &recording{
entries: make(map[string]os.FileInfo),
}
err := r.record(filename)
if err != nil {
return nil, err
}
return &itemToWatch{filename: filename, left: r}, nil
}
func (item *itemToWatch) checkForChanges() ([]fsnotify.Event, error) {
if item.right == nil {
item.right = &recording{
entries: make(map[string]os.FileInfo),
}
}
err := item.right.record(item.filename)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
dirOp := checkChange(item.left.FileInfo, item.right.FileInfo)
if dirOp != 0 {
evs := []fsnotify.Event{fsnotify.Event{Op: dirOp, Name: item.filename}}
return evs, nil
}
if item.left.FileInfo == nil || !item.left.IsDir() {
// Done.
return nil, nil
}
leftIsIn := false
left, right := item.left.entries, item.right.entries
if len(right) > len(left) {
left, right = right, left
leftIsIn = true
}
var evs []fsnotify.Event
for name, fi1 := range left {
fi2 := right[name]
fil, fir := fi1, fi2
if leftIsIn {
fil, fir = fir, fil
}
op := checkChange(fil, fir)
if op != 0 {
evs = append(evs, fsnotify.Event{Op: op, Name: filepath.Join(item.filename, name)})
}
}
return evs, nil
}
func checkChange(fi1, fi2 os.FileInfo) fsnotify.Op {
if fi1 == nil && fi2 != nil {
return fsnotify.Create
}
if fi1 != nil && fi2 == nil {
return fsnotify.Remove
}
if fi1 == nil && fi2 == nil {
return 0
}
if fi1.IsDir() || fi2.IsDir() {
return 0
}
if fi1.Mode() != fi2.Mode() {
return fsnotify.Chmod
}
if fi1.ModTime() != fi2.ModTime() || fi1.Size() != fi2.Size() {
return fsnotify.Write
}
return 0
}