-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinotify.go
115 lines (96 loc) · 2.07 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
package logtail
import (
"reflect"
"syscall"
"unsafe"
)
func cStringLen(s []byte) int {
for i, e := range s {
if e == 0 {
return i
}
}
return 0
}
// EventType ...
type EventType int
const (
// EventTypeCreate ...
EventTypeCreate EventType = 1
// EventTypeModify ...
EventTypeModify EventType = 2
)
// WatchEvent ...
type WatchEvent struct {
Filename string
Type EventType
}
// DirectoryWatcher ...
type DirectoryWatcher struct {
inotifyFd int
watchDesc int
watchChan chan WatchEvent
}
// NewWatcher ...
func NewWatcher(dirname string) *DirectoryWatcher {
inotifyFd, err := syscall.InotifyInit()
if err != nil {
panic(err)
}
watchDesc, err := syscall.InotifyAddWatch(
inotifyFd, dirname, syscall.IN_MODIFY|syscall.IN_CREATE)
if err != nil {
panic(err)
}
return &DirectoryWatcher{
inotifyFd: inotifyFd,
watchDesc: watchDesc,
watchChan: make(chan WatchEvent),
}
}
func eventTypeFromInotify(mask uint32) EventType {
if mask&syscall.IN_CREATE != 0 {
return EventTypeCreate
}
return EventTypeModify
}
// Watch ...
func (w *DirectoryWatcher) Watch() {
buffer := make([]byte, syscall.SizeofInotifyEvent*128)
for {
numReads, err := syscall.Read(w.inotifyFd, buffer)
if err != nil {
panic(err)
}
for offset := 0; offset+syscall.SizeofInotifyEvent < numReads; {
event := (*syscall.InotifyEvent)(unsafe.Pointer(&buffer[offset]))
if event.Wd == int32(w.watchDesc) {
p := unsafe.Pointer(&event.Name)
header := reflect.SliceHeader{
Data: uintptr(p),
Len: int(event.Len),
Cap: int(event.Len),
}
array := *(*[]byte)(unsafe.Pointer(&header))
name := string(array[:cStringLen(array)])
w.watchChan <- WatchEvent{
Filename: name,
Type: eventTypeFromInotify(event.Mask),
}
}
offset += int(syscall.SizeofInotifyEvent + event.Len)
}
}
}
// GetWatchChan ...
func (w *DirectoryWatcher) GetWatchChan() <-chan WatchEvent {
return w.watchChan
}
// Shutdown ...
func (w *DirectoryWatcher) Shutdown() {
err := syscall.Close(w.inotifyFd)
if err != nil {
panic(err)
}
close(w.watchChan)
}