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.
5 // +build freebsd openbsd netbsd dragonfly darwin
18 "golang.org/x/sys/unix"
21 // Watcher watches a set of files, delivering events to a channel.
25 done chan bool // Channel for sending a "quit message" to the reader goroutine
27 kq int // File descriptor (as returned by the kqueue() syscall).
29 mu sync.Mutex // Protects access to watcher data
30 watches map[string]int // Map of watched file descriptors (key: path).
31 externalWatches map[string]bool // Map of watches added by user of the library.
32 dirFlags map[string]uint32 // Map of watched directories to fflags used in kqueue.
33 paths map[int]pathInfo // Map file descriptors to path names for processing kqueue events.
34 fileExists map[string]bool // Keep track of if we know this file exists (to stop duplicate create events).
35 isClosed bool // Set to true when Close() is first called
38 type pathInfo struct {
43 // NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
44 func NewWatcher() (*Watcher, error) {
52 watches: make(map[string]int),
53 dirFlags: make(map[string]uint32),
54 paths: make(map[int]pathInfo),
55 fileExists: make(map[string]bool),
56 externalWatches: make(map[string]bool),
57 Events: make(chan Event),
58 Errors: make(chan error),
59 done: make(chan bool),
66 // Close removes all watches and closes the events channel.
67 func (w *Watcher) Close() error {
76 // copy paths to remove while locked
78 var pathsToRemove = make([]string, 0, len(w.watches))
79 for name := range w.watches {
80 pathsToRemove = append(pathsToRemove, name)
83 // unlock before calling Remove, which also locks
86 for _, name := range pathsToRemove {
87 if e := w.Remove(name); e != nil && err == nil {
92 // Send "quit" message to the reader goroutine:
98 // Add starts watching the named file or directory (non-recursively).
99 func (w *Watcher) Add(name string) error {
101 w.externalWatches[name] = true
103 _, err := w.addWatch(name, noteAllEvents)
107 // Remove stops watching the the named file or directory (non-recursively).
108 func (w *Watcher) Remove(name string) error {
109 name = filepath.Clean(name)
111 watchfd, ok := w.watches[name]
114 return fmt.Errorf("can't remove non-existent kevent watch for: %s", name)
117 const registerRemove = unix.EV_DELETE
118 if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil {
125 isDir := w.paths[watchfd].isDir
126 delete(w.watches, name)
127 delete(w.paths, watchfd)
128 delete(w.dirFlags, name)
131 // Find all watched paths that are in this directory that are not external.
133 var pathsToRemove []string
135 for _, path := range w.paths {
136 wdir, _ := filepath.Split(path.name)
137 if filepath.Clean(wdir) == name {
138 if !w.externalWatches[path.name] {
139 pathsToRemove = append(pathsToRemove, path.name)
144 for _, name := range pathsToRemove {
145 // Since these are internal, not much sense in propagating error
146 // to the user, as that will just confuse them with an error about
147 // a path they did not explicitly watch themselves.
155 // Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE)
156 const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME
158 // keventWaitTime to block on each read from kevent
159 var keventWaitTime = durationToTimespec(100 * time.Millisecond)
161 // addWatch adds name to the watched file set.
162 // The flags are interpreted as described in kevent(2).
163 // Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks.
164 func (w *Watcher) addWatch(name string, flags uint32) (string, error) {
166 // Make ./name and name equivalent
167 name = filepath.Clean(name)
172 return "", errors.New("kevent instance already closed")
174 watchfd, alreadyWatching := w.watches[name]
175 // We already have a watch, but we can still override flags.
177 isDir = w.paths[watchfd].isDir
181 if !alreadyWatching {
182 fi, err := os.Lstat(name)
187 // Don't watch sockets.
188 if fi.Mode()&os.ModeSocket == os.ModeSocket {
192 // Don't watch named pipes.
193 if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe {
198 // Unfortunately, Linux can add bogus symlinks to watch list without
199 // issue, and Windows can't do symlinks period (AFAIK). To maintain
200 // consistency, we will act like everything is fine. There will simply
201 // be no file events for broken symlinks.
202 // Hence the returns of nil on errors.
203 if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
204 name, err = filepath.EvalSymlinks(name)
210 _, alreadyWatching = w.watches[name]
217 fi, err = os.Lstat(name)
223 watchfd, err = unix.Open(name, openMode, 0700)
231 const registerAdd = unix.EV_ADD | unix.EV_CLEAR | unix.EV_ENABLE
232 if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil {
237 if !alreadyWatching {
239 w.watches[name] = watchfd
240 w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
245 // Watch the directory if it has not been watched before,
246 // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles)
249 watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE &&
250 (!alreadyWatching || (w.dirFlags[name]&unix.NOTE_WRITE) != unix.NOTE_WRITE)
251 // Store flags so this watch can be updated later
252 w.dirFlags[name] = flags
256 if err := w.watchDirectoryFiles(name); err != nil {
264 // readEvents reads from kqueue and converts the received kevents into
265 // Event values that it sends down the Events channel.
266 func (w *Watcher) readEvents() {
267 eventBuffer := make([]unix.Kevent_t, 10)
270 // See if there is a message on the "done" channel
273 err := unix.Close(w.kq)
284 kevents, err := read(w.kq, eventBuffer, &keventWaitTime)
285 // EINTR is okay, the syscall was interrupted before timeout expired.
286 if err != nil && err != unix.EINTR {
291 // Flush the events we received to the Events channel
292 for len(kevents) > 0 {
293 kevent := &kevents[0]
294 watchfd := int(kevent.Ident)
295 mask := uint32(kevent.Fflags)
297 path := w.paths[watchfd]
299 event := newEvent(path.name, mask)
301 if path.isDir && !(event.Op&Remove == Remove) {
302 // Double check to make sure the directory exists. This can happen when
303 // we do a rm -fr on a recursively watched folders and we receive a
304 // modification event first but the folder has been deleted and later
305 // receive the delete event
306 if _, err := os.Lstat(event.Name); os.IsNotExist(err) {
307 // mark is as delete event
312 if event.Op&Rename == Rename || event.Op&Remove == Remove {
315 delete(w.fileExists, event.Name)
319 if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) {
320 w.sendDirectoryChangeEvents(event.Name)
322 // Send the event on the Events channel
326 if event.Op&Remove == Remove {
327 // Look for a file that may have overwritten this.
328 // For example, mv f1 f2 will delete f2, then create f2.
330 fileDir := filepath.Clean(event.Name)
332 _, found := w.watches[fileDir]
335 // make sure the directory exists before we watch for changes. When we
336 // do a recursive watch and perform rm -fr, the parent directory might
337 // have gone missing, ignore the missing directory and let the
338 // upcoming delete event remove the watch from the parent directory.
339 if _, err := os.Lstat(fileDir); err == nil {
340 w.sendDirectoryChangeEvents(fileDir)
344 filePath := filepath.Clean(event.Name)
345 if fileInfo, err := os.Lstat(filePath); err == nil {
346 w.sendFileCreatedEventIfNew(filePath, fileInfo)
351 // Move to next event
352 kevents = kevents[1:]
357 // newEvent returns an platform-independent Event based on kqueue Fflags.
358 func newEvent(name string, mask uint32) Event {
359 e := Event{Name: name}
360 if mask&unix.NOTE_DELETE == unix.NOTE_DELETE {
363 if mask&unix.NOTE_WRITE == unix.NOTE_WRITE {
366 if mask&unix.NOTE_RENAME == unix.NOTE_RENAME {
369 if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB {
375 func newCreateEvent(name string) Event {
376 return Event{Name: name, Op: Create}
379 // watchDirectoryFiles to mimic inotify when adding a watch on a directory
380 func (w *Watcher) watchDirectoryFiles(dirPath string) error {
382 files, err := ioutil.ReadDir(dirPath)
387 for _, fileInfo := range files {
388 filePath := filepath.Join(dirPath, fileInfo.Name())
389 filePath, err = w.internalWatch(filePath, fileInfo)
395 w.fileExists[filePath] = true
402 // sendDirectoryEvents searches the directory for newly created files
403 // and sends them over the event channel. This functionality is to have
404 // the BSD version of fsnotify match Linux inotify which provides a
405 // create event for files created in a watched directory.
406 func (w *Watcher) sendDirectoryChangeEvents(dirPath string) {
408 files, err := ioutil.ReadDir(dirPath)
413 // Search for new files
414 for _, fileInfo := range files {
415 filePath := filepath.Join(dirPath, fileInfo.Name())
416 err := w.sendFileCreatedEventIfNew(filePath, fileInfo)
424 // sendFileCreatedEvent sends a create event if the file isn't already being tracked.
425 func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) {
427 _, doesExist := w.fileExists[filePath]
431 w.Events <- newCreateEvent(filePath)
434 // like watchDirectoryFiles (but without doing another ReadDir)
435 filePath, err = w.internalWatch(filePath, fileInfo)
441 w.fileExists[filePath] = true
447 func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) (string, error) {
448 if fileInfo.IsDir() {
449 // mimic Linux providing delete events for subdirectories
450 // but preserve the flags used if currently watching subdirectory
452 flags := w.dirFlags[name]
455 flags |= unix.NOTE_DELETE | unix.NOTE_RENAME
456 return w.addWatch(name, flags)
459 // watch file to mimic Linux inotify
460 return w.addWatch(name, noteAllEvents)
463 // kqueue creates a new kernel event queue and returns a descriptor.
464 func kqueue() (kq int, err error) {
465 kq, err = unix.Kqueue()
472 // register events with the queue
473 func register(kq int, fds []int, flags int, fflags uint32) error {
474 changes := make([]unix.Kevent_t, len(fds))
476 for i, fd := range fds {
477 // SetKevent converts int to the platform-specific types:
478 unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags)
479 changes[i].Fflags = fflags
482 // register the events
483 success, err := unix.Kevent(kq, changes, nil, nil)
490 // read retrieves pending events, or waits until an event occurs.
491 // A timeout of nil blocks indefinitely, while 0 polls the queue.
492 func read(kq int, events []unix.Kevent_t, timeout *unix.Timespec) ([]unix.Kevent_t, error) {
493 n, err := unix.Kevent(kq, nil, events, timeout)
497 return events[0:n], nil
500 // durationToTimespec prepares a timeout value
501 func durationToTimespec(d time.Duration) unix.Timespec {
502 return unix.NsecToTimespec(d.Nanoseconds())