OLD | NEW |
---|---|
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "content/common/file_path_watcher/file_path_watcher.h" | 5 #include "content/common/file_path_watcher/file_path_watcher.h" |
6 | 6 |
7 #include <CoreServices/CoreServices.h> | 7 #include <fcntl.h> |
8 #include <set> | 8 #include <sys/event.h> |
9 | 9 #include <sys/param.h> |
10 #include "base/file_path.h" | 10 |
11 #include <vector> | |
12 | |
11 #include "base/file_util.h" | 13 #include "base/file_util.h" |
12 #include "base/logging.h" | |
13 #include "base/mac/scoped_cftyperef.h" | |
14 #include "base/memory/singleton.h" | |
15 #include "base/message_loop.h" | 14 #include "base/message_loop.h" |
16 #include "base/time.h" | 15 #include "base/message_loop_proxy.h" |
17 | 16 #include "base/stringprintf.h" |
18 // Note to future well meaning engineers. Unless kqueue semantics have changed | |
19 // considerably, do NOT try to reimplement this class using kqueue. The main | |
20 // problem is that this class requires the ability to watch a directory | |
21 // and notice changes to any files within it. A kqueue on a directory can watch | |
22 // for creation and deletion of files, but not for modifications to files within | |
23 // the directory. To do this with the current kqueue semantics would require | |
24 // kqueueing every file in the directory, and file descriptors are a limited | |
25 // resource. If you have a good idea on how to get around this, the source for a | |
26 // reasonable implementation of this class using kqueues is attached here: | |
27 // http://code.google.com/p/chromium/issues/detail?id=54822#c13 | |
28 | 17 |
29 namespace { | 18 namespace { |
30 | 19 |
31 // The latency parameter passed to FSEventsStreamCreate(). | 20 // Mac-specific file watcher implementation based on kqueue. |
32 const CFAbsoluteTime kEventLatencySeconds = 0.3; | 21 // Originally it was based on FSEvents so that the semantics were equivalent |
33 | 22 // on Linux, OSX and Windows where it was able to detect: |
34 // Mac-specific file watcher implementation based on the FSEvents API. | 23 // - file creation/deletion/modification in a watched directory |
24 // - file creation/deletion/modification for a watched file | |
25 // - modifications to the paths to a watched object that would affect the | |
26 // object such as renaming/attibute changes etc. | |
27 // The FSEvents version did all of the above except handling attribute changes | |
28 // to path components. Unfortunately FSEvents appears to have an issue where the | |
29 // current implementation (Mac OS X 10.6.7) sometimes drops events and doesn't | |
30 // send notifications. See | |
31 // http://code.google.com/p/chromium/issues/detail?id=54822#c31 for source that | |
32 // will reproduce the problem. FSEvents also required having a CFRunLoop | |
33 // backing the thread that it was running on, that caused added complexity | |
34 // in the interfaces. | |
35 // The kqueue implementation will handle all of the items in the list above | |
36 // except for detecting modifications to files in a watched directory. It will | |
37 // detect the creation and deletion of files, just not the modification of | |
38 // files. It does however detect the attribute changes that the FSEvents impl | |
39 // would miss. | |
35 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate, | 40 class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate, |
41 public MessageLoopForIO::Watcher, | |
36 public MessageLoop::DestructionObserver { | 42 public MessageLoop::DestructionObserver { |
37 public: | 43 public: |
38 FilePathWatcherImpl(); | 44 FilePathWatcherImpl() : kqueue_(-1) {} |
39 | 45 virtual ~FilePathWatcherImpl() {} |
40 // Called from the FSEvents callback whenever there is a change to the paths | 46 |
41 void OnFilePathChanged(); | 47 // MessageLoopForIO::Watcher overrides. |
42 | 48 virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE; |
43 // (Re-)Initialize the event stream to start reporting events from | 49 virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE; |
44 // |start_event|. | 50 |
45 void UpdateEventStream(FSEventStreamEventId start_event); | 51 // MessageLoop::DestructionObserver overrides. |
52 virtual void WillDestroyCurrentMessageLoop() OVERRIDE; | |
46 | 53 |
47 // FilePathWatcher::PlatformDelegate overrides. | 54 // FilePathWatcher::PlatformDelegate overrides. |
48 virtual bool Watch(const FilePath& path, | 55 virtual bool Watch(const FilePath& path, |
49 FilePathWatcher::Delegate* delegate, | 56 FilePathWatcher::Delegate* delegate) OVERRIDE; |
50 base::MessageLoopProxy* loop) OVERRIDE; | |
51 virtual void Cancel() OVERRIDE; | 57 virtual void Cancel() OVERRIDE; |
52 | 58 |
53 // Deletion of the FilePathWatcher will call Cancel() to dispose of this | |
54 // object in the right thread. This also observes destruction of the required | |
55 // cleanup thread, in case it quits before Cancel() is called. | |
56 virtual void WillDestroyCurrentMessageLoop() OVERRIDE; | |
57 | |
58 scoped_refptr<base::MessageLoopProxy> run_loop_message_loop() { | |
59 return run_loop_message_loop_; | |
60 } | |
61 | |
62 private: | 59 private: |
63 virtual ~FilePathWatcherImpl() {} | 60 class EventData { |
64 | 61 public: |
65 // Destroy the event stream. | 62 EventData(const FilePath& path, const FilePath::StringType& subdir) |
66 void DestroyEventStream(); | 63 : path_(path), subdir_(subdir) { } |
67 | 64 FilePath path_; // Full path to this item. |
68 // Start observing the destruction of the |run_loop_message_loop_| thread, | 65 FilePath::StringType subdir_; // Path to any sub item. |
69 // and watching the FSEventStream. | 66 }; |
70 void StartObserverAndEventStream(FSEventStreamEventId start_event); | 67 typedef std::vector<struct kevent> EventVector; |
71 | 68 |
72 // Cleans up and stops observing the |run_loop_message_loop_| thread. | 69 // Can only be called on |io_message_loop_|'s thread. |
73 void CancelOnMessageLoopThread() OVERRIDE; | 70 virtual void CancelOnMessageLoopThread() OVERRIDE; |
74 | 71 |
75 // Delegate to notify upon changes. | 72 // Returns true if the kevent values are error free. |
73 bool AreKeventValuesValid(struct kevent* kevents, int count); | |
74 | |
75 // Respond to a change of attributes of the path component represented by | |
76 // |event|. Sets |target_file_affected| to true if |target_| is affected. | |
77 // Sets |update_watches| to true if |events_| need to be updated. | |
78 void HandleAttributesChange(const EventVector::iterator& event, | |
79 bool* target_file_affected, | |
80 bool* update_watches); | |
81 | |
82 // Respond to a move of deletion of the path component represented by | |
83 // |event|. Sets |target_file_affected| to true if |target_| is affected. | |
84 // Sets |update_watches| to true if |events_| need to be updated. | |
85 void HandleDeleteOrMoveChange(const EventVector::iterator& event, | |
86 bool* target_file_affected, | |
87 bool* update_watches); | |
88 | |
89 // Respond to a creation of an item in the path component represented by | |
90 // |event|. Sets |target_file_affected| to true if |target_| is affected. | |
91 // Sets |update_watches| to true if |events_| need to be updated. | |
92 void HandleCreateItemChange(const EventVector::iterator& event, | |
93 bool* target_file_affected, | |
94 bool* update_watches); | |
95 | |
96 // Update |events_| with the current status of the system. | |
97 // Sets |target_file_affected| to true if |target_| is affected. | |
98 // Returns false if an error occurs. | |
99 bool UpdateWatches(bool* target_file_affected); | |
100 | |
101 // Fills |events| with one kevent per component in |path|. | |
102 // Returns the number of valid events created where a valid event is | |
103 // defined as one that has a ident (file descriptor) field != -1. | |
104 static int EventsForPath(FilePath path, EventVector *events); | |
105 | |
106 // Release a kevent generated by EventsForPath. | |
107 static void ReleaseEvent(struct kevent& event); | |
108 | |
109 // Returns a file descriptor that will not block the system from deleting | |
110 // the file it references. | |
111 static int FileDescriptorForPath(const FilePath& path); | |
112 | |
113 // Closes |*fd| and sets |*fd| to -1. | |
114 static void CloseFileDescriptor(int* fd); | |
115 | |
116 // Returns true if kevent has open file descriptor. | |
117 static bool IsKeventFileDescriptorOpen(const struct kevent& event) { | |
118 return event.ident != static_cast<uintptr_t>(-1); | |
119 } | |
120 | |
121 static EventData* EventDataForKevent(const struct kevent& event) { | |
122 return reinterpret_cast<EventData*>(event.udata); | |
123 } | |
124 | |
125 EventVector events_; | |
126 scoped_refptr<base::MessageLoopProxy> io_message_loop_; | |
127 MessageLoopForIO::FileDescriptorWatcher kqueue_watcher_; | |
76 scoped_refptr<FilePathWatcher::Delegate> delegate_; | 128 scoped_refptr<FilePathWatcher::Delegate> delegate_; |
77 | |
78 // Target path to watch (passed to delegate). | |
79 FilePath target_; | 129 FilePath target_; |
80 | 130 int kqueue_; |
81 // Keep track of the last modified time of the file. We use nulltime | |
82 // to represent the file not existing. | |
83 base::Time last_modified_; | |
84 | |
85 // The time at which we processed the first notification with the | |
86 // |last_modified_| time stamp. | |
87 base::Time first_notification_; | |
88 | |
89 // Backend stream we receive event callbacks from (strong reference). | |
90 FSEventStreamRef fsevent_stream_; | |
91 | |
92 // Run loop for FSEventStream to run on. | |
93 scoped_refptr<base::MessageLoopProxy> run_loop_message_loop_; | |
94 | 131 |
95 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); | 132 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); |
96 }; | 133 }; |
97 | 134 |
98 // The callback passed to FSEventStreamCreate(). | 135 void FilePathWatcherImpl::ReleaseEvent(struct kevent& event) { |
99 void FSEventsCallback(ConstFSEventStreamRef stream, | 136 CloseFileDescriptor(reinterpret_cast<int*>(&event.ident)); |
100 void* event_watcher, size_t num_events, | 137 EventData* entry = EventDataForKevent(event); |
101 void* event_paths, const FSEventStreamEventFlags flags[], | 138 delete entry; |
102 const FSEventStreamEventId event_ids[]) { | 139 event.udata = NULL; |
103 FilePathWatcherImpl* watcher = | 140 } |
104 reinterpret_cast<FilePathWatcherImpl*>(event_watcher); | 141 |
105 DCHECK(watcher->run_loop_message_loop()->BelongsToCurrentThread()); | 142 int FilePathWatcherImpl::EventsForPath(FilePath path, EventVector* events) { |
106 | 143 DCHECK(MessageLoopForIO::current()); |
107 bool root_changed = false; | 144 // Make sure that we are working with a clean slate. |
108 FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream); | 145 DCHECK(events->empty()); |
109 for (size_t i = 0; i < num_events; i++) { | 146 |
110 if (flags[i] & kFSEventStreamEventFlagRootChanged) | 147 std::vector<FilePath::StringType> components; |
111 root_changed = true; | 148 path.GetComponents(&components); |
112 if (event_ids[i]) | 149 |
113 root_change_at = std::min(root_change_at, event_ids[i]); | 150 if (components.size() < 1) { |
114 } | 151 return -1; |
115 | 152 } |
116 // Reinitialize the event stream if we find changes to the root. This is | 153 |
117 // necessary since FSEvents doesn't report any events for the subtree after | 154 int last_existing_entry = 0; |
118 // the directory to be watched gets created. | 155 FilePath built_path; |
119 if (root_changed) { | 156 bool path_still_exists = true; |
120 // Resetting the event stream from within the callback fails (FSEvents spews | 157 for(std::vector<FilePath::StringType>::iterator i = components.begin(); |
121 // bad file descriptor errors), so post a task to do the reset. | 158 i != components.end(); ++i) { |
122 watcher->run_loop_message_loop()->PostTask(FROM_HERE, | 159 if (i == components.begin()) { |
123 NewRunnableMethod(watcher, &FilePathWatcherImpl::UpdateEventStream, | 160 built_path = FilePath(*i); |
124 root_change_at)); | 161 } else { |
125 } | 162 built_path = built_path.Append(*i); |
126 | 163 } |
127 watcher->OnFilePathChanged(); | 164 int fd = -1; |
128 } | 165 if (path_still_exists) { |
129 | 166 fd = FileDescriptorForPath(built_path); |
130 // FilePathWatcherImpl implementation: | 167 if (fd == -1) { |
131 | 168 path_still_exists = false; |
132 FilePathWatcherImpl::FilePathWatcherImpl() | 169 } else { |
133 : fsevent_stream_(NULL) { | 170 ++last_existing_entry; |
134 } | 171 } |
135 | 172 } |
136 void FilePathWatcherImpl::OnFilePathChanged() { | 173 FilePath::StringType subdir = (i != (components.end() - 1)) ? *(i + 1) : ""; |
137 // Switch to the CFRunLoop based thread if necessary, so we can tear down | 174 EventData* data = new EventData(built_path, subdir); |
138 // the event stream. | 175 struct kevent event; |
139 if (!message_loop()->BelongsToCurrentThread()) { | 176 EV_SET(&event, fd, EVFILT_VNODE, (EV_ADD | EV_CLEAR | EV_RECEIPT), |
140 message_loop()->PostTask( | 177 (NOTE_DELETE | NOTE_WRITE | NOTE_ATTRIB | |
141 FROM_HERE, | 178 NOTE_RENAME | NOTE_REVOKE | NOTE_EXTEND), 0, data); |
142 NewRunnableMethod(this, &FilePathWatcherImpl::OnFilePathChanged)); | 179 events->push_back(event); |
180 } | |
181 return last_existing_entry; | |
182 } | |
183 | |
184 int FilePathWatcherImpl::FileDescriptorForPath(const FilePath& path) { | |
185 return HANDLE_EINTR(open(path.value().c_str(), O_EVTONLY)); | |
186 } | |
187 | |
188 void FilePathWatcherImpl::CloseFileDescriptor(int *fd) { | |
189 if (*fd == -1) { | |
143 return; | 190 return; |
144 } | 191 } |
145 | 192 |
146 DCHECK(message_loop()->BelongsToCurrentThread()); | 193 if (HANDLE_EINTR(close(*fd)) != 0) { |
147 DCHECK(!target_.empty()); | 194 PLOG(ERROR) << "close"; |
148 | 195 } |
149 base::PlatformFileInfo file_info; | 196 *fd = -1; |
150 bool file_exists = file_util::GetFileInfo(target_, &file_info); | 197 } |
151 if (file_exists && (last_modified_.is_null() || | 198 |
152 last_modified_ != file_info.last_modified)) { | 199 bool FilePathWatcherImpl::AreKeventValuesValid(struct kevent* kevents, |
153 last_modified_ = file_info.last_modified; | 200 int count) { |
154 first_notification_ = base::Time::Now(); | 201 if (count < 0) { |
202 PLOG(ERROR) << "kevent"; | |
203 return false; | |
204 } | |
205 bool valid = true; | |
206 for (int i = 0; i < count; ++i) { | |
207 if (kevents[i].flags & EV_ERROR && kevents[i].data) { | |
208 // Find the kevent in |events_| that matches the kevent with the error. | |
209 EventVector::iterator event = events_.begin(); | |
210 for (; event != events_.end(); ++event) { | |
211 if (event->ident == kevents[i].ident) { | |
212 break; | |
213 } | |
214 } | |
215 std::string path_name; | |
216 if (event != events_.end()) { | |
217 EventData* event_data = EventDataForKevent(*event); | |
218 if (event_data != NULL) { | |
219 path_name = event_data->path_.value(); | |
220 } | |
221 } | |
222 if (path_name.empty()) { | |
223 path_name = base::StringPrintf( | |
224 "fd %d", *reinterpret_cast<int*>(&kevents[i].ident)); | |
225 } | |
226 LOG(ERROR) << "Error: " << kevents[i].data << " for " << path_name; | |
227 valid = false; | |
228 } | |
229 } | |
230 return valid; | |
231 } | |
232 | |
233 void FilePathWatcherImpl::HandleAttributesChange( | |
234 const EventVector::iterator& event, | |
235 bool* target_file_affected, | |
236 bool* update_watches) { | |
237 EventVector::iterator next_event = event + 1; | |
238 EventData* next_event_data = EventDataForKevent(*next_event); | |
239 // Check to see if the next item in path is still accessible. | |
240 int have_access = FileDescriptorForPath(next_event_data->path_); | |
241 if (have_access == -1) { | |
242 *target_file_affected = true; | |
243 *update_watches = true; | |
244 EventVector::iterator local_event(event); | |
245 for (; local_event != events_.end(); ++local_event) { | |
246 // Close all nodes from the event down. This has the side effect of | |
247 // potentially rendering other events in |updates| invalid. | |
248 // There is no need to remove the events from |kqueue_| because this | |
249 // happens as a side effect of closing the file descriptor. | |
250 CloseFileDescriptor(reinterpret_cast<int*>(&local_event->ident)); | |
251 } | |
252 } else { | |
253 CloseFileDescriptor(&have_access); | |
254 } | |
255 } | |
256 | |
257 void FilePathWatcherImpl::HandleDeleteOrMoveChange( | |
258 const EventVector::iterator& event, | |
259 bool* target_file_affected, | |
260 bool* update_watches) { | |
261 *target_file_affected = true; | |
262 *update_watches = true; | |
263 EventVector::iterator local_event(event); | |
264 for (; local_event != events_.end(); ++local_event) { | |
265 // Close all nodes from the event down. This has the side effect of | |
266 // potentially rendering other events in |updates| invalid. | |
267 // There is no need to remove the events from |kqueue_| because this | |
268 // happens as a side effect of closing the file descriptor. | |
269 CloseFileDescriptor(reinterpret_cast<int*>(&local_event->ident)); | |
270 } | |
271 } | |
272 | |
273 void FilePathWatcherImpl::HandleCreateItemChange( | |
274 const EventVector::iterator& event, | |
275 bool* target_file_affected, | |
276 bool* update_watches) { | |
277 // Get the next item in the path. | |
278 EventVector::iterator next_event = event + 1; | |
279 EventData* next_event_data = EventDataForKevent(*next_event); | |
280 | |
281 // Check to see if it already has a valid file descriptor. | |
282 if (!IsKeventFileDescriptorOpen(*next_event)) { | |
283 // If not, attempt to open a file descriptor for it. | |
284 next_event->ident = FileDescriptorForPath(next_event_data->path_); | |
285 if (IsKeventFileDescriptorOpen(*next_event)) { | |
286 *update_watches = true; | |
287 if (next_event_data->subdir_.empty()) { | |
288 *target_file_affected = true; | |
289 } | |
290 } | |
291 } | |
292 } | |
293 | |
294 bool FilePathWatcherImpl::UpdateWatches(bool* target_file_affected) { | |
295 // Iterate over events adding kevents for items that exist to the kqueue. | |
296 // Then check to see if new components in the path have been created. | |
297 // Repeat until no new components in the path are detected. | |
298 // This is to get around races in directory creation in a watched path. | |
299 bool update_watches = true; | |
300 while (update_watches) { | |
301 size_t valid; | |
302 for (valid = 0; valid < events_.size(); ++valid) { | |
303 if (!IsKeventFileDescriptorOpen(events_[valid])) { | |
304 break; | |
305 } | |
306 } | |
307 if (valid == 0) { | |
308 // The root of the file path is inaccessible? | |
309 return false; | |
310 } | |
311 | |
312 EventVector updates(valid); | |
313 int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], valid, &updates[0], | |
314 valid, NULL)); | |
315 if (!AreKeventValuesValid(&updates[0], count)) { | |
316 return false; | |
317 } | |
318 update_watches = false; | |
319 for (; valid < events_.size(); ++valid) { | |
320 EventData* event_data = EventDataForKevent(events_[valid]); | |
321 events_[valid].ident = FileDescriptorForPath(event_data->path_); | |
322 if (IsKeventFileDescriptorOpen(events_[valid])) { | |
323 update_watches = true; | |
324 if (event_data->subdir_.empty()) { | |
325 *target_file_affected = true; | |
326 } | |
327 } else { | |
328 break; | |
329 } | |
330 } | |
331 } | |
332 return true; | |
333 } | |
334 | |
335 void FilePathWatcherImpl::OnFileCanReadWithoutBlocking(int fd) { | |
336 DCHECK(MessageLoopForIO::current()); | |
337 CHECK_EQ(fd, kqueue_); | |
338 CHECK(events_.size()); | |
339 | |
340 // Request the file system update notifications that have occurred and return | |
341 // them in |updates|. |count| will contain the number of updates that have | |
342 // occurred. | |
343 EventVector updates(events_.size()); | |
344 struct timespec timeout = {0, 0}; | |
345 int count = HANDLE_EINTR(kevent(kqueue_, NULL, 0, &updates[0], updates.size(), | |
346 &timeout)); | |
347 | |
348 // Error values are stored within updates, so check to make sure that no | |
349 // errors occurred. | |
350 if (!AreKeventValuesValid(&updates[0], count)) { | |
351 delegate_->OnFilePathError(target_); | |
352 Cancel(); | |
353 return; | |
354 } | |
355 | |
356 bool update_watches = false; | |
357 bool send_notification = false; | |
358 | |
359 // Iterate through each of the updates and react to them. | |
360 for (int i = 0; i < count; ++i) { | |
361 // Find our kevent record that matches the update notification. | |
362 EventVector::iterator event = events_.begin(); | |
363 for (; event != events_.end(); ++event) { | |
364 if (!IsKeventFileDescriptorOpen(*event) || | |
365 event->ident == updates[i].ident) { | |
366 break; | |
367 } | |
368 } | |
369 if (!IsKeventFileDescriptorOpen(*event) || event == events_.end()) { | |
370 // The event may no longer exist in |events_| because another event | |
371 // modified |events_| in such a way to make it invalid. For example if | |
372 // the path is /foo/bar/bam and foo is deleted, NOTE_DELETE events for | |
373 // foo, bar and bam will be sent. If foo is processed first, then | |
374 // the file descriptors for bar and bam will already be closed and set | |
375 // to -1 before they get a chance to be processed. | |
376 continue; | |
377 } | |
378 | |
379 EventData* event_data = EventDataForKevent(*event); | |
380 | |
381 // If the subdir is empty, this is the last item on the path and is the | |
382 // target file. | |
383 bool target_file_affected = event_data->subdir_.empty(); | |
384 if ((updates[i].fflags & NOTE_ATTRIB) && !target_file_affected) { | |
Mark Mentovai
2011/04/01 18:13:37
Rationalize your style here so everything is consi
| |
385 HandleAttributesChange(event, &target_file_affected, &update_watches); | |
386 } | |
387 if (updates[i].fflags & (NOTE_DELETE | NOTE_REVOKE | NOTE_RENAME)) { | |
388 HandleDeleteOrMoveChange(event, &target_file_affected, &update_watches); | |
389 } | |
390 if (updates[i].fflags & NOTE_WRITE && !target_file_affected) { | |
391 HandleCreateItemChange(event, &target_file_affected, &update_watches); | |
392 } | |
393 send_notification |= target_file_affected; | |
394 } | |
395 | |
396 if (update_watches) { | |
397 if (!UpdateWatches(&send_notification)) { | |
398 delegate_->OnFilePathError(target_); | |
399 Cancel(); | |
400 } | |
401 } | |
402 | |
403 if (send_notification) { | |
155 delegate_->OnFilePathChanged(target_); | 404 delegate_->OnFilePathChanged(target_); |
156 } else if (file_exists && !first_notification_.is_null()) { | 405 } |
157 // The target's last modification time is equal to what's on record. This | 406 } |
158 // means that either an unrelated event occurred, or the target changed | 407 |
159 // again (file modification times only have a resolution of 1s). Comparing | 408 void FilePathWatcherImpl::OnFileCanWriteWithoutBlocking(int fd) { |
160 // file modification times against the wall clock is not reliable to find | 409 NOTREACHED(); |
161 // out whether the change is recent, since this code might just run too | 410 } |
162 // late. Moreover, there's no guarantee that file modification time and wall | 411 |
163 // clock times come from the same source. | 412 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() { |
164 // | 413 CancelOnMessageLoopThread(); |
165 // Instead, the time at which the first notification carrying the current | |
166 // |last_notified_| time stamp is recorded. Later notifications that find | |
167 // the same file modification time only need to be forwarded until wall | |
168 // clock has advanced one second from the initial notification. After that | |
169 // interval, client code is guaranteed to having seen the current revision | |
170 // of the file. | |
171 if (base::Time::Now() - first_notification_ > | |
172 base::TimeDelta::FromSeconds(1)) { | |
173 // Stop further notifications for this |last_modification_| time stamp. | |
174 first_notification_ = base::Time(); | |
175 } | |
176 delegate_->OnFilePathChanged(target_); | |
177 } else if (!file_exists && !last_modified_.is_null()) { | |
178 last_modified_ = base::Time(); | |
179 delegate_->OnFilePathChanged(target_); | |
180 } | |
181 } | 414 } |
182 | 415 |
183 bool FilePathWatcherImpl::Watch(const FilePath& path, | 416 bool FilePathWatcherImpl::Watch(const FilePath& path, |
184 FilePathWatcher::Delegate* delegate, | 417 FilePathWatcher::Delegate* delegate) { |
185 base::MessageLoopProxy* loop) { | |
186 DCHECK(target_.value().empty()); | |
187 DCHECK(MessageLoopForIO::current()); | 418 DCHECK(MessageLoopForIO::current()); |
188 | 419 DCHECK(target_.value().empty()); // Can only watch one path. |
189 set_message_loop(base::MessageLoopProxy::CreateForCurrentThread()); | 420 DCHECK(delegate); |
190 run_loop_message_loop_ = loop; | 421 DCHECK_EQ(kqueue_, -1); |
422 | |
423 delegate_ = delegate; | |
191 target_ = path; | 424 target_ = path; |
192 delegate_ = delegate; | 425 |
193 | |
194 FSEventStreamEventId start_event = FSEventsGetCurrentEventId(); | |
195 | |
196 base::PlatformFileInfo file_info; | |
197 if (file_util::GetFileInfo(target_, &file_info)) { | |
198 last_modified_ = file_info.last_modified; | |
199 first_notification_ = base::Time::Now(); | |
200 } | |
201 | |
202 run_loop_message_loop()->PostTask(FROM_HERE, | |
203 NewRunnableMethod(this, &FilePathWatcherImpl::StartObserverAndEventStream, | |
204 start_event)); | |
205 | |
206 return true; | |
207 } | |
208 | |
209 void FilePathWatcherImpl::StartObserverAndEventStream( | |
210 FSEventStreamEventId start_event) { | |
211 DCHECK(run_loop_message_loop()->BelongsToCurrentThread()); | |
212 MessageLoop::current()->AddDestructionObserver(this); | 426 MessageLoop::current()->AddDestructionObserver(this); |
213 UpdateEventStream(start_event); | 427 io_message_loop_ = base::MessageLoopProxy::CreateForCurrentThread(); |
428 | |
429 kqueue_ = kqueue(); | |
430 if (kqueue_ == -1) { | |
431 PLOG(ERROR) << "kqueue"; | |
432 return false; | |
433 } | |
434 | |
435 int last_entry = EventsForPath(target_, &events_); | |
436 CHECK_NE(last_entry, 0); | |
437 | |
438 EventVector responses(last_entry); | |
439 | |
440 int count = HANDLE_EINTR(kevent(kqueue_, &events_[0], last_entry, | |
441 &responses[0], last_entry, NULL)); | |
442 if (!AreKeventValuesValid(&responses[0], count)) { | |
443 // Calling Cancel() here to close any file descriptors that were opened. | |
444 // This would happen in the destructor anyways, but FilePathWatchers tend to | |
445 // be long lived, and if an error has occurred, there is no reason to waste | |
446 // the file descriptors. | |
447 Cancel(); | |
448 return false; | |
449 } | |
450 | |
451 return MessageLoopForIO::current()->WatchFileDescriptor( | |
452 kqueue_, true, MessageLoopForIO::WATCH_READ, &kqueue_watcher_, this); | |
214 } | 453 } |
215 | 454 |
216 void FilePathWatcherImpl::Cancel() { | 455 void FilePathWatcherImpl::Cancel() { |
217 if (!run_loop_message_loop().get()) { | 456 base::MessageLoopProxy* proxy = io_message_loop_.get(); |
218 // Watch was never called, so exit. | 457 if (!proxy) { |
219 set_cancelled(); | 458 set_cancelled(); |
220 return; | 459 return; |
221 } | 460 } |
222 | 461 if (!proxy->BelongsToCurrentThread()) { |
223 // Switch to the CFRunLoop based thread if necessary, so we can tear down | 462 proxy->PostTask(FROM_HERE, |
224 // the event stream. | 463 NewRunnableMethod(this, &FilePathWatcherImpl::Cancel)); |
225 if (!run_loop_message_loop()->BelongsToCurrentThread()) { | 464 return; |
226 run_loop_message_loop()->PostTask(FROM_HERE, | 465 } |
227 new FilePathWatcher::CancelTask(this)); | 466 CancelOnMessageLoopThread(); |
228 } else { | |
229 CancelOnMessageLoopThread(); | |
230 } | |
231 } | 467 } |
232 | 468 |
233 void FilePathWatcherImpl::CancelOnMessageLoopThread() { | 469 void FilePathWatcherImpl::CancelOnMessageLoopThread() { |
234 set_cancelled(); | 470 DCHECK(MessageLoopForIO::current()); |
235 if (fsevent_stream_) { | 471 if (!is_cancelled()) { |
236 DestroyEventStream(); | 472 set_cancelled(); |
473 kqueue_watcher_.StopWatchingFileDescriptor(); | |
474 CloseFileDescriptor(&kqueue_); | |
475 std::for_each(events_.begin(), events_.end(), ReleaseEvent); | |
476 events_.clear(); | |
477 io_message_loop_.release(); | |
237 MessageLoop::current()->RemoveDestructionObserver(this); | 478 MessageLoop::current()->RemoveDestructionObserver(this); |
238 delegate_ = NULL; | 479 delegate_ = NULL; |
239 } | 480 } |
240 } | 481 } |
241 | 482 |
242 void FilePathWatcherImpl::WillDestroyCurrentMessageLoop() { | |
243 CancelOnMessageLoopThread(); | |
244 } | |
245 | |
246 void FilePathWatcherImpl::UpdateEventStream(FSEventStreamEventId start_event) { | |
247 DCHECK(run_loop_message_loop()->BelongsToCurrentThread()); | |
248 DCHECK(MessageLoopForUI::current()); | |
249 | |
250 // It can happen that the watcher gets canceled while tasks that call this | |
251 // function are still in flight, so abort if this situation is detected. | |
252 if (is_cancelled()) | |
253 return; | |
254 | |
255 if (fsevent_stream_) | |
256 DestroyEventStream(); | |
257 | |
258 base::mac::ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString( | |
259 NULL, target_.value().c_str(), kCFStringEncodingMacHFS)); | |
260 base::mac::ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString( | |
261 NULL, target_.DirName().value().c_str(), kCFStringEncodingMacHFS)); | |
262 CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() }; | |
263 base::mac::ScopedCFTypeRef<CFArrayRef> watched_paths(CFArrayCreate( | |
264 NULL, reinterpret_cast<const void**>(paths_array), arraysize(paths_array), | |
265 &kCFTypeArrayCallBacks)); | |
266 | |
267 FSEventStreamContext context; | |
268 context.version = 0; | |
269 context.info = this; | |
270 context.retain = NULL; | |
271 context.release = NULL; | |
272 context.copyDescription = NULL; | |
273 | |
274 fsevent_stream_ = FSEventStreamCreate(NULL, &FSEventsCallback, &context, | |
275 watched_paths, | |
276 start_event, | |
277 kEventLatencySeconds, | |
278 kFSEventStreamCreateFlagWatchRoot); | |
279 FSEventStreamScheduleWithRunLoop(fsevent_stream_, CFRunLoopGetCurrent(), | |
280 kCFRunLoopDefaultMode); | |
281 if (!FSEventStreamStart(fsevent_stream_)) { | |
282 message_loop()->PostTask(FROM_HERE, | |
283 NewRunnableMethod(delegate_.get(), | |
284 &FilePathWatcher::Delegate::OnError)); | |
285 } | |
286 } | |
287 | |
288 void FilePathWatcherImpl::DestroyEventStream() { | |
289 FSEventStreamStop(fsevent_stream_); | |
290 FSEventStreamUnscheduleFromRunLoop(fsevent_stream_, CFRunLoopGetCurrent(), | |
291 kCFRunLoopDefaultMode); | |
292 FSEventStreamRelease(fsevent_stream_); | |
293 fsevent_stream_ = NULL; | |
294 } | |
295 | |
296 } // namespace | 483 } // namespace |
297 | 484 |
298 FilePathWatcher::FilePathWatcher() { | 485 FilePathWatcher::FilePathWatcher() { |
299 impl_ = new FilePathWatcherImpl(); | 486 impl_ = new FilePathWatcherImpl(); |
300 } | 487 } |
OLD | NEW |