forked from pingcap/tidb-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
319 lines (270 loc) · 6.24 KB
/
watcher.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
package watcher
import (
"io/ioutil"
"os"
"path/filepath"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/siddontang/go/sync2"
)
// errors created by Watcher
var (
ErrWatcherStarted = errors.New("watcher already started")
ErrWatcherClosed = errors.New("watcher already closed")
)
// Watcher watches for files or directory changes by polling
// currently, if multi operations applied to one file or directory, only one event (with single Op) will be sent
// the priority of Op is:
// 1. Modify
// 2. Chmod
// 3. Rename / Move
// 4. Create / Remove
type Watcher struct {
Events chan Event
Errors chan error
running sync2.AtomicInt32
closed chan struct{}
wg sync.WaitGroup
mu sync.Mutex
names map[string]struct{} // original added names needed to watch
files map[string]os.FileInfo // all latest watching files
}
// NewWatcher creates a new Watcher instance
func NewWatcher() *Watcher {
w := &Watcher{
Events: make(chan Event),
Errors: make(chan error),
closed: make(chan struct{}),
names: make(map[string]struct{}),
files: make(map[string]os.FileInfo),
}
return w
}
// Start starts the watching
func (w *Watcher) Start(d time.Duration) error {
if !w.running.CompareAndSwap(0, 1) {
return ErrWatcherStarted
}
select {
case <-w.closed:
return ErrWatcherClosed
default:
}
w.wg.Add(1)
go func() {
defer w.wg.Done()
w.doWatch(d)
}()
return nil
}
// Close stops the watching
func (w *Watcher) Close() {
if !w.running.CompareAndSwap(1, 0) {
return
}
close(w.closed)
w.wg.Wait()
close(w.Events)
close(w.Errors)
w.mu.Lock()
w.names = make(map[string]struct{})
w.files = make(map[string]os.FileInfo)
w.mu.Unlock()
}
// Add adds named file or directory (non-recursively) to the watching list
// this can only be success if all events be sent (lock release)
func (w *Watcher) Add(name string) error {
w.mu.Lock()
defer w.mu.Unlock()
select {
case <-w.closed:
return ErrWatcherClosed
default:
}
fileList, err := listForName(name)
if err != nil {
return errors.Trace(err)
}
w.names[name] = struct{}{}
for fp, fi := range fileList {
w.files[fp] = fi
}
return nil
}
// Remove removes named file or directory (non-recursively) from the watching list
// this can only be success if all events be sent (lock release)
func (w *Watcher) Remove(name string) error {
w.mu.Lock()
defer w.mu.Unlock()
select {
case <-w.closed:
return ErrWatcherClosed
default:
}
w.doRemove(name)
return nil
}
// doRemove does the actual remove operation
// it does not consider the mutex protection
func (w *Watcher) doRemove(name string) {
delete(w.names, name)
fi, ok := w.files[name]
if !ok {
return // not exists anymore
}
// remove itself
delete(w.files, name)
if !fi.IsDir() {
// not a directory, return
return
}
for fp := range w.files {
// remove all files in this directory
if filepath.Dir(fp) == name {
delete(w.files, fp)
}
}
}
// doWatch does the watching
func (w *Watcher) doWatch(d time.Duration) {
ticker := time.NewTicker(d)
defer ticker.Stop()
for {
select {
case <-w.closed:
return
case <-ticker.C:
currFileList := w.listForAll()
w.pollEvents(currFileList)
// update file list
w.mu.Lock()
w.files = currFileList
w.mu.Unlock()
}
}
}
// pollEvents polls events for files
func (w *Watcher) pollEvents(currFileList map[string]os.FileInfo) {
w.mu.Lock()
defer w.mu.Unlock()
creates := make(map[string]os.FileInfo)
removes := make(map[string]os.FileInfo)
// check for remove
for latestFp, latestFi := range w.files {
if _, ok := currFileList[latestFp]; !ok {
removes[latestFp] = latestFi
}
}
// check for create / modify / chmod
for fp, currFi := range currFileList {
latestFi, ok := w.files[fp]
if !ok {
// create
creates[fp] = currFi
continue
}
// ModTime may return timestamp in second level on some file system
// So use ModTime + Size to judge modify event will be more precisely
if !latestFi.ModTime().Equal(currFi.ModTime()) ||
latestFi.Size() != currFi.Size() {
// modify
select {
case <-w.closed:
return
case w.Events <- Event{Path: fp, Op: Modify, FileInfo: currFi}:
}
}
if latestFi.Mode() != currFi.Mode() {
// chmod
select {
case <-w.closed:
return
case w.Events <- Event{Path: fp, Op: Chmod, FileInfo: currFi}:
}
}
}
// check for rename / move
for removeFp, removeFi := range removes {
for createFp, createFi := range creates {
if os.SameFile(removeFi, createFi) {
ev := Event{
Path: removeFp, // for Move, use from-path
Op: Move,
FileInfo: removeFi,
}
if filepath.Dir(removeFp) == filepath.Dir(createFp) {
ev.Op = Rename
}
delete(removes, removeFp)
delete(creates, createFp)
select {
case <-w.closed:
return
case w.Events <- ev:
}
}
}
}
// send events for create
for fp, fi := range creates {
select {
case <-w.closed:
return
case w.Events <- Event{Path: fp, Op: Create, FileInfo: fi}:
}
}
// send events for remove
for fp, fi := range removes {
select {
case <-w.closed:
return
case w.Events <- Event{Path: fp, Op: Remove, FileInfo: fi}:
}
}
}
// listForAll returns a list of files info for all watching files and directories currently
func (w *Watcher) listForAll() map[string]os.FileInfo {
w.mu.Lock()
defer w.mu.Unlock()
fileList := make(map[string]os.FileInfo)
for name := range w.names {
fl, err := listForName(name)
if err != nil {
if os.IsNotExist(errors.Cause(err)) {
w.doRemove(name)
}
select {
case <-w.closed:
return nil
case w.Errors <- err:
}
}
for fp, fi := range fl {
fileList[fp] = fi
}
}
return fileList
}
// listForName returns a list of files info for this file or files in this directory
func listForName(name string) (map[string]os.FileInfo, error) {
stat, err := os.Stat(name)
if err != nil {
return nil, errors.Annotatef(err, "name %s", name)
}
list := make(map[string]os.FileInfo)
list[name] = stat
if !stat.IsDir() {
// not a directory, return
return list, nil
}
fInfoList, err := ioutil.ReadDir(name)
if err != nil {
return nil, errors.Annotatef(err, "directory %s", name)
}
for _, fi := range fInfoList {
fp := filepath.Join(name, fi.Name())
list[fp] = fi
}
return list, nil
}