-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathinotify.go
527 lines (426 loc) · 9.5 KB
/
inotify.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//go:build linux
// +build linux
package gonotify
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"github.com/illarion/gonotify/v3/syscallf"
)
const (
// maxEvents is the maximum number of events to read in one syscall
maxEvents = 1024
)
type addWatchResult struct {
wd int
err error
}
type addWatchRequest struct {
pathName string
mask uint32
result chan addWatchResult
}
type rmWdRequest struct {
wd int
ignored bool // if true, the watch was removed automatically
result chan error
}
type rmPathRequest struct {
pathName string
result chan error
}
type eventItem struct {
InotifyEvent
err error
}
// Inotify is the low level wrapper around inotify_init(), inotify_add_watch() and inotify_rm_watch()
type Inotify struct {
ctx context.Context
done chan struct{}
addWatchIn chan addWatchRequest
rmByWdIn chan rmWdRequest
rmByPathIn chan rmPathRequest
eventsOut chan eventItem
readMutex sync.Mutex
}
// NewInotify creates new inotify instance
func NewInotify(ctx context.Context) (*Inotify, error) {
fd, err := syscall.InotifyInit1(syscall.IN_CLOEXEC | syscall.IN_NONBLOCK)
if err != nil {
return nil, err
}
file := os.NewFile(uintptr(fd), "inotify")
inotify := &Inotify{
ctx: ctx,
done: make(chan struct{}),
addWatchIn: make(chan addWatchRequest),
rmByWdIn: make(chan rmWdRequest),
rmByPathIn: make(chan rmPathRequest),
eventsOut: make(chan eventItem, maxEvents),
}
type getPathRequest struct {
wd int
result chan string
}
getPathIn := make(chan getPathRequest)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
//defer cancel()
<-ctx.Done()
//file.Close()
wg.Done()
}()
wg.Add(1)
// read events goroutine. Only this goroutine can read or close the inotify file descriptor
go func() {
defer wg.Done()
defer close(inotify.eventsOut)
// reusable buffers for reading inotify events. Make sure they're not
// leaked into other goroutines, as they're not thread safe
buf := make([]byte, maxEvents*(syscall.SizeofInotifyEvent+syscall.NAME_MAX+1))
for {
select {
case <-ctx.Done():
return
default:
}
var n int
for {
select {
case <-ctx.Done():
return
default:
}
n, err = file.Read(buf)
if err != nil {
// if we got an error, we should return
select {
case inotify.eventsOut <- eventItem{
InotifyEvent: InotifyEvent{},
err: err,
}:
default:
}
return
}
if n > 0 {
break
}
}
if n < syscall.SizeofInotifyEvent {
select {
case <-ctx.Done():
return
default:
continue
}
}
offset := 0
for offset+syscall.SizeofInotifyEvent <= n {
event := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset]))
var name string
{
nameStart := offset + syscall.SizeofInotifyEvent
nameEnd := offset + syscall.SizeofInotifyEvent + int(event.Len)
if nameEnd > n {
continue
}
name = strings.TrimRight(string(buf[nameStart:nameEnd]), "\x00")
offset = nameEnd
}
req := getPathRequest{wd: int(event.Wd), result: make(chan string)}
var watchName string
select {
case <-ctx.Done():
return
case getPathIn <- req:
select {
case <-ctx.Done():
return
case watchName = <-req.result:
}
}
if watchName == "" {
continue
}
name = filepath.Join(watchName, name)
inotifyEvent := InotifyEvent{
Wd: int(event.Wd),
Name: name,
Mask: event.Mask,
Cookie: event.Cookie,
}
// watch was removed explicitly or automatically
if inotifyEvent.Is(IN_IGNORED) {
// remove watch
result := make(chan error)
select {
case <-ctx.Done():
return
case inotify.rmByWdIn <- rmWdRequest{
wd: int(event.Wd),
ignored: true,
result: result,
}:
case <-time.After(1 * time.Second):
}
select {
case <-ctx.Done():
return
case err := <-result:
if err != nil {
// TODO log error
}
}
continue
}
select {
case <-ctx.Done():
return
case inotify.eventsOut <- eventItem{
InotifyEvent: inotifyEvent,
err: nil,
}:
}
}
}
}()
wg.Add(1)
// main goroutine (handle channels)
go func() {
//defer cancel()
defer wg.Done()
watches := make(map[string]int)
paths := make(map[int]string)
for {
select {
case <-ctx.Done():
// Handle pending requests
draining := true
for draining {
select {
case req := <-inotify.addWatchIn:
// Send error to addWatch requests
select {
case req.result <- addWatchResult{
wd: 0,
err: errors.New("Inotify instance closed"),
}:
default:
}
case <-inotify.rmByWdIn:
case <-inotify.addWatchIn:
case <-inotify.rmByPathIn:
case <-getPathIn:
default:
draining = false
}
}
for _, w := range watches {
_, err := syscallf.InotifyRmWatch(fd, w)
if err != nil {
continue
}
}
return
case req := <-inotify.addWatchIn:
wd, err := syscall.InotifyAddWatch(fd, req.pathName, req.mask)
if err == nil {
watches[req.pathName] = wd
paths[wd] = req.pathName
}
select {
case req.result <- addWatchResult{wd: wd, err: err}:
case <-ctx.Done():
}
case req := <-inotify.rmByWdIn:
pathName, ok := paths[req.wd]
if !ok {
continue
}
if !req.ignored {
_, err = syscallf.InotifyRmWatch(fd, req.wd)
}
delete(watches, pathName)
delete(paths, req.wd)
select {
case req.result <- err:
case <-ctx.Done():
}
case req := <-inotify.rmByPathIn:
wd, ok := watches[req.pathName]
if !ok {
continue
}
_, err := syscallf.InotifyRmWatch(fd, wd)
delete(watches, req.pathName)
delete(paths, wd)
select {
case req.result <- err:
case <-ctx.Done():
}
case req := <-getPathIn:
wd := paths[req.wd]
select {
case req.result <- wd:
case <-ctx.Done():
}
}
}
}()
go func() {
//defer cancel()
wg.Wait()
close(inotify.done)
}()
return inotify, nil
}
// Done returns a channel that is closed when Inotify is done
func (i *Inotify) Done() <-chan struct{} {
return i.done
}
// AddWatch adds given path to list of watched files / folders
func (i *Inotify) AddWatch(pathName string, mask uint32) (int, error) {
req := addWatchRequest{
pathName: pathName,
mask: mask,
result: make(chan addWatchResult),
}
select {
case <-i.ctx.Done():
return 0, i.ctx.Err()
case i.addWatchIn <- req:
select {
case <-i.ctx.Done():
return 0, i.ctx.Err()
case result := <-req.result:
return result.wd, result.err
}
}
}
// RmWd removes watch by watch descriptor
func (i *Inotify) RmWd(wd int) error {
req := rmWdRequest{
wd: wd,
ignored: false,
result: make(chan error),
}
select {
case <-i.ctx.Done():
return i.ctx.Err()
case i.rmByWdIn <- req:
}
select {
case <-i.ctx.Done():
return i.ctx.Err()
case err := <-req.result:
return err
}
}
// RmWatch removes watch by pathName
func (i *Inotify) RmWatch(pathName string) error {
req := rmPathRequest{
pathName: pathName,
result: make(chan error),
}
select {
case <-i.ctx.Done():
return i.ctx.Err()
case i.rmByPathIn <- req:
}
select {
case <-i.ctx.Done():
return i.ctx.Err()
case err := <-req.result:
return err
}
}
// Read reads portion of InotifyEvents and may fail with an error. If no events are available, it will
// wait forever, until context is cancelled.
func (i *Inotify) Read() ([]InotifyEvent, error) {
i.readMutex.Lock()
defer i.readMutex.Unlock()
events := make([]InotifyEvent, 0, maxEvents)
select {
case <-i.ctx.Done():
return events, i.ctx.Err()
case <-i.Done():
return events, errors.New("inotify closed")
case evt, ok := <-i.eventsOut:
if !ok {
return events, errors.New("inotify closed")
}
if evt.err != nil {
return events, evt.err
}
if evt.InotifyEvent.Wd != 0 {
// append first event
events = append(events, evt.InotifyEvent)
}
if len(events) >= maxEvents {
return events, nil
}
// read all available events
read:
for {
select {
case <-i.ctx.Done():
return events, i.ctx.Err()
case <-i.Done():
return events, errors.New("inotify closed")
case evt, ok := <-i.eventsOut:
if !ok {
return events, errors.New("inotify closed")
}
if evt.err != nil {
return events, evt.err
}
if evt.InotifyEvent.Wd != 0 {
// append event
events = append(events, evt.InotifyEvent)
}
if len(events) >= maxEvents {
return events, nil
}
default:
break read
}
}
}
return events, nil
}
// ReadDeadline waits for InotifyEvents until deadline is reached, or context is cancelled. If
// deadline is reached, it will return all events read until that point.
func (i *Inotify) ReadDeadline(deadline time.Time) ([]InotifyEvent, error) {
i.readMutex.Lock()
defer i.readMutex.Unlock()
events := make([]InotifyEvent, 0, maxEvents)
for {
select {
case <-i.ctx.Done():
return events, i.ctx.Err()
case <-i.Done():
return events, errors.New("Inotify closed")
case <-time.After(time.Until(deadline)):
return events, nil
case evt, ok := <-i.eventsOut:
if !ok {
return events, errors.New("Inotify closed")
}
if evt.err != nil {
return events, evt.err
}
events = append(events, evt.InotifyEvent)
if len(events) >= maxEvents {
return events, nil
}
}
}
}