inotify_linux.go 8.9 KB

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