Debian Codegraph @

inotify/inotify_linux.go

raw
1 //go:build linux
2
3 // Copyright 2010 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 /*
8 Package inotify implements a wrapper for the Linux inotify system.
9
10 Example:
11
12 watcher, err := inotify.NewWatcher()
13 if err != nil {
14 log.Fatal(err)
15 }
16 err = watcher.Watch("/tmp")
17 if err != nil {
18 log.Fatal(err)
19 }
20 for {
21 select {
22 case ev := <-watcher.Event:
23 log.Println("event:", ev)
24 case err := <-watcher.Error:
25 log.Println("error:", err)
26 }
27 }
28 */
29 package inotify // import "k8s.io/utils/inotify"
30
31 import (
32 "errors"
33 "fmt"
34 "os"
35 "strings"
36 "syscall"
37 "unsafe"
38 )
39
40 // NewWatcher creates and returns a new inotify instance using inotify_init(2)
41 func NewWatcher() (*Watcher, error) {
42 fd, errno := syscall.InotifyInit1(syscall.IN_CLOEXEC)
43 if fd == -1 {
44 return nil, os.NewSyscallError("inotify_init", errno)
45 }
46 w := &Watcher{
47 fd: fd,
48 watches: make(map[string]*watch),
49 paths: make(map[int]string),
50 Event: make(chan *Event),
51 Error: make(chan error),
52 done: make(chan bool, 1),
53 }
54
55 go w.readEvents()
56 return w, nil
57 }
58
59 // Close closes an inotify watcher instance
60 // It sends a message to the reader goroutine to quit and removes all watches
61 // associated with the inotify instance
62 func (w *Watcher) Close() error {
63 if w.isClosed {
64 return nil
65 }
66 w.isClosed = true
67
68 // Send "quit" message to the reader goroutine
69 w.done <- true
70 for path := range w.watches {
71 w.RemoveWatch(path)
72 }
73
74 return nil
75 }
76
77 // AddWatch adds path to the watched file set.
78 // The flags are interpreted as described in inotify_add_watch(2).
79 func (w *Watcher) AddWatch(path string, flags uint32) error {
80 if w.isClosed {
81 return errors.New("inotify instance already closed")
82 }
83
84 watchEntry, found := w.watches[path]
85 if found {
86 watchEntry.flags |= flags
87 flags |= syscall.IN_MASK_ADD
88 }
89
90 w.mu.Lock() // synchronize with readEvents goroutine
91
92 wd, err := syscall.InotifyAddWatch(w.fd, path, flags)
93 if err != nil {
94 w.mu.Unlock()
95 return &os.PathError{
96 Op: "inotify_add_watch",
97 Path: path,
98 Err: err,
99 }
100 }
101
102 if !found {
103 w.watches[path] = &watch{wd: uint32(wd), flags: flags}
104 w.paths[wd] = path
105 }
106 w.mu.Unlock()
107 return nil
108 }
109
110 // Watch adds path to the watched file set, watching all events.
111 func (w *Watcher) Watch(path string) error {
112 return w.AddWatch(path, InAllEvents)
113 }
114
115 // RemoveWatch removes path from the watched file set.
116 func (w *Watcher) RemoveWatch(path string) error {
117 watch, ok := w.watches[path]
118 if !ok {
119 return fmt.Errorf("can't remove non-existent inotify watch for: %s", path)
120 }
121 success, errno := syscall.InotifyRmWatch(w.fd, watch.wd)
122 if success == -1 {
123 // when file descriptor or watch descriptor not found, InotifyRmWatch syscall return EINVAL error
124 // if return error, it may lead this path remain in watches and paths map, and no other event can trigger remove action.
125 if errno != syscall.EINVAL {
126 return os.NewSyscallError("inotify_rm_watch", errno)
127 }
128 }
129 delete(w.watches, path)
130 // Locking here to protect the read from paths in readEvents.
131 w.mu.Lock()
132 delete(w.paths, int(watch.wd))
133 w.mu.Unlock()
134 return nil
135 }
136
137 // readEvents reads from the inotify file descriptor, converts the
138 // received events into Event objects and sends them via the Event channel
139 func (w *Watcher) readEvents() {
140 var buf [syscall.SizeofInotifyEvent * 4096]byte
141
142 for {
143 n, err := syscall.Read(w.fd, buf[:])
144 // See if there is a message on the "done" channel
145 var done bool
146 select {
147 case done = <-w.done:
148 default:
149 }
150
151 // If EOF or a "done" message is received
152 if n == 0 || done {
153 // The syscall.Close can be slow. Close
154 // w.Event first.
155 close(w.Event)
156 err := syscall.Close(w.fd)
157 if err != nil {
158 w.Error <- os.NewSyscallError("close", err)
159 }
160 close(w.Error)
161 return
162 }
163 if n < 0 {
164 w.Error <- os.NewSyscallError("read", err)
165 continue
166 }
167 if n < syscall.SizeofInotifyEvent {
168 w.Error <- errors.New("inotify: short read in readEvents()")
169 continue
170 }
171
172 var offset uint32
173 // We don't know how many events we just read into the buffer
174 // While the offset points to at least one whole event...
175 for offset <= uint32(n-syscall.SizeofInotifyEvent) {
176 // Point "raw" to the event in the buffer
177 raw := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset]))
178 event := new(Event)
179 event.Mask = uint32(raw.Mask)
180 event.Cookie = uint32(raw.Cookie)
181 nameLen := uint32(raw.Len)
182 // If the event happened to the watched directory or the watched file, the kernel
183 // doesn't append the filename to the event, but we would like to always fill the
184 // the "Name" field with a valid filename. We retrieve the path of the watch from
185 // the "paths" map.
186 w.mu.Lock()
187 name, ok := w.paths[int(raw.Wd)]
188 w.mu.Unlock()
189 if ok {
190 event.Name = name
191 if nameLen > 0 {
192 // Point "bytes" at the first byte of the filename
193 bytes := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent]))
194 // The filename is padded with NUL bytes. TrimRight() gets rid of those.
195 event.Name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000")
196 }
197 // Send the event on the events channel
198 w.Event <- event
199 }
200 // Move to the next event in the buffer
201 offset += syscall.SizeofInotifyEvent + nameLen
202 }
203 }
204 }
205
206 // String formats the event e in the form
207 // "filename: 0xEventMask = IN_ACCESS|IN_ATTRIB_|..."
208 func (e *Event) String() string {
209 var events string
210
211 m := e.Mask
212 for _, b := range eventBits {
213 if m&b.Value == b.Value {
214 m &^= b.Value
215 events += "|" + b.Name
216 }
217 }
218
219 if m != 0 {
220 events += fmt.Sprintf("|%#x", m)
221 }
222 if len(events) > 0 {
223 events = " == " + events[1:]
224 }
225
226 return fmt.Sprintf("%q: %#x%s", e.Name, e.Mask, events)
227 }
228
229 const (
230 // Options for inotify_init() are not exported
231 // IN_CLOEXEC uint32 = syscall.IN_CLOEXEC
232 // IN_NONBLOCK uint32 = syscall.IN_NONBLOCK
233
234 // Options for AddWatch
235
236 // InDontFollow : Don't dereference pathname if it is a symbolic link
237 InDontFollow uint32 = syscall.IN_DONT_FOLLOW
238 // InOneshot : Monitor the filesystem object corresponding to pathname for one event, then remove from watch list
239 InOneshot uint32 = syscall.IN_ONESHOT
240 // InOnlydir : Watch pathname only if it is a directory
241 InOnlydir uint32 = syscall.IN_ONLYDIR
242
243 // The "IN_MASK_ADD" option is not exported, as AddWatch
244 // adds it automatically, if there is already a watch for the given path
245 // IN_MASK_ADD uint32 = syscall.IN_MASK_ADD
246
247 // Events
248
249 // InAccess : File was accessed
250 InAccess uint32 = syscall.IN_ACCESS
251 // InAllEvents : Bit mask for all notify events
252 InAllEvents uint32 = syscall.IN_ALL_EVENTS
253 // InAttrib : Metadata changed
254 InAttrib uint32 = syscall.IN_ATTRIB
255 // InClose : Equates to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE
256 InClose uint32 = syscall.IN_CLOSE
257 // InCloseNowrite : File or directory not opened for writing was closed
258 InCloseNowrite uint32 = syscall.IN_CLOSE_NOWRITE
259 // InCloseWrite : File opened for writing was closed
260 InCloseWrite uint32 = syscall.IN_CLOSE_WRITE
261 // InCreate : File/directory created in watched directory
262 InCreate uint32 = syscall.IN_CREATE
263 // InDelete : File/directory deleted from watched directory
264 InDelete uint32 = syscall.IN_DELETE
265 // InDeleteSelf : Watched file/directory was itself deleted
266 InDeleteSelf uint32 = syscall.IN_DELETE_SELF
267 // InModify : File was modified
268 InModify uint32 = syscall.IN_MODIFY
269 // InMove : Equates to IN_MOVED_FROM | IN_MOVED_TO
270 InMove uint32 = syscall.IN_MOVE
271 // InMovedFrom : Generated for the directory containing the old filename when a file is renamed
272 InMovedFrom uint32 = syscall.IN_MOVED_FROM
273 // InMovedTo : Generated for the directory containing the new filename when a file is renamed
274 InMovedTo uint32 = syscall.IN_MOVED_TO
275 // InMoveSelf : Watched file/directory was itself moved
276 InMoveSelf uint32 = syscall.IN_MOVE_SELF
277 // InOpen : File or directory was opened
278 InOpen uint32 = syscall.IN_OPEN
279
280 // Special events
281
282 // InIsdir : Subject of this event is a directory
283 InIsdir uint32 = syscall.IN_ISDIR
284 // InIgnored : Watch was removed explicitly or automatically
285 InIgnored uint32 = syscall.IN_IGNORED
286 // InQOverflow : Event queue overflowed
287 InQOverflow uint32 = syscall.IN_Q_OVERFLOW
288 // InUnmount : Filesystem containing watched object was unmounted
289 InUnmount uint32 = syscall.IN_UNMOUNT
290 )
291
292 var eventBits = []struct {
293 Value uint32
294 Name string
295 }{
296 {InAccess, "IN_ACCESS"},
297 {InAttrib, "IN_ATTRIB"},
298 {InClose, "IN_CLOSE"},
299 {InCloseNowrite, "IN_CLOSE_NOWRITE"},
300 {InCloseWrite, "IN_CLOSE_WRITE"},
301 {InCreate, "IN_CREATE"},
302 {InDelete, "IN_DELETE"},
303 {InDeleteSelf, "IN_DELETE_SELF"},
304 {InModify, "IN_MODIFY"},
305 {InMove, "IN_MOVE"},
306 {InMovedFrom, "IN_MOVED_FROM"},
307 {InMovedTo, "IN_MOVED_TO"},
308 {InMoveSelf, "IN_MOVE_SELF"},
309 {InOpen, "IN_OPEN"},
310 {InIsdir, "IN_ISDIR"},
311 {InIgnored, "IN_IGNORED"},
312 {InQOverflow, "IN_Q_OVERFLOW"},
313 {InUnmount, "IN_UNMOUNT"},
314 }