OSDN Git Service

Hulk did something
[bytom/vapor.git] / vendor / github.com / fsnotify / fsnotify / kqueue.go
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 // +build freebsd openbsd netbsd dragonfly darwin
6
7 package fsnotify
8
9 import (
10         "errors"
11         "fmt"
12         "io/ioutil"
13         "os"
14         "path/filepath"
15         "sync"
16         "time"
17
18         "golang.org/x/sys/unix"
19 )
20
21 // Watcher watches a set of files, delivering events to a channel.
22 type Watcher struct {
23         Events chan Event
24         Errors chan error
25         done   chan bool // Channel for sending a "quit message" to the reader goroutine
26
27         kq int // File descriptor (as returned by the kqueue() syscall).
28
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
36 }
37
38 type pathInfo struct {
39         name  string
40         isDir bool
41 }
42
43 // NewWatcher establishes a new watcher with the underlying OS and begins waiting for events.
44 func NewWatcher() (*Watcher, error) {
45         kq, err := kqueue()
46         if err != nil {
47                 return nil, err
48         }
49
50         w := &Watcher{
51                 kq:              kq,
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),
60         }
61
62         go w.readEvents()
63         return w, nil
64 }
65
66 // Close removes all watches and closes the events channel.
67 func (w *Watcher) Close() error {
68         w.mu.Lock()
69         if w.isClosed {
70                 w.mu.Unlock()
71                 return nil
72         }
73         w.isClosed = true
74         w.mu.Unlock()
75
76         // copy paths to remove while locked
77         w.mu.Lock()
78         var pathsToRemove = make([]string, 0, len(w.watches))
79         for name := range w.watches {
80                 pathsToRemove = append(pathsToRemove, name)
81         }
82         w.mu.Unlock()
83         // unlock before calling Remove, which also locks
84
85         var err error
86         for _, name := range pathsToRemove {
87                 if e := w.Remove(name); e != nil && err == nil {
88                         err = e
89                 }
90         }
91
92         // Send "quit" message to the reader goroutine:
93         w.done <- true
94
95         return nil
96 }
97
98 // Add starts watching the named file or directory (non-recursively).
99 func (w *Watcher) Add(name string) error {
100         w.mu.Lock()
101         w.externalWatches[name] = true
102         w.mu.Unlock()
103         _, err := w.addWatch(name, noteAllEvents)
104         return err
105 }
106
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)
110         w.mu.Lock()
111         watchfd, ok := w.watches[name]
112         w.mu.Unlock()
113         if !ok {
114                 return fmt.Errorf("can't remove non-existent kevent watch for: %s", name)
115         }
116
117         const registerRemove = unix.EV_DELETE
118         if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil {
119                 return err
120         }
121
122         unix.Close(watchfd)
123
124         w.mu.Lock()
125         isDir := w.paths[watchfd].isDir
126         delete(w.watches, name)
127         delete(w.paths, watchfd)
128         delete(w.dirFlags, name)
129         w.mu.Unlock()
130
131         // Find all watched paths that are in this directory that are not external.
132         if isDir {
133                 var pathsToRemove []string
134                 w.mu.Lock()
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)
140                                 }
141                         }
142                 }
143                 w.mu.Unlock()
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.
148                         w.Remove(name)
149                 }
150         }
151
152         return nil
153 }
154
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
157
158 // keventWaitTime to block on each read from kevent
159 var keventWaitTime = durationToTimespec(100 * time.Millisecond)
160
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) {
165         var isDir bool
166         // Make ./name and name equivalent
167         name = filepath.Clean(name)
168
169         w.mu.Lock()
170         if w.isClosed {
171                 w.mu.Unlock()
172                 return "", errors.New("kevent instance already closed")
173         }
174         watchfd, alreadyWatching := w.watches[name]
175         // We already have a watch, but we can still override flags.
176         if alreadyWatching {
177                 isDir = w.paths[watchfd].isDir
178         }
179         w.mu.Unlock()
180
181         if !alreadyWatching {
182                 fi, err := os.Lstat(name)
183                 if err != nil {
184                         return "", err
185                 }
186
187                 // Don't watch sockets.
188                 if fi.Mode()&os.ModeSocket == os.ModeSocket {
189                         return "", nil
190                 }
191
192                 // Don't watch named pipes.
193                 if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe {
194                         return "", nil
195                 }
196
197                 // Follow Symlinks
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)
205                         if err != nil {
206                                 return "", nil
207                         }
208
209                         w.mu.Lock()
210                         _, alreadyWatching = w.watches[name]
211                         w.mu.Unlock()
212
213                         if alreadyWatching {
214                                 return name, nil
215                         }
216
217                         fi, err = os.Lstat(name)
218                         if err != nil {
219                                 return "", nil
220                         }
221                 }
222
223                 watchfd, err = unix.Open(name, openMode, 0700)
224                 if watchfd == -1 {
225                         return "", err
226                 }
227
228                 isDir = fi.IsDir()
229         }
230
231         const registerAdd = unix.EV_ADD | unix.EV_CLEAR | unix.EV_ENABLE
232         if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil {
233                 unix.Close(watchfd)
234                 return "", err
235         }
236
237         if !alreadyWatching {
238                 w.mu.Lock()
239                 w.watches[name] = watchfd
240                 w.paths[watchfd] = pathInfo{name: name, isDir: isDir}
241                 w.mu.Unlock()
242         }
243
244         if 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)
247                 w.mu.Lock()
248
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
253                 w.mu.Unlock()
254
255                 if watchDir {
256                         if err := w.watchDirectoryFiles(name); err != nil {
257                                 return "", err
258                         }
259                 }
260         }
261         return name, nil
262 }
263
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)
268
269         for {
270                 // See if there is a message on the "done" channel
271                 select {
272                 case <-w.done:
273                         err := unix.Close(w.kq)
274                         if err != nil {
275                                 w.Errors <- err
276                         }
277                         close(w.Events)
278                         close(w.Errors)
279                         return
280                 default:
281                 }
282
283                 // Get new events
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 {
287                         w.Errors <- err
288                         continue
289                 }
290
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)
296                         w.mu.Lock()
297                         path := w.paths[watchfd]
298                         w.mu.Unlock()
299                         event := newEvent(path.name, mask)
300
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
308                                         event.Op |= Remove
309                                 }
310                         }
311
312                         if event.Op&Rename == Rename || event.Op&Remove == Remove {
313                                 w.Remove(event.Name)
314                                 w.mu.Lock()
315                                 delete(w.fileExists, event.Name)
316                                 w.mu.Unlock()
317                         }
318
319                         if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) {
320                                 w.sendDirectoryChangeEvents(event.Name)
321                         } else {
322                                 // Send the event on the Events channel
323                                 w.Events <- event
324                         }
325
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.
329                                 if path.isDir {
330                                         fileDir := filepath.Clean(event.Name)
331                                         w.mu.Lock()
332                                         _, found := w.watches[fileDir]
333                                         w.mu.Unlock()
334                                         if found {
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)
341                                                 }
342                                         }
343                                 } else {
344                                         filePath := filepath.Clean(event.Name)
345                                         if fileInfo, err := os.Lstat(filePath); err == nil {
346                                                 w.sendFileCreatedEventIfNew(filePath, fileInfo)
347                                         }
348                                 }
349                         }
350
351                         // Move to next event
352                         kevents = kevents[1:]
353                 }
354         }
355 }
356
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 {
361                 e.Op |= Remove
362         }
363         if mask&unix.NOTE_WRITE == unix.NOTE_WRITE {
364                 e.Op |= Write
365         }
366         if mask&unix.NOTE_RENAME == unix.NOTE_RENAME {
367                 e.Op |= Rename
368         }
369         if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB {
370                 e.Op |= Chmod
371         }
372         return e
373 }
374
375 func newCreateEvent(name string) Event {
376         return Event{Name: name, Op: Create}
377 }
378
379 // watchDirectoryFiles to mimic inotify when adding a watch on a directory
380 func (w *Watcher) watchDirectoryFiles(dirPath string) error {
381         // Get all files
382         files, err := ioutil.ReadDir(dirPath)
383         if err != nil {
384                 return err
385         }
386
387         for _, fileInfo := range files {
388                 filePath := filepath.Join(dirPath, fileInfo.Name())
389                 filePath, err = w.internalWatch(filePath, fileInfo)
390                 if err != nil {
391                         return err
392                 }
393
394                 w.mu.Lock()
395                 w.fileExists[filePath] = true
396                 w.mu.Unlock()
397         }
398
399         return nil
400 }
401
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) {
407         // Get all files
408         files, err := ioutil.ReadDir(dirPath)
409         if err != nil {
410                 w.Errors <- err
411         }
412
413         // Search for new files
414         for _, fileInfo := range files {
415                 filePath := filepath.Join(dirPath, fileInfo.Name())
416                 err := w.sendFileCreatedEventIfNew(filePath, fileInfo)
417
418                 if err != nil {
419                         return
420                 }
421         }
422 }
423
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) {
426         w.mu.Lock()
427         _, doesExist := w.fileExists[filePath]
428         w.mu.Unlock()
429         if !doesExist {
430                 // Send create event
431                 w.Events <- newCreateEvent(filePath)
432         }
433
434         // like watchDirectoryFiles (but without doing another ReadDir)
435         filePath, err = w.internalWatch(filePath, fileInfo)
436         if err != nil {
437                 return err
438         }
439
440         w.mu.Lock()
441         w.fileExists[filePath] = true
442         w.mu.Unlock()
443
444         return nil
445 }
446
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
451                 w.mu.Lock()
452                 flags := w.dirFlags[name]
453                 w.mu.Unlock()
454
455                 flags |= unix.NOTE_DELETE | unix.NOTE_RENAME
456                 return w.addWatch(name, flags)
457         }
458
459         // watch file to mimic Linux inotify
460         return w.addWatch(name, noteAllEvents)
461 }
462
463 // kqueue creates a new kernel event queue and returns a descriptor.
464 func kqueue() (kq int, err error) {
465         kq, err = unix.Kqueue()
466         if kq == -1 {
467                 return kq, err
468         }
469         return kq, nil
470 }
471
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))
475
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
480         }
481
482         // register the events
483         success, err := unix.Kevent(kq, changes, nil, nil)
484         if success == -1 {
485                 return err
486         }
487         return nil
488 }
489
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)
494         if err != nil {
495                 return nil, err
496         }
497         return events[0:n], nil
498 }
499
500 // durationToTimespec prepares a timeout value
501 func durationToTimespec(d time.Duration) unix.Timespec {
502         return unix.NsecToTimespec(d.Nanoseconds())
503 }