inotify_linux.go 9.6 KB

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