kqueue.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. // Don't watch named pipes.
  156. if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe {
  157. return nil
  158. }
  159. // Follow Symlinks
  160. // Unfortunately, Linux can add bogus symlinks to watch list without
  161. // issue, and Windows can't do symlinks period (AFAIK). To maintain
  162. // consistency, we will act like everything is fine. There will simply
  163. // be no file events for broken symlinks.
  164. // Hence the returns of nil on errors.
  165. if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
  166. name, err = filepath.EvalSymlinks(name)
  167. if err != nil {
  168. return nil
  169. }
  170. fi, err = os.Lstat(name)
  171. if err != nil {
  172. return nil
  173. }
  174. }
  175. watchfd, err = syscall.Open(name, openMode, 0700)
  176. if watchfd == -1 {
  177. return err
  178. }
  179. isDir = fi.IsDir()
  180. }
  181. const registerAdd = syscall.EV_ADD | syscall.EV_CLEAR | syscall.EV_ENABLE
  182. if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil {
  183. syscall.Close(watchfd)
  184. return err
  185. }
  186. if !alreadyWatching {
  187. w.mu.Lock()
  188. w.watches[name] = watchfd
  189. w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
  190. w.mu.Unlock()
  191. }
  192. if isDir {
  193. // Watch the directory if it has not been watched before,
  194. // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
  195. w.mu.Lock()
  196. watchDir := (flags&syscall.NOTE_WRITE) == syscall.NOTE_WRITE &&
  197. (!alreadyWatching || (w.dirFlags[name]&syscall.NOTE_WRITE) != syscall.NOTE_WRITE)
  198. // Store flags so this watch can be updated later
  199. w.dirFlags[name] = flags
  200. w.mu.Unlock()
  201. if watchDir {
  202. if err := w.watchDirectoryFiles(name); err != nil {
  203. return err
  204. }
  205. }
  206. }
  207. return nil
  208. }
  209. // readEvents reads from kqueue and converts the received kevents into
  210. // Event values that it sends down the Events channel.
  211. func (w *Watcher) readEvents() {
  212. eventBuffer := make([]syscall.Kevent_t, 10)
  213. for {
  214. // See if there is a message on the "done" channel
  215. select {
  216. case <-w.done:
  217. err := syscall.Close(w.kq)
  218. if err != nil {
  219. w.Errors <- err
  220. }
  221. close(w.Events)
  222. close(w.Errors)
  223. return
  224. default:
  225. }
  226. // Get new events
  227. kevents, err := read(w.kq, eventBuffer, &keventWaitTime)
  228. // EINTR is okay, the syscall was interrupted before timeout expired.
  229. if err != nil && err != syscall.EINTR {
  230. w.Errors <- err
  231. continue
  232. }
  233. // Flush the events we received to the Events channel
  234. for len(kevents) > 0 {
  235. kevent := &kevents[0]
  236. watchfd := int(kevent.Ident)
  237. mask := uint32(kevent.Fflags)
  238. w.mu.Lock()
  239. path := w.paths[watchfd]
  240. w.mu.Unlock()
  241. event := newEvent(path.name, mask)
  242. if path.isDir && !(event.Op&Remove == Remove) {
  243. // Double check to make sure the directory exists. This can happen when
  244. // we do a rm -fr on a recursively watched folders and we receive a
  245. // modification event first but the folder has been deleted and later
  246. // receive the delete event
  247. if _, err := os.Lstat(event.Name); os.IsNotExist(err) {
  248. // mark is as delete event
  249. event.Op |= Remove
  250. }
  251. }
  252. if event.Op&Rename == Rename || event.Op&Remove == Remove {
  253. w.Remove(event.Name)
  254. w.mu.Lock()
  255. delete(w.fileExists, event.Name)
  256. w.mu.Unlock()
  257. }
  258. if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) {
  259. w.sendDirectoryChangeEvents(event.Name)
  260. } else {
  261. // Send the event on the Events channel
  262. w.Events <- event
  263. }
  264. if event.Op&Remove == Remove {
  265. // Look for a file that may have overwritten this.
  266. // For example, mv f1 f2 will delete f2, then create f2.
  267. fileDir, _ := filepath.Split(event.Name)
  268. fileDir = filepath.Clean(fileDir)
  269. w.mu.Lock()
  270. _, found := w.watches[fileDir]
  271. w.mu.Unlock()
  272. if found {
  273. // make sure the directory exists before we watch for changes. When we
  274. // do a recursive watch and perform rm -fr, the parent directory might
  275. // have gone missing, ignore the missing directory and let the
  276. // upcoming delete event remove the watch from the parent directory.
  277. if _, err := os.Lstat(fileDir); os.IsExist(err) {
  278. w.sendDirectoryChangeEvents(fileDir)
  279. // FIXME: should this be for events on files or just isDir?
  280. }
  281. }
  282. }
  283. // Move to next event
  284. kevents = kevents[1:]
  285. }
  286. }
  287. }
  288. // newEvent returns an platform-independent Event based on kqueue Fflags.
  289. func newEvent(name string, mask uint32) Event {
  290. e := Event{Name: name}
  291. if mask&syscall.NOTE_DELETE == syscall.NOTE_DELETE {
  292. e.Op |= Remove
  293. }
  294. if mask&syscall.NOTE_WRITE == syscall.NOTE_WRITE {
  295. e.Op |= Write
  296. }
  297. if mask&syscall.NOTE_RENAME == syscall.NOTE_RENAME {
  298. e.Op |= Rename
  299. }
  300. if mask&syscall.NOTE_ATTRIB == syscall.NOTE_ATTRIB {
  301. e.Op |= Chmod
  302. }
  303. return e
  304. }
  305. func newCreateEvent(name string) Event {
  306. return Event{Name: name, Op: Create}
  307. }
  308. // watchDirectoryFiles to mimic inotify when adding a watch on a directory
  309. func (w *Watcher) watchDirectoryFiles(dirPath string) error {
  310. // Get all files
  311. files, err := ioutil.ReadDir(dirPath)
  312. if err != nil {
  313. return err
  314. }
  315. for _, fileInfo := range files {
  316. filePath := filepath.Join(dirPath, fileInfo.Name())
  317. if err := w.internalWatch(filePath, fileInfo); err != nil {
  318. return err
  319. }
  320. w.mu.Lock()
  321. w.fileExists[filePath] = true
  322. w.mu.Unlock()
  323. }
  324. return nil
  325. }
  326. // sendDirectoryEvents searches the directory for newly created files
  327. // and sends them over the event channel. This functionality is to have
  328. // the BSD version of fsnotify match Linux inotify which provides a
  329. // create event for files created in a watched directory.
  330. func (w *Watcher) sendDirectoryChangeEvents(dirPath string) {
  331. // Get all files
  332. files, err := ioutil.ReadDir(dirPath)
  333. if err != nil {
  334. w.Errors <- err
  335. }
  336. // Search for new files
  337. for _, fileInfo := range files {
  338. filePath := filepath.Join(dirPath, fileInfo.Name())
  339. w.mu.Lock()
  340. _, doesExist := w.fileExists[filePath]
  341. w.mu.Unlock()
  342. if !doesExist {
  343. // Send create event
  344. w.Events <- newCreateEvent(filePath)
  345. }
  346. // like watchDirectoryFiles (but without doing another ReadDir)
  347. if err := w.internalWatch(filePath, fileInfo); err != nil {
  348. return
  349. }
  350. w.mu.Lock()
  351. w.fileExists[filePath] = true
  352. w.mu.Unlock()
  353. }
  354. }
  355. func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) error {
  356. if fileInfo.IsDir() {
  357. // mimic Linux providing delete events for subdirectories
  358. // but preserve the flags used if currently watching subdirectory
  359. w.mu.Lock()
  360. flags := w.dirFlags[name]
  361. w.mu.Unlock()
  362. flags |= syscall.NOTE_DELETE
  363. return w.addWatch(name, flags)
  364. }
  365. // watch file to mimic Linux inotify
  366. return w.addWatch(name, noteAllEvents)
  367. }
  368. // kqueue creates a new kernel event queue and returns a descriptor.
  369. func kqueue() (kq int, err error) {
  370. kq, err = syscall.Kqueue()
  371. if kq == -1 {
  372. return kq, err
  373. }
  374. return kq, nil
  375. }
  376. // register events with the queue
  377. func register(kq int, fds []int, flags int, fflags uint32) error {
  378. changes := make([]syscall.Kevent_t, len(fds))
  379. for i, fd := range fds {
  380. // SetKevent converts int to the platform-specific types:
  381. syscall.SetKevent(&changes[i], fd, syscall.EVFILT_VNODE, flags)
  382. changes[i].Fflags = fflags
  383. }
  384. // register the events
  385. success, err := syscall.Kevent(kq, changes, nil, nil)
  386. if success == -1 {
  387. return err
  388. }
  389. return nil
  390. }
  391. // read retrieves pending events, or waits until an event occurs.
  392. // A timeout of nil blocks indefinitely, while 0 polls the queue.
  393. func read(kq int, events []syscall.Kevent_t, timeout *syscall.Timespec) ([]syscall.Kevent_t, error) {
  394. n, err := syscall.Kevent(kq, nil, events, timeout)
  395. if err != nil {
  396. return nil, err
  397. }
  398. return events[0:n], nil
  399. }
  400. // durationToTimespec prepares a timeout value
  401. func durationToTimespec(d time.Duration) syscall.Timespec {
  402. return syscall.NsecToTimespec(d.Nanoseconds())
  403. }