kqueue.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. // +build freebsd openbsd netbsd dragonfly darwin
  5. package fsnotify
  6. import (
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path/filepath"
  12. "sync"
  13. "syscall"
  14. "time"
  15. )
  16. // Watcher watches a set of files, delivering events to a channel.
  17. type Watcher struct {
  18. Events chan Event
  19. Errors chan error
  20. done chan bool // Channel for sending a "quit message" to the reader goroutine
  21. kq int // File descriptor (as returned by the kqueue() syscall).
  22. mu sync.Mutex // Protects access to watcher data
  23. watches map[string]int // Map of watched file descriptors (key: path).
  24. externalWatches map[string]bool // Map of watches added by user of the library.
  25. dirFlags map[string]uint32 // Map of watched directories to fflags used in kqueue.
  26. paths map[int]pathInfo // Map file descriptors to path names for processing kqueue events.
  27. fileExists map[string]bool // Keep track of if we know this file exists (to stop duplicate create events).
  28. isClosed bool // Set to true when Close() is first called
  29. }
  30. type pathInfo struct {
  31. name string
  32. isDir bool
  33. }
  34. // NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
  35. func NewWatcher() (*Watcher, error) {
  36. kq, err := kqueue()
  37. if err != nil {
  38. return nil, err
  39. }
  40. w := &Watcher{
  41. kq: kq,
  42. watches: make(map[string]int),
  43. dirFlags: make(map[string]uint32),
  44. paths: make(map[int]pathInfo),
  45. fileExists: make(map[string]bool),
  46. externalWatches: make(map[string]bool),
  47. Events: make(chan Event),
  48. Errors: make(chan error),
  49. done: make(chan bool),
  50. }
  51. go w.readEvents()
  52. return w, nil
  53. }
  54. // Close removes all watches and closes the events channel.
  55. func (w *Watcher) Close() error {
  56. w.mu.Lock()
  57. if w.isClosed {
  58. w.mu.Unlock()
  59. return nil
  60. }
  61. w.isClosed = true
  62. w.mu.Unlock()
  63. w.mu.Lock()
  64. ws := w.watches
  65. w.mu.Unlock()
  66. var err error
  67. for name := range ws {
  68. if e := w.Remove(name); e != nil && err == nil {
  69. err = e
  70. }
  71. }
  72. // Send "quit" message to the reader goroutine:
  73. w.done <- true
  74. return nil
  75. }
  76. // Add starts watching the named file or directory (non-recursively).
  77. func (w *Watcher) Add(name string) error {
  78. w.mu.Lock()
  79. w.externalWatches[name] = true
  80. w.mu.Unlock()
  81. return w.addWatch(name, noteAllEvents)
  82. }
  83. // Remove stops watching the the named file or directory (non-recursively).
  84. func (w *Watcher) Remove(name string) error {
  85. name = filepath.Clean(name)
  86. w.mu.Lock()
  87. watchfd, ok := w.watches[name]
  88. w.mu.Unlock()
  89. if !ok {
  90. return fmt.Errorf("can't remove non-existent kevent watch for: %s", name)
  91. }
  92. const registerRemove = syscall.EV_DELETE
  93. if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil {
  94. return err
  95. }
  96. syscall.Close(watchfd)
  97. w.mu.Lock()
  98. isDir := w.paths[watchfd].isDir
  99. delete(w.watches, name)
  100. delete(w.paths, watchfd)
  101. delete(w.dirFlags, name)
  102. w.mu.Unlock()
  103. // Find all watched paths that are in this directory that are not external.
  104. if isDir {
  105. var pathsToRemove []string
  106. w.mu.Lock()
  107. for _, path := range w.paths {
  108. wdir, _ := filepath.Split(path.name)
  109. if filepath.Clean(wdir) == name {
  110. if !w.externalWatches[path.name] {
  111. pathsToRemove = append(pathsToRemove, path.name)
  112. }
  113. }
  114. }
  115. w.mu.Unlock()
  116. for _, name := range pathsToRemove {
  117. // Since these are internal, not much sense in propagating error
  118. // to the user, as that will just confuse them with an error about
  119. // a path they did not explicitly watch themselves.
  120. w.Remove(name)
  121. }
  122. }
  123. return nil
  124. }
  125. // Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE)
  126. const noteAllEvents = syscall.NOTE_DELETE | syscall.NOTE_WRITE | syscall.NOTE_ATTRIB | syscall.NOTE_RENAME
  127. // keventWaitTime to block on each read from kevent
  128. var keventWaitTime = durationToTimespec(100 * time.Millisecond)
  129. // addWatch adds name to the watched file set.
  130. // The flags are interpreted as described in kevent(2).
  131. func (w *Watcher) addWatch(name string, flags uint32) error {
  132. var isDir bool
  133. // Make ./name and name equivalent
  134. name = filepath.Clean(name)
  135. w.mu.Lock()
  136. if w.isClosed {
  137. w.mu.Unlock()
  138. return errors.New("kevent instance already closed")
  139. }
  140. watchfd, alreadyWatching := w.watches[name]
  141. // We already have a watch, but we can still override flags.
  142. if alreadyWatching {
  143. isDir = w.paths[watchfd].isDir
  144. }
  145. w.mu.Unlock()
  146. if !alreadyWatching {
  147. fi, err := os.Lstat(name)
  148. if err != nil {
  149. return err
  150. }
  151. // Don't watch sockets.
  152. if fi.Mode()&os.ModeSocket == os.ModeSocket {
  153. return nil
  154. }
  155. // Follow Symlinks
  156. // Unfortunately, Linux can add bogus symlinks to watch list without
  157. // issue, and Windows can't do symlinks period (AFAIK). To maintain
  158. // consistency, we will act like everything is fine. There will simply
  159. // be no file events for broken symlinks.
  160. // Hence the returns of nil on errors.
  161. if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
  162. name, err = filepath.EvalSymlinks(name)
  163. if err != nil {
  164. return nil
  165. }
  166. fi, err = os.Lstat(name)
  167. if err != nil {
  168. return nil
  169. }
  170. }
  171. watchfd, err = syscall.Open(name, openMode, 0700)
  172. if watchfd == -1 {
  173. return err
  174. }
  175. isDir = fi.IsDir()
  176. }
  177. const registerAdd = syscall.EV_ADD | syscall.EV_CLEAR | syscall.EV_ENABLE
  178. if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil {
  179. syscall.Close(watchfd)
  180. return err
  181. }
  182. if !alreadyWatching {
  183. w.mu.Lock()
  184. w.watches[name] = watchfd
  185. w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
  186. w.mu.Unlock()
  187. }
  188. if isDir {
  189. // Watch the directory if it has not been watched before,
  190. // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
  191. w.mu.Lock()
  192. watchDir := (flags&syscall.NOTE_WRITE) == syscall.NOTE_WRITE &&
  193. (!alreadyWatching || (w.dirFlags[name]&syscall.NOTE_WRITE) != syscall.NOTE_WRITE)
  194. // Store flags so this watch can be updated later
  195. w.dirFlags[name] = flags
  196. w.mu.Unlock()
  197. if watchDir {
  198. if err := w.watchDirectoryFiles(name); err != nil {
  199. return err
  200. }
  201. }
  202. }
  203. return nil
  204. }
  205. // readEvents reads from kqueue and converts the received kevents into
  206. // Event values that it sends down the Events channel.
  207. func (w *Watcher) readEvents() {
  208. eventBuffer := make([]syscall.Kevent_t, 10)
  209. for {
  210. // See if there is a message on the "done" channel
  211. select {
  212. case <-w.done:
  213. err := syscall.Close(w.kq)
  214. if err != nil {
  215. w.Errors <- err
  216. }
  217. close(w.Events)
  218. close(w.Errors)
  219. return
  220. default:
  221. }
  222. // Get new events
  223. kevents, err := read(w.kq, eventBuffer, &keventWaitTime)
  224. // EINTR is okay, the syscall was interrupted before timeout expired.
  225. if err != nil && err != syscall.EINTR {
  226. w.Errors <- err
  227. continue
  228. }
  229. // Flush the events we received to the Events channel
  230. for len(kevents) > 0 {
  231. kevent := &kevents[0]
  232. watchfd := int(kevent.Ident)
  233. mask := uint32(kevent.Fflags)
  234. w.mu.Lock()
  235. path := w.paths[watchfd]
  236. w.mu.Unlock()
  237. event := newEvent(path.name, mask)
  238. if path.isDir && !(event.Op&Remove == Remove) {
  239. // Double check to make sure the directory exists. This can happen when
  240. // we do a rm -fr on a recursively watched folders and we receive a
  241. // modification event first but the folder has been deleted and later
  242. // receive the delete event
  243. if _, err := os.Lstat(event.Name); os.IsNotExist(err) {
  244. // mark is as delete event
  245. event.Op |= Remove
  246. }
  247. }
  248. if event.Op&Rename == Rename || event.Op&Remove == Remove {
  249. w.Remove(event.Name)
  250. w.mu.Lock()
  251. delete(w.fileExists, event.Name)
  252. w.mu.Unlock()
  253. }
  254. if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) {
  255. w.sendDirectoryChangeEvents(event.Name)
  256. } else {
  257. // Send the event on the Events channel
  258. w.Events <- event
  259. }
  260. if event.Op&Remove == Remove {
  261. // Look for a file that may have overwritten this.
  262. // For example, mv f1 f2 will delete f2, then create f2.
  263. fileDir, _ := filepath.Split(event.Name)
  264. fileDir = filepath.Clean(fileDir)
  265. w.mu.Lock()
  266. _, found := w.watches[fileDir]
  267. w.mu.Unlock()
  268. if found {
  269. // make sure the directory exists before we watch for changes. When we
  270. // do a recursive watch and perform rm -fr, the parent directory might
  271. // have gone missing, ignore the missing directory and let the
  272. // upcoming delete event remove the watch from the parent directory.
  273. if _, err := os.Lstat(fileDir); os.IsExist(err) {
  274. w.sendDirectoryChangeEvents(fileDir)
  275. // FIXME: should this be for events on files or just isDir?
  276. }
  277. }
  278. }
  279. // Move to next event
  280. kevents = kevents[1:]
  281. }
  282. }
  283. }
  284. // newEvent returns an platform-independent Event based on kqueue Fflags.
  285. func newEvent(name string, mask uint32) Event {
  286. e := Event{Name: name}
  287. if mask&syscall.NOTE_DELETE == syscall.NOTE_DELETE {
  288. e.Op |= Remove
  289. }
  290. if mask&syscall.NOTE_WRITE == syscall.NOTE_WRITE {
  291. e.Op |= Write
  292. }
  293. if mask&syscall.NOTE_RENAME == syscall.NOTE_RENAME {
  294. e.Op |= Rename
  295. }
  296. if mask&syscall.NOTE_ATTRIB == syscall.NOTE_ATTRIB {
  297. e.Op |= Chmod
  298. }
  299. return e
  300. }
  301. func newCreateEvent(name string) Event {
  302. return Event{Name: name, Op: Create}
  303. }
  304. // watchDirectoryFiles to mimic inotify when adding a watch on a directory
  305. func (w *Watcher) watchDirectoryFiles(dirPath string) error {
  306. // Get all files
  307. files, err := ioutil.ReadDir(dirPath)
  308. if err != nil {
  309. return err
  310. }
  311. for _, fileInfo := range files {
  312. filePath := filepath.Join(dirPath, fileInfo.Name())
  313. if err := w.internalWatch(filePath, fileInfo); err != nil {
  314. return err
  315. }
  316. w.mu.Lock()
  317. w.fileExists[filePath] = true
  318. w.mu.Unlock()
  319. }
  320. return nil
  321. }
  322. // sendDirectoryEvents searches the directory for newly created files
  323. // and sends them over the event channel. This functionality is to have
  324. // the BSD version of fsnotify match Linux inotify which provides a
  325. // create event for files created in a watched directory.
  326. func (w *Watcher) sendDirectoryChangeEvents(dirPath string) {
  327. // Get all files
  328. files, err := ioutil.ReadDir(dirPath)
  329. if err != nil {
  330. w.Errors <- err
  331. }
  332. // Search for new files
  333. for _, fileInfo := range files {
  334. filePath := filepath.Join(dirPath, fileInfo.Name())
  335. w.mu.Lock()
  336. _, doesExist := w.fileExists[filePath]
  337. w.mu.Unlock()
  338. if !doesExist {
  339. // Send create event
  340. w.Events <- newCreateEvent(filePath)
  341. }
  342. // like watchDirectoryFiles (but without doing another ReadDir)
  343. if err := w.internalWatch(filePath, fileInfo); err != nil {
  344. return
  345. }
  346. w.mu.Lock()
  347. w.fileExists[filePath] = true
  348. w.mu.Unlock()
  349. }
  350. }
  351. func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) error {
  352. if fileInfo.IsDir() {
  353. // mimic Linux providing delete events for subdirectories
  354. // but preserve the flags used if currently watching subdirectory
  355. w.mu.Lock()
  356. flags := w.dirFlags[name]
  357. w.mu.Unlock()
  358. flags |= syscall.NOTE_DELETE
  359. return w.addWatch(name, flags)
  360. }
  361. // watch file to mimic Linux inotify
  362. return w.addWatch(name, noteAllEvents)
  363. }
  364. // kqueue creates a new kernel event queue and returns a descriptor.
  365. func kqueue() (kq int, err error) {
  366. kq, err = syscall.Kqueue()
  367. if kq == -1 {
  368. return kq, err
  369. }
  370. return kq, nil
  371. }
  372. // register events with the queue
  373. func register(kq int, fds []int, flags int, fflags uint32) error {
  374. changes := make([]syscall.Kevent_t, len(fds))
  375. for i, fd := range fds {
  376. // SetKevent converts int to the platform-specific types:
  377. syscall.SetKevent(&changes[i], fd, syscall.EVFILT_VNODE, flags)
  378. changes[i].Fflags = fflags
  379. }
  380. // register the events
  381. success, err := syscall.Kevent(kq, changes, nil, nil)
  382. if success == -1 {
  383. return err
  384. }
  385. return nil
  386. }
  387. // read retrieves pending events, or waits until an event occurs.
  388. // A timeout of nil blocks indefinitely, while 0 polls the queue.
  389. func read(kq int, events []syscall.Kevent_t, timeout *syscall.Timespec) ([]syscall.Kevent_t, error) {
  390. n, err := syscall.Kevent(kq, nil, events, timeout)
  391. if err != nil {
  392. return nil, err
  393. }
  394. return events[0:n], nil
  395. }
  396. // durationToTimespec prepares a timeout value
  397. func durationToTimespec(d time.Duration) syscall.Timespec {
  398. return syscall.NsecToTimespec(d.Nanoseconds())
  399. }