diff options
author | dmaclach@chromium.org <dmaclach@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-03-18 04:11:49 +0000 |
---|---|---|
committer | dmaclach@chromium.org <dmaclach@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-03-18 04:11:49 +0000 |
commit | b8ca91f78cf0ba682787ec1c4605021b304f1305 (patch) | |
tree | fa497cdf8396758fc777387c428ad1d9772cb4cd /content/common | |
parent | 0a7031a43ea2b15e606882e9c5e3da58f565b701 (diff) | |
download | chromium_src-b8ca91f78cf0ba682787ec1c4605021b304f1305.zip chromium_src-b8ca91f78cf0ba682787ec1c4605021b304f1305.tar.gz chromium_src-b8ca91f78cf0ba682787ec1c4605021b304f1305.tar.bz2 |
Move FilePathWatcher class from chrome/browser/... to content/common...
The service process needs FilePathWatcher, and with this change I
got rid of the dependency on BrowserThread which allows it to be moved to common/...
I also tried my hand at a kqueue impl on the Mac, but failed.
See http://code.google.com/p/chromium/issues/detail?id=54822#c13 for details.
BUG=74983
TEST=BUILD
Review URL: http://codereview.chromium.org/6670081
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@78664 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'content/common')
7 files changed, 1592 insertions, 0 deletions
diff --git a/content/common/file_path_watcher/file_path_watcher.cc b/content/common/file_path_watcher/file_path_watcher.cc new file mode 100644 index 0000000..05ea10c --- /dev/null +++ b/content/common/file_path_watcher/file_path_watcher.cc @@ -0,0 +1,36 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Cross platform methods for FilePathWatcher. See the various platform +// specific implementation files, too. + +#include "content/common/file_path_watcher/file_path_watcher.h" + +#include "base/logging.h" +#include "base/message_loop.h" + +FilePathWatcher::~FilePathWatcher() { + impl_->Cancel(); +} + +bool FilePathWatcher::Watch(const FilePath& path, + Delegate* delegate, + base::MessageLoopProxy* loop) { + DCHECK(path.IsAbsolute()); + return impl_->Watch(path, delegate, loop); +} + +FilePathWatcher::PlatformDelegate::~PlatformDelegate() { +} + +void FilePathWatcher::DeletePlatformDelegate::Destruct( + const PlatformDelegate* delegate) { + scoped_refptr<base::MessageLoopProxy> loop = delegate->message_loop(); + if (loop.get() == NULL || loop->BelongsToCurrentThread()) { + delete delegate; + } else { + loop->PostNonNestableTask(FROM_HERE, + new DeleteTask<PlatformDelegate>(delegate)); + } +} diff --git a/content/common/file_path_watcher/file_path_watcher.h b/content/common/file_path_watcher/file_path_watcher.h new file mode 100644 index 0000000..a7d0ca99 --- /dev/null +++ b/content/common/file_path_watcher/file_path_watcher.h @@ -0,0 +1,102 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This module provides a way to monitor a file or directory for changes. + +#ifndef CONTENT_COMMON_FILE_PATH_WATCHER_FILE_PATH_WATCHER_H_ +#define CONTENT_COMMON_FILE_PATH_WATCHER_FILE_PATH_WATCHER_H_ +#pragma once + +#include "base/basictypes.h" +#include "base/file_path.h" +#include "base/message_loop_proxy.h" +#include "base/ref_counted.h" + +// This class lets you register interest in changes on a FilePath. +// The delegate will get called whenever the file or directory referenced by the +// FilePath is changed, including created or deleted. Due to limitations in the +// underlying OS APIs, spurious notifications might occur that don't relate to +// an actual change to the watch target. +class FilePathWatcher { + public: + // Declares the callback client code implements to receive notifications. Note + // that implementations of this interface should not keep a reference to the + // corresponding FileWatcher object to prevent a reference cycle. + class Delegate : public base::RefCountedThreadSafe<Delegate> { + public: + virtual ~Delegate() {} + virtual void OnFilePathChanged(const FilePath& path) = 0; + // Called when platform specific code detected an error. The watcher will + // not call OnFilePathChanged for future changes. + virtual void OnError() {} + }; + + FilePathWatcher(); + ~FilePathWatcher(); + + // Register interest in any changes on |path|. OnPathChanged will be called + // back for each change. Returns true on success. |loop| is only used + // by the Mac implementation right now, and must be backed by a CFRunLoop + // based MessagePump. This is usually going to be a MessageLoop of type + // TYPE_UI. + bool Watch(const FilePath& path, + Delegate* delegate, + base::MessageLoopProxy* loop) WARN_UNUSED_RESULT; + + class PlatformDelegate; + + // Traits for PlatformDelegate, which must delete itself on the IO message + // loop that Watch was called from. + struct DeletePlatformDelegate { + static void Destruct(const PlatformDelegate* delegate); + }; + + // Used internally to encapsulate different members on different platforms. + class PlatformDelegate + : public base::RefCountedThreadSafe<PlatformDelegate, + DeletePlatformDelegate> { + public: + // Start watching for the given |path| and notify |delegate| about changes. + // |loop| is only used by the Mac implementation right now, and must be + // backed by a CFRunLoop based MessagePump. This is usually going to be a + // MessageLoop of type TYPE_UI. + virtual bool Watch( + const FilePath& path, + Delegate* delegate, + base::MessageLoopProxy* loop) WARN_UNUSED_RESULT = 0; + + // Stop watching. This is called from FilePathWatcher's dtor in order to + // allow to shut down properly while the object is still alive. + virtual void Cancel() = 0; + + /* scoped_refptr<base::MessageLoopProxy> message_loop() const { + return message_loop_; + } + void set_message_loop(base::MessageLoopProxy* loop);*/ + + protected: + friend class DeleteTask<PlatformDelegate>; + friend struct DeletePlatformDelegate; + virtual ~PlatformDelegate(); + + scoped_refptr<base::MessageLoopProxy> message_loop() const { + return message_loop_; + } + + void set_message_loop(base::MessageLoopProxy* loop) { + message_loop_ = loop; + } + + private: + // IO Message Loop. + scoped_refptr<base::MessageLoopProxy> message_loop_; + }; + + private: + scoped_refptr<PlatformDelegate> impl_; + + DISALLOW_COPY_AND_ASSIGN(FilePathWatcher); +}; + +#endif // CONTENT_COMMON_FILE_PATH_WATCHER_FILE_PATH_WATCHER_H_ diff --git a/content/common/file_path_watcher/file_path_watcher_browsertest.cc b/content/common/file_path_watcher/file_path_watcher_browsertest.cc new file mode 100644 index 0000000..8480741 --- /dev/null +++ b/content/common/file_path_watcher/file_path_watcher_browsertest.cc @@ -0,0 +1,469 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/common/file_path_watcher/file_path_watcher.h" + +#include <set> + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/message_loop.h" +#include "base/message_loop_proxy.h" +#include "base/path_service.h" +#include "base/scoped_temp_dir.h" +#include "base/string_util.h" +#include "base/stl_util-inl.h" +#include "base/synchronization/waitable_event.h" +#include "base/test/test_timeouts.h" +#include "base/threading/thread.h" +#include "testing/gtest/include/gtest/gtest.h" + +#if defined(OS_MACOSX) +// TODO(mnissler): There are flakes on Mac (http://crbug.com/54822) at least for +// FilePathWatcherTest.MultipleWatchersSingleFile. +#define MAYBE(name) FLAKY_ ## name +#else +#define MAYBE(name) name +#endif + +namespace { + +class TestDelegate; + +// Aggregates notifications from the test delegates and breaks the message loop +// the test thread is waiting on once they all came in. +class NotificationCollector + : public base::RefCountedThreadSafe<NotificationCollector> { + public: + NotificationCollector() + : loop_(base::MessageLoopProxy::CreateForCurrentThread()) {} + + // Called from the file thread by the delegates. + void OnChange(TestDelegate* delegate) { + loop_->PostTask(FROM_HERE, + NewRunnableMethod(this, + &NotificationCollector::RecordChange, + make_scoped_refptr(delegate))); + } + + void Register(TestDelegate* delegate) { + delegates_.insert(delegate); + } + + void Reset() { + signaled_.clear(); + } + + bool Success() { + return signaled_ == delegates_; + } + + private: + void RecordChange(TestDelegate* delegate) { + ASSERT_TRUE(loop_->BelongsToCurrentThread()); + ASSERT_TRUE(delegates_.count(delegate)); + signaled_.insert(delegate); + + // Check whether all delegates have been signaled. + if (signaled_ == delegates_) + loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); + } + + // Set of registered delegates. + std::set<TestDelegate*> delegates_; + + // Set of signaled delegates. + std::set<TestDelegate*> signaled_; + + // The loop we should break after all delegates signaled. + scoped_refptr<base::MessageLoopProxy> loop_; +}; + +// A mock FilePathWatcher::Delegate for testing. I'd rather use gmock, but it's +// not thread safe for setting expectations, so the test code couldn't safely +// reset expectations while the file watcher is running. In order to allow this, +// we keep simple thread safe status flags in TestDelegate. +class TestDelegate : public FilePathWatcher::Delegate { + public: + // The message loop specified by |loop| will be quit if a notification is + // received while the delegate is |armed_|. Note that the testing code must + // guarantee |loop| outlives the file thread on which OnFilePathChanged runs. + explicit TestDelegate(NotificationCollector* collector) + : collector_(collector) { + collector_->Register(this); + } + + virtual void OnFilePathChanged(const FilePath&) { + collector_->OnChange(this); + } + + private: + scoped_refptr<NotificationCollector> collector_; + + DISALLOW_COPY_AND_ASSIGN(TestDelegate); +}; + +// A helper class for setting up watches on the file thread. +class SetupWatchTask : public Task { + public: + SetupWatchTask(const FilePath& target, + FilePathWatcher* watcher, + FilePathWatcher::Delegate* delegate, + bool* result, + base::WaitableEvent* completion, + base::MessageLoopProxy* mac_run_loop) + : target_(target), + watcher_(watcher), + delegate_(delegate), + result_(result), + completion_(completion), + mac_run_loop_(mac_run_loop) {} + + void Run() { + *result_ = watcher_->Watch(target_, delegate_, mac_run_loop_); + completion_->Signal(); + } + + private: + const FilePath target_; + FilePathWatcher* watcher_; + FilePathWatcher::Delegate* delegate_; + bool* result_; + base::WaitableEvent* completion_; + scoped_refptr<base::MessageLoopProxy> mac_run_loop_; + + DISALLOW_COPY_AND_ASSIGN(SetupWatchTask); +}; + +class FilePathWatcherTest : public testing::Test { + public: + FilePathWatcherTest() + : loop_(MessageLoop::TYPE_UI), + file_thread_("FilePathWatcherTest") { } + + virtual ~FilePathWatcherTest() { } + + protected: + virtual void SetUp() { + // Create a separate file thread in order to test proper thread usage. + base::Thread::Options options(MessageLoop::TYPE_IO, 0); + ASSERT_TRUE(file_thread_.StartWithOptions(options)); + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + collector_ = new NotificationCollector(); + } + + virtual void TearDown() { + loop_.RunAllPending(); + } + + FilePath test_file() { + return temp_dir_.path().AppendASCII("FilePathWatcherTest"); + } + + // Write |content| to |file|. Returns true on success. + bool WriteFile(const FilePath& file, const std::string& content) { + int write_size = file_util::WriteFile(file, content.c_str(), + content.length()); + return write_size == static_cast<int>(content.length()); + } + + bool SetupWatch(const FilePath& target, + FilePathWatcher* watcher, + FilePathWatcher::Delegate* delegate) WARN_UNUSED_RESULT { + base::WaitableEvent completion(false, false); + bool result; + file_thread_.message_loop_proxy()->PostTask(FROM_HERE, + new SetupWatchTask(target, + watcher, + delegate, + &result, + &completion, + base::MessageLoopProxy::CreateForCurrentThread())); + completion.Wait(); + return result; + } + + bool WaitForEvents() WARN_UNUSED_RESULT { + collector_->Reset(); + loop_.Run(); + return collector_->Success(); + } + + NotificationCollector* collector() { return collector_.get(); } + + MessageLoop loop_; + base::Thread file_thread_; + ScopedTempDir temp_dir_; + scoped_refptr<NotificationCollector> collector_; +}; + +// Basic test: Create the file and verify that we notice. +TEST_F(FilePathWatcherTest, MAYBE(NewFile)) { + FilePathWatcher watcher; + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get())); + + ASSERT_TRUE(WriteFile(test_file(), "content")); + ASSERT_TRUE(WaitForEvents()); +} + +// Verify that modifying the file is caught. +TEST_F(FilePathWatcherTest, MAYBE(ModifiedFile)) { + ASSERT_TRUE(WriteFile(test_file(), "content")); + + FilePathWatcher watcher; + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get())); + + // Now make sure we get notified if the file is modified. + ASSERT_TRUE(WriteFile(test_file(), "new content")); + ASSERT_TRUE(WaitForEvents()); +} + +// Verify that moving the file into place is caught. +TEST_F(FilePathWatcherTest, MAYBE(MovedFile)) { + FilePath source_file(temp_dir_.path().AppendASCII("source")); + ASSERT_TRUE(WriteFile(source_file, "content")); + + FilePathWatcher watcher; + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get())); + + // Now make sure we get notified if the file is modified. + ASSERT_TRUE(file_util::Move(source_file, test_file())); + ASSERT_TRUE(WaitForEvents()); +} + +TEST_F(FilePathWatcherTest, MAYBE(DeletedFile)) { + ASSERT_TRUE(WriteFile(test_file(), "content")); + + FilePathWatcher watcher; + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get())); + + // Now make sure we get notified if the file is deleted. + file_util::Delete(test_file(), false); + ASSERT_TRUE(WaitForEvents()); +} + +// Used by the DeleteDuringNotify test below. +// Deletes the FilePathWatcher when it's notified. +class Deleter : public FilePathWatcher::Delegate { + public: + Deleter(FilePathWatcher* watcher, MessageLoop* loop) + : watcher_(watcher), + loop_(loop) { + } + + virtual void OnFilePathChanged(const FilePath& path) { + watcher_.reset(); + loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask()); + } + + scoped_ptr<FilePathWatcher> watcher_; + MessageLoop* loop_; +}; + +// Verify that deleting a watcher during the callback doesn't crash. +TEST_F(FilePathWatcherTest, DeleteDuringNotify) { + FilePathWatcher* watcher = new FilePathWatcher; + // Takes ownership of watcher. + scoped_refptr<Deleter> deleter(new Deleter(watcher, &loop_)); + ASSERT_TRUE(SetupWatch(test_file(), watcher, deleter.get())); + + ASSERT_TRUE(WriteFile(test_file(), "content")); + ASSERT_TRUE(WaitForEvents()); + + // We win if we haven't crashed yet. + // Might as well double-check it got deleted, too. + ASSERT_TRUE(deleter->watcher_.get() == NULL); +} + +// Verify that deleting the watcher works even if there is a pending +// notification. +TEST_F(FilePathWatcherTest, DestroyWithPendingNotification) { + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + FilePathWatcher* watcher = new FilePathWatcher; + ASSERT_TRUE(SetupWatch(test_file(), watcher, delegate.get())); + ASSERT_TRUE(WriteFile(test_file(), "content")); + file_thread_.message_loop_proxy()->DeleteSoon(FROM_HERE, watcher); +} + +TEST_F(FilePathWatcherTest, MAYBE(MultipleWatchersSingleFile)) { + FilePathWatcher watcher1, watcher2; + scoped_refptr<TestDelegate> delegate1(new TestDelegate(collector())); + scoped_refptr<TestDelegate> delegate2(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(test_file(), &watcher1, delegate1.get())); + ASSERT_TRUE(SetupWatch(test_file(), &watcher2, delegate2.get())); + + ASSERT_TRUE(WriteFile(test_file(), "content")); + ASSERT_TRUE(WaitForEvents()); +} + +// Verify that watching a file whose parent directory doesn't exist yet works if +// the directory and file are created eventually. +TEST_F(FilePathWatcherTest, NonExistentDirectory) { + FilePathWatcher watcher; + FilePath dir(temp_dir_.path().AppendASCII("dir")); + FilePath file(dir.AppendASCII("file")); + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get())); + + ASSERT_TRUE(file_util::CreateDirectory(dir)); + + ASSERT_TRUE(WriteFile(file, "content")); + + VLOG(1) << "Waiting for file creation"; + ASSERT_TRUE(WaitForEvents()); + + ASSERT_TRUE(WriteFile(file, "content v2")); + VLOG(1) << "Waiting for file change"; + ASSERT_TRUE(WaitForEvents()); + + ASSERT_TRUE(file_util::Delete(file, false)); + VLOG(1) << "Waiting for file deletion"; + ASSERT_TRUE(WaitForEvents()); +} + +// Exercises watch reconfiguration for the case that directories on the path +// are rapidly created. +TEST_F(FilePathWatcherTest, DirectoryChain) { + FilePath path(temp_dir_.path()); + std::vector<std::string> dir_names; + for (int i = 0; i < 20; i++) { + std::string dir(StringPrintf("d%d", i)); + dir_names.push_back(dir); + path = path.AppendASCII(dir); + } + + FilePathWatcher watcher; + FilePath file(path.AppendASCII("file")); + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get())); + + FilePath sub_path(temp_dir_.path()); + for (std::vector<std::string>::const_iterator d(dir_names.begin()); + d != dir_names.end(); ++d) { + sub_path = sub_path.AppendASCII(*d); + ASSERT_TRUE(file_util::CreateDirectory(sub_path)); + } + VLOG(1) << "Create File"; + ASSERT_TRUE(WriteFile(file, "content")); + VLOG(1) << "Waiting for file creation"; + ASSERT_TRUE(WaitForEvents()); + + ASSERT_TRUE(WriteFile(file, "content v2")); + VLOG(1) << "Waiting for file modification"; + ASSERT_TRUE(WaitForEvents()); +} + +TEST_F(FilePathWatcherTest, DisappearingDirectory) { + FilePathWatcher watcher; + FilePath dir(temp_dir_.path().AppendASCII("dir")); + FilePath file(dir.AppendASCII("file")); + ASSERT_TRUE(file_util::CreateDirectory(dir)); + ASSERT_TRUE(WriteFile(file, "content")); + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get())); + + ASSERT_TRUE(file_util::Delete(dir, true)); + ASSERT_TRUE(WaitForEvents()); +} + +// Tests that a file that is deleted and reappears is tracked correctly. +TEST_F(FilePathWatcherTest, DeleteAndRecreate) { + ASSERT_TRUE(WriteFile(test_file(), "content")); + FilePathWatcher watcher; + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get())); + + ASSERT_TRUE(file_util::Delete(test_file(), false)); + VLOG(1) << "Waiting for file deletion"; + ASSERT_TRUE(WaitForEvents()); + + ASSERT_TRUE(WriteFile(test_file(), "content")); + VLOG(1) << "Waiting for file creation"; + ASSERT_TRUE(WaitForEvents()); +} + +TEST_F(FilePathWatcherTest, WatchDirectory) { + FilePathWatcher watcher; + FilePath dir(temp_dir_.path().AppendASCII("dir")); + FilePath file1(dir.AppendASCII("file1")); + FilePath file2(dir.AppendASCII("file2")); + scoped_refptr<TestDelegate> delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(dir, &watcher, delegate.get())); + + ASSERT_TRUE(file_util::CreateDirectory(dir)); + VLOG(1) << "Waiting for directory creation"; + ASSERT_TRUE(WaitForEvents()); + + ASSERT_TRUE(WriteFile(file1, "content")); + VLOG(1) << "Waiting for file1 creation"; + ASSERT_TRUE(WaitForEvents()); + + ASSERT_TRUE(WriteFile(file1, "content v2")); + VLOG(1) << "Waiting for file1 modification"; + ASSERT_TRUE(WaitForEvents()); + + ASSERT_TRUE(file_util::Delete(file1, false)); + VLOG(1) << "Waiting for file1 deletion"; + ASSERT_TRUE(WaitForEvents()); + + ASSERT_TRUE(WriteFile(file2, "content")); + VLOG(1) << "Waiting for file2 creation"; + ASSERT_TRUE(WaitForEvents()); +} + +TEST_F(FilePathWatcherTest, MoveParent) { + FilePathWatcher file_watcher; + FilePathWatcher subdir_watcher; + FilePath dir(temp_dir_.path().AppendASCII("dir")); + FilePath dest(temp_dir_.path().AppendASCII("dest")); + FilePath subdir(dir.AppendASCII("subdir")); + FilePath file(subdir.AppendASCII("file")); + scoped_refptr<TestDelegate> file_delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(file, &file_watcher, file_delegate.get())); + scoped_refptr<TestDelegate> subdir_delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(subdir, &subdir_watcher, subdir_delegate.get())); + + // Setup a directory hierarchy. + ASSERT_TRUE(file_util::CreateDirectory(subdir)); + ASSERT_TRUE(WriteFile(file, "content")); + VLOG(1) << "Waiting for file creation"; + ASSERT_TRUE(WaitForEvents()); + + // Move the parent directory. + file_util::Move(dir, dest); + VLOG(1) << "Waiting for directory move"; + ASSERT_TRUE(WaitForEvents()); +} + +TEST_F(FilePathWatcherTest, MoveChild) { + FilePathWatcher file_watcher; + FilePathWatcher subdir_watcher; + FilePath source_dir(temp_dir_.path().AppendASCII("source")); + FilePath source_subdir(source_dir.AppendASCII("subdir")); + FilePath source_file(source_subdir.AppendASCII("file")); + FilePath dest_dir(temp_dir_.path().AppendASCII("dest")); + FilePath dest_subdir(dest_dir.AppendASCII("subdir")); + FilePath dest_file(dest_subdir.AppendASCII("file")); + + // Setup a directory hierarchy. + ASSERT_TRUE(file_util::CreateDirectory(source_subdir)); + ASSERT_TRUE(WriteFile(source_file, "content")); + + scoped_refptr<TestDelegate> file_delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(dest_file, &file_watcher, file_delegate.get())); + scoped_refptr<TestDelegate> subdir_delegate(new TestDelegate(collector())); + ASSERT_TRUE(SetupWatch(dest_subdir, &subdir_watcher, subdir_delegate.get())); + + // Move the directory into place, s.t. the watched file appears. + ASSERT_TRUE(file_util::Move(source_dir, dest_dir)); + ASSERT_TRUE(WaitForEvents()); +} + +} // namespace diff --git a/content/common/file_path_watcher/file_path_watcher_inotify.cc b/content/common/file_path_watcher/file_path_watcher_inotify.cc new file mode 100644 index 0000000..ac9e5ce --- /dev/null +++ b/content/common/file_path_watcher/file_path_watcher_inotify.cc @@ -0,0 +1,434 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/common/file_path_watcher/file_path_watcher.h" + +#include <errno.h> +#include <string.h> +#include <sys/inotify.h> +#include <sys/ioctl.h> +#include <sys/select.h> +#include <unistd.h> + +#include <algorithm> +#include <set> +#include <utility> +#include <vector> + +#include "base/eintr_wrapper.h" +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/hash_tables.h" +#include "base/lazy_instance.h" +#include "base/logging.h" +#include "base/message_loop.h" +#include "base/message_loop_proxy.h" +#include "base/scoped_ptr.h" +#include "base/synchronization/lock.h" +#include "base/task.h" +#include "base/threading/thread.h" + +namespace { + +class FilePathWatcherImpl; + +// Singleton to manage all inotify watches. +// TODO(tony): It would be nice if this wasn't a singleton. +// http://crbug.com/38174 +class InotifyReader { + public: + typedef int Watch; // Watch descriptor used by AddWatch and RemoveWatch. + static const Watch kInvalidWatch = -1; + + // Watch directory |path| for changes. |watcher| will be notified on each + // change. Returns kInvalidWatch on failure. + Watch AddWatch(const FilePath& path, FilePathWatcherImpl* watcher); + + // Remove |watch|. Returns true on success. + bool RemoveWatch(Watch watch, FilePathWatcherImpl* watcher); + + // Callback for InotifyReaderTask. + void OnInotifyEvent(const inotify_event* event); + + private: + friend struct ::base::DefaultLazyInstanceTraits<InotifyReader>; + + typedef std::set<FilePathWatcherImpl*> WatcherSet; + + InotifyReader(); + ~InotifyReader(); + + // We keep track of which delegates want to be notified on which watches. + base::hash_map<Watch, WatcherSet> watchers_; + + // Lock to protect watchers_. + base::Lock lock_; + + // Separate thread on which we run blocking read for inotify events. + base::Thread thread_; + + // File descriptor returned by inotify_init. + const int inotify_fd_; + + // Use self-pipe trick to unblock select during shutdown. + int shutdown_pipe_[2]; + + // Flag set to true when startup was successful. + bool valid_; + + DISALLOW_COPY_AND_ASSIGN(InotifyReader); +}; + +class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate { + public: + FilePathWatcherImpl(); + + // Called for each event coming from the watch. |fired_watch| identifies the + // watch that fired, |child| indicates what has changed, and is relative to + // the currently watched path for |fired_watch|. The flag |created| is true if + // the object appears, and |is_directory| is set when the event refers to a + // directory. + void OnFilePathChanged(InotifyReader::Watch fired_watch, + const FilePath::StringType& child, + bool created, + bool is_directory); + + // Start watching |path| for changes and notify |delegate| on each change. + // Returns true if watch for |path| has been added successfully. + virtual bool Watch(const FilePath& path, + FilePathWatcher::Delegate* delegate, + base::MessageLoopProxy* loop) OVERRIDE; + + // Cancel the watch. This unregisters the instance with InotifyReader. + virtual void Cancel() OVERRIDE; + + private: + virtual ~FilePathWatcherImpl() {} + + // Inotify watches are installed for all directory components of |target_|. A + // WatchEntry instance holds the watch descriptor for a component and the + // subdirectory for that identifies the next component. + struct WatchEntry { + WatchEntry(InotifyReader::Watch watch, const FilePath::StringType& subdir) + : watch_(watch), + subdir_(subdir) {} + + InotifyReader::Watch watch_; + FilePath::StringType subdir_; + }; + typedef std::vector<WatchEntry> WatchVector; + + // Reconfigure to watch for the most specific parent directory of |target_| + // that exists. Updates |watched_path_|. Returns true on success. + bool UpdateWatches() WARN_UNUSED_RESULT; + + // Delegate to notify upon changes. + scoped_refptr<FilePathWatcher::Delegate> delegate_; + + // The file or directory we're supposed to watch. + FilePath target_; + + // The vector of watches and next component names for all path components, + // starting at the root directory. The last entry corresponds to the watch for + // |target_| and always stores an empty next component name in |subdir_|. + WatchVector watches_; + + DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); +}; + +class InotifyReaderTask : public Task { + public: + InotifyReaderTask(InotifyReader* reader, int inotify_fd, int shutdown_fd) + : reader_(reader), + inotify_fd_(inotify_fd), + shutdown_fd_(shutdown_fd) { + } + + virtual void Run() { + while (true) { + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(inotify_fd_, &rfds); + FD_SET(shutdown_fd_, &rfds); + + // Wait until some inotify events are available. + int select_result = + HANDLE_EINTR(select(std::max(inotify_fd_, shutdown_fd_) + 1, + &rfds, NULL, NULL, NULL)); + if (select_result < 0) { + DPLOG(WARNING) << "select failed"; + return; + } + + if (FD_ISSET(shutdown_fd_, &rfds)) + return; + + // Adjust buffer size to current event queue size. + int buffer_size; + int ioctl_result = HANDLE_EINTR(ioctl(inotify_fd_, FIONREAD, + &buffer_size)); + + if (ioctl_result != 0) { + DPLOG(WARNING) << "ioctl failed"; + return; + } + + std::vector<char> buffer(buffer_size); + + ssize_t bytes_read = HANDLE_EINTR(read(inotify_fd_, &buffer[0], + buffer_size)); + + if (bytes_read < 0) { + DPLOG(WARNING) << "read from inotify fd failed"; + return; + } + + ssize_t i = 0; + while (i < bytes_read) { + inotify_event* event = reinterpret_cast<inotify_event*>(&buffer[i]); + size_t event_size = sizeof(inotify_event) + event->len; + DCHECK(i + event_size <= static_cast<size_t>(bytes_read)); + reader_->OnInotifyEvent(event); + i += event_size; + } + } + } + + private: + InotifyReader* reader_; + int inotify_fd_; + int shutdown_fd_; + + DISALLOW_COPY_AND_ASSIGN(InotifyReaderTask); +}; + +static base::LazyInstance<InotifyReader> g_inotify_reader( + base::LINKER_INITIALIZED); + +InotifyReader::InotifyReader() + : thread_("inotify_reader"), + inotify_fd_(inotify_init()), + valid_(false) { + shutdown_pipe_[0] = -1; + shutdown_pipe_[1] = -1; + if (inotify_fd_ >= 0 && pipe(shutdown_pipe_) == 0 && thread_.Start()) { + thread_.message_loop()->PostTask( + FROM_HERE, new InotifyReaderTask(this, inotify_fd_, shutdown_pipe_[0])); + valid_ = true; + } +} + +InotifyReader::~InotifyReader() { + if (valid_) { + // Write to the self-pipe so that the select call in InotifyReaderTask + // returns. + ssize_t ret = HANDLE_EINTR(write(shutdown_pipe_[1], "", 1)); + DPCHECK(ret > 0); + DCHECK_EQ(ret, 1); + thread_.Stop(); + } + if (inotify_fd_ >= 0) + close(inotify_fd_); + if (shutdown_pipe_[0] >= 0) + close(shutdown_pipe_[0]); + if (shutdown_pipe_[1] >= 0) + close(shutdown_pipe_[1]); +} + +InotifyReader::Watch InotifyReader::AddWatch( + const FilePath& path, FilePathWatcherImpl* watcher) { + if (!valid_) + return kInvalidWatch; + + base::AutoLock auto_lock(lock_); + + Watch watch = inotify_add_watch(inotify_fd_, path.value().c_str(), + IN_CREATE | IN_DELETE | + IN_CLOSE_WRITE | IN_MOVE | + IN_ONLYDIR); + + if (watch == kInvalidWatch) + return kInvalidWatch; + + watchers_[watch].insert(watcher); + + return watch; +} + +bool InotifyReader::RemoveWatch(Watch watch, + FilePathWatcherImpl* watcher) { + if (!valid_) + return false; + + base::AutoLock auto_lock(lock_); + + watchers_[watch].erase(watcher); + + if (watchers_[watch].empty()) { + watchers_.erase(watch); + return (inotify_rm_watch(inotify_fd_, watch) == 0); + } + + return true; +} + +void InotifyReader::OnInotifyEvent(const inotify_event* event) { + if (event->mask & IN_IGNORED) + return; + + FilePath::StringType child(event->len ? event->name : FILE_PATH_LITERAL("")); + base::AutoLock auto_lock(lock_); + + for (WatcherSet::iterator watcher = watchers_[event->wd].begin(); + watcher != watchers_[event->wd].end(); + ++watcher) { + (*watcher)->OnFilePathChanged(event->wd, + child, + event->mask & (IN_CREATE | IN_MOVED_TO), + event->mask & IN_ISDIR); + } +} + +FilePathWatcherImpl::FilePathWatcherImpl() + : delegate_(NULL) { +} + +void FilePathWatcherImpl::OnFilePathChanged( + InotifyReader::Watch fired_watch, + const FilePath::StringType& child, + bool created, + bool is_directory) { + + if (!message_loop()->BelongsToCurrentThread()) { + // Switch to message_loop_ to access watches_ safely. + message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(this, + &FilePathWatcherImpl::OnFilePathChanged, + fired_watch, + child, + created, + is_directory)); + return; + } + + DCHECK(MessageLoopForIO::current()); + + // Find the entry in |watches_| that corresponds to |fired_watch|. + WatchVector::const_iterator watch_entry(watches_.begin()); + for ( ; watch_entry != watches_.end(); ++watch_entry) { + if (fired_watch == watch_entry->watch_) + break; + } + + // If this notification is from a previous generation of watches or the watch + // has been cancelled (|watches_| is empty then), bail out. + if (watch_entry == watches_.end()) + return; + + // Check whether a path component of |target_| changed. + bool change_on_target_path = child.empty() || child == watch_entry->subdir_; + + // Check whether the change references |target_| or a direct child. + DCHECK(watch_entry->subdir_.empty() || (watch_entry + 1) != watches_.end()); + bool target_changed = watch_entry->subdir_.empty() || + (watch_entry->subdir_ == child && (++watch_entry)->subdir_.empty()); + + // Update watches if a directory component of the |target_| path (dis)appears. + if (is_directory && change_on_target_path && !UpdateWatches()) { + delegate_->OnError(); + return; + } + + // Report the following events: + // - The target or a direct child of the target got changed (in case the + // watched path refers to a directory). + // - One of the parent directories got moved or deleted, since the target + // disappears in this case. + // - One of the parent directories appears. The event corresponding to the + // target appearing might have been missed in this case, so recheck. + if (target_changed || + (change_on_target_path && !created) || + (change_on_target_path && file_util::PathExists(target_))) { + delegate_->OnFilePathChanged(target_); + } +} + +bool FilePathWatcherImpl::Watch(const FilePath& path, + FilePathWatcher::Delegate* delegate, + base::MessageLoopProxy*) { + DCHECK(target_.empty()); + DCHECK(MessageLoopForIO::current()); + + set_message_loop(base::MessageLoopProxy::CreateForCurrentThread()); + delegate_ = delegate; + target_ = path; + std::vector<FilePath::StringType> comps; + target_.GetComponents(&comps); + DCHECK(!comps.empty()); + for (std::vector<FilePath::StringType>::const_iterator comp(++comps.begin()); + comp != comps.end(); ++comp) { + watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch, *comp)); + } + watches_.push_back(WatchEntry(InotifyReader::kInvalidWatch, + FilePath::StringType())); + return UpdateWatches(); +} + +void FilePathWatcherImpl::Cancel() { + if (!message_loop().get()) { + // Watch was never called, so exit. + return; + } + + // Switch to the message_loop_ if necessary so we can access |watches_|. + if (!message_loop()->BelongsToCurrentThread()) { + message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(this, &FilePathWatcherImpl::Cancel)); + return; + } + + for (WatchVector::iterator watch_entry(watches_.begin()); + watch_entry != watches_.end(); ++watch_entry) { + if (watch_entry->watch_ != InotifyReader::kInvalidWatch) + g_inotify_reader.Get().RemoveWatch(watch_entry->watch_, this); + } + watches_.clear(); + delegate_ = NULL; + target_.clear(); +} + +bool FilePathWatcherImpl::UpdateWatches() { + // Ensure this runs on the message_loop_ exclusively in order to avoid + // concurrency issues. + DCHECK(message_loop()->BelongsToCurrentThread()); + + // Walk the list of watches and update them as we go. + FilePath path(FILE_PATH_LITERAL("/")); + bool path_valid = true; + for (WatchVector::iterator watch_entry(watches_.begin()); + watch_entry != watches_.end(); ++watch_entry) { + InotifyReader::Watch old_watch = watch_entry->watch_; + if (path_valid) { + watch_entry->watch_ = g_inotify_reader.Get().AddWatch(path, this); + if (watch_entry->watch_ == InotifyReader::kInvalidWatch) { + path_valid = false; + } + } else { + watch_entry->watch_ = InotifyReader::kInvalidWatch; + } + if (old_watch != InotifyReader::kInvalidWatch && + old_watch != watch_entry->watch_) { + g_inotify_reader.Get().RemoveWatch(old_watch, this); + } + path = path.Append(watch_entry->subdir_); + } + + return true; +} + +} // namespace + +FilePathWatcher::FilePathWatcher() { + impl_ = new FilePathWatcherImpl(); +} diff --git a/content/common/file_path_watcher/file_path_watcher_mac.cc b/content/common/file_path_watcher/file_path_watcher_mac.cc new file mode 100644 index 0000000..6e89ad1 --- /dev/null +++ b/content/common/file_path_watcher/file_path_watcher_mac.cc @@ -0,0 +1,274 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/common/file_path_watcher/file_path_watcher.h" + +#include <CoreServices/CoreServices.h> +#include <set> + +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/logging.h" +#include "base/mac/scoped_cftyperef.h" +#include "base/message_loop.h" +#include "base/singleton.h" +#include "base/time.h" + +// Note to future well meaning engineers. Unless kqueue semantics have changed +// considerably, do NOT try to reimplement this class using kqueue. The main +// problem is that this class requires the ability to watch a directory +// and notice changes to any files within it. A kqueue on a directory can watch +// for creation and deletion of files, but not for modifications to files within +// the directory. To do this with the current kqueue semantics would require +// kqueueing every file in the directory, and file descriptors are a limited +// resource. If you have a good idea on how to get around this, the source for a +// reasonable implementation of this class using kqueues is attached here: +// http://code.google.com/p/chromium/issues/detail?id=54822#c13 + +namespace { + +// The latency parameter passed to FSEventsStreamCreate(). +const CFAbsoluteTime kEventLatencySeconds = 0.3; + +// Mac-specific file watcher implementation based on the FSEvents API. +class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate { + public: + FilePathWatcherImpl(); + + // Called from the FSEvents callback whenever there is a change to the paths + void OnFilePathChanged(); + + // (Re-)Initialize the event stream to start reporting events from + // |start_event|. + void UpdateEventStream(FSEventStreamEventId start_event); + + // FilePathWatcher::PlatformDelegate overrides. + virtual bool Watch(const FilePath& path, + FilePathWatcher::Delegate* delegate, + base::MessageLoopProxy* loop) OVERRIDE; + virtual void Cancel() OVERRIDE; + + scoped_refptr<base::MessageLoopProxy> run_loop_message_loop() { + return run_loop_message_loop_; + } + + private: + virtual ~FilePathWatcherImpl() {} + + // Destroy the event stream. + void DestroyEventStream(); + + // Delegate to notify upon changes. + scoped_refptr<FilePathWatcher::Delegate> delegate_; + + // Target path to watch (passed to delegate). + FilePath target_; + + // Keep track of the last modified time of the file. We use nulltime + // to represent the file not existing. + base::Time last_modified_; + + // The time at which we processed the first notification with the + // |last_modified_| time stamp. + base::Time first_notification_; + + // Backend stream we receive event callbacks from (strong reference). + FSEventStreamRef fsevent_stream_; + + // Run loop for FSEventStream to run on. + scoped_refptr<base::MessageLoopProxy> run_loop_message_loop_; + + // Used to detect early cancellation. + bool canceled_; + + DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); +}; + +// The callback passed to FSEventStreamCreate(). +void FSEventsCallback(ConstFSEventStreamRef stream, + void* event_watcher, size_t num_events, + void* event_paths, const FSEventStreamEventFlags flags[], + const FSEventStreamEventId event_ids[]) { + FilePathWatcherImpl* watcher = + reinterpret_cast<FilePathWatcherImpl*>(event_watcher); + DCHECK(watcher->run_loop_message_loop()->BelongsToCurrentThread()); + + bool root_changed = false; + FSEventStreamEventId root_change_at = FSEventStreamGetLatestEventId(stream); + for (size_t i = 0; i < num_events; i++) { + if (flags[i] & kFSEventStreamEventFlagRootChanged) + root_changed = true; + if (event_ids[i]) + root_change_at = std::min(root_change_at, event_ids[i]); + } + + // Reinitialize the event stream if we find changes to the root. This is + // necessary since FSEvents doesn't report any events for the subtree after + // the directory to be watched gets created. + if (root_changed) { + // Resetting the event stream from within the callback fails (FSEvents spews + // bad file descriptor errors), so post a task to do the reset. + watcher->run_loop_message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(watcher, &FilePathWatcherImpl::UpdateEventStream, + root_change_at)); + } + + watcher->OnFilePathChanged(); +} + +// FilePathWatcherImpl implementation: + +FilePathWatcherImpl::FilePathWatcherImpl() + : fsevent_stream_(NULL), + canceled_(false) { +} + +void FilePathWatcherImpl::OnFilePathChanged() { + // Switch to the CFRunLoop based thread if necessary, so we can tear down + // the event stream. + if (!message_loop()->BelongsToCurrentThread()) { + message_loop()->PostTask( + FROM_HERE, + NewRunnableMethod(this, &FilePathWatcherImpl::OnFilePathChanged)); + return; + } + + DCHECK(message_loop()->BelongsToCurrentThread()); + DCHECK(!target_.empty()); + + base::PlatformFileInfo file_info; + bool file_exists = file_util::GetFileInfo(target_, &file_info); + if (file_exists && (last_modified_.is_null() || + last_modified_ != file_info.last_modified)) { + last_modified_ = file_info.last_modified; + first_notification_ = base::Time::Now(); + delegate_->OnFilePathChanged(target_); + } else if (file_exists && !first_notification_.is_null()) { + // The target's last modification time is equal to what's on record. This + // means that either an unrelated event occurred, or the target changed + // again (file modification times only have a resolution of 1s). Comparing + // file modification times against the wall clock is not reliable to find + // out whether the change is recent, since this code might just run too + // late. Moreover, there's no guarantee that file modification time and wall + // clock times come from the same source. + // + // Instead, the time at which the first notification carrying the current + // |last_notified_| time stamp is recorded. Later notifications that find + // the same file modification time only need to be forwarded until wall + // clock has advanced one second from the initial notification. After that + // interval, client code is guaranteed to having seen the current revision + // of the file. + if (base::Time::Now() - first_notification_ > + base::TimeDelta::FromSeconds(1)) { + // Stop further notifications for this |last_modification_| time stamp. + first_notification_ = base::Time(); + } + delegate_->OnFilePathChanged(target_); + } else if (!file_exists && !last_modified_.is_null()) { + last_modified_ = base::Time(); + delegate_->OnFilePathChanged(target_); + } +} + +bool FilePathWatcherImpl::Watch(const FilePath& path, + FilePathWatcher::Delegate* delegate, + base::MessageLoopProxy* loop) { + DCHECK(target_.value().empty()); + DCHECK(MessageLoopForIO::current()); + + set_message_loop(base::MessageLoopProxy::CreateForCurrentThread()); + run_loop_message_loop_ = loop; + target_ = path; + delegate_ = delegate; + + FSEventStreamEventId start_event = FSEventsGetCurrentEventId(); + + base::PlatformFileInfo file_info; + if (file_util::GetFileInfo(target_, &file_info)) { + last_modified_ = file_info.last_modified; + first_notification_ = base::Time::Now(); + } + + run_loop_message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(this, &FilePathWatcherImpl::UpdateEventStream, + start_event)); + + return true; +} + +void FilePathWatcherImpl::Cancel() { + if (!run_loop_message_loop().get()) { + // Watch was never called, so exit. + return; + } + + // Switch to the CFRunLoop based thread if necessary, so we can tear down + // the event stream. + if (!run_loop_message_loop()->BelongsToCurrentThread()) { + run_loop_message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(this, &FilePathWatcherImpl::Cancel)); + return; + } + + canceled_ = true; + if (fsevent_stream_) + DestroyEventStream(); +} + +void FilePathWatcherImpl::UpdateEventStream(FSEventStreamEventId start_event) { + DCHECK(run_loop_message_loop()->BelongsToCurrentThread()); + DCHECK(MessageLoopForUI::current()); + + // It can happen that the watcher gets canceled while tasks that call this + // function are still in flight, so abort if this situation is detected. + if (canceled_) + return; + + if (fsevent_stream_) + DestroyEventStream(); + + base::mac::ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString( + NULL, target_.value().c_str(), kCFStringEncodingMacHFS)); + base::mac::ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString( + NULL, target_.DirName().value().c_str(), kCFStringEncodingMacHFS)); + CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() }; + base::mac::ScopedCFTypeRef<CFArrayRef> watched_paths(CFArrayCreate( + NULL, reinterpret_cast<const void**>(paths_array), arraysize(paths_array), + &kCFTypeArrayCallBacks)); + + FSEventStreamContext context; + context.version = 0; + context.info = this; + context.retain = NULL; + context.release = NULL; + context.copyDescription = NULL; + + fsevent_stream_ = FSEventStreamCreate(NULL, &FSEventsCallback, &context, + watched_paths, + start_event, + kEventLatencySeconds, + kFSEventStreamCreateFlagWatchRoot); + FSEventStreamScheduleWithRunLoop(fsevent_stream_, CFRunLoopGetCurrent(), + kCFRunLoopDefaultMode); + if (!FSEventStreamStart(fsevent_stream_)) { + message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(delegate_.get(), + &FilePathWatcher::Delegate::OnError)); + } +} + +void FilePathWatcherImpl::DestroyEventStream() { + DCHECK(run_loop_message_loop()->BelongsToCurrentThread()); + FSEventStreamStop(fsevent_stream_); + FSEventStreamUnscheduleFromRunLoop(fsevent_stream_, CFRunLoopGetCurrent(), + kCFRunLoopDefaultMode); + FSEventStreamRelease(fsevent_stream_); + fsevent_stream_ = NULL; +} + +} // namespace + +FilePathWatcher::FilePathWatcher() { + impl_ = new FilePathWatcherImpl(); +} diff --git a/content/common/file_path_watcher/file_path_watcher_stub.cc b/content/common/file_path_watcher/file_path_watcher_stub.cc new file mode 100644 index 0000000..42b6ec6 --- /dev/null +++ b/content/common/file_path_watcher/file_path_watcher_stub.cc @@ -0,0 +1,21 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file exists for Unix systems which don't have the inotify headers, and +// thus cannot build file_watcher_inotify.cc + +#include "chrome/common/file_path_watcher/file_path_watcher.h" + +class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate { + public: + virtual bool Watch(const FilePath& path, + FileWatcher::Delegate* delegate, + base::MessageLoopProxy*) OVERRIDE { + return false; + } +}; + +FilePathWatcher::FilePathWatcher() { + impl_ = new FilePathWatcherImpl(); +} diff --git a/content/common/file_path_watcher/file_path_watcher_win.cc b/content/common/file_path_watcher/file_path_watcher_win.cc new file mode 100644 index 0000000..b6b4333 --- /dev/null +++ b/content/common/file_path_watcher/file_path_watcher_win.cc @@ -0,0 +1,256 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/common/file_path_watcher/file_path_watcher.h" + +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/logging.h" +#include "base/message_loop_proxy.h" +#include "base/ref_counted.h" +#include "base/time.h" +#include "base/win/object_watcher.h" + +namespace { + +class FilePathWatcherImpl : public FilePathWatcher::PlatformDelegate, + public base::win::ObjectWatcher::Delegate { + public: + FilePathWatcherImpl() : delegate_(NULL), handle_(INVALID_HANDLE_VALUE) {} + + // FilePathWatcher::PlatformDelegate overrides. + virtual bool Watch(const FilePath& path, + FilePathWatcher::Delegate* delegate, + base::MessageLoopProxy* loop) OVERRIDE; + virtual void Cancel() OVERRIDE; + + // Callback from MessageLoopForIO. + virtual void OnObjectSignaled(HANDLE object); + + private: + virtual ~FilePathWatcherImpl(); + + // Setup a watch handle for directory |dir|. Returns true if no fatal error + // occurs. |handle| will receive the handle value if |dir| is watchable, + // otherwise INVALID_HANDLE_VALUE. + static bool SetupWatchHandle(const FilePath& dir, HANDLE* handle) + WARN_UNUSED_RESULT; + + // (Re-)Initialize the watch handle. + bool UpdateWatch() WARN_UNUSED_RESULT; + + // Destroy the watch handle. + void DestroyWatch(); + + // Delegate to notify upon changes. + scoped_refptr<FilePathWatcher::Delegate> delegate_; + + // Path we're supposed to watch (passed to delegate). + FilePath target_; + + // Handle for FindFirstChangeNotification. + HANDLE handle_; + + // ObjectWatcher to watch handle_ for events. + base::win::ObjectWatcher watcher_; + + // Keep track of the last modified time of the file. We use nulltime + // to represent the file not existing. + base::Time last_modified_; + + // The time at which we processed the first notification with the + // |last_modified_| time stamp. + base::Time first_notification_; + + DISALLOW_COPY_AND_ASSIGN(FilePathWatcherImpl); +}; + +bool FilePathWatcherImpl::Watch(const FilePath& path, + FilePathWatcher::Delegate* delegate, + base::MessageLoopProxy*) { + DCHECK(target_.value().empty()); // Can only watch one path. + + set_message_loop(base::MessageLoopProxy::CreateForCurrentThread()); + delegate_ = delegate; + target_ = path; + + if (!UpdateWatch()) + return false; + + watcher_.StartWatching(handle_, this); + + return true; +} + +void FilePathWatcherImpl::Cancel() { + if (!message_loop().get()) { + // Watch was never called, so exit. + return; + } + + // Switch to the file thread if necessary so we can stop |watcher_|. + if (!message_loop()->BelongsToCurrentThread()) { + message_loop()->PostTask(FROM_HERE, + NewRunnableMethod(this, &FilePathWatcherImpl::Cancel)); + return; + } + + if (handle_ != INVALID_HANDLE_VALUE) + DestroyWatch(); +} + +void FilePathWatcherImpl::OnObjectSignaled(HANDLE object) { + DCHECK(object == handle_); + // Make sure we stay alive through the body of this function. + scoped_refptr<FilePathWatcherImpl> keep_alive(this); + + if (!UpdateWatch()) { + delegate_->OnError(); + return; + } + + // Check whether the event applies to |target_| and notify the delegate. + base::PlatformFileInfo file_info; + bool file_exists = file_util::GetFileInfo(target_, &file_info); + if (file_exists && (last_modified_.is_null() || + last_modified_ != file_info.last_modified)) { + last_modified_ = file_info.last_modified; + first_notification_ = base::Time::Now(); + delegate_->OnFilePathChanged(target_); + } else if (file_exists && !first_notification_.is_null()) { + // The target's last modification time is equal to what's on record. This + // means that either an unrelated event occurred, or the target changed + // again (file modification times only have a resolution of 1s). Comparing + // file modification times against the wall clock is not reliable to find + // out whether the change is recent, since this code might just run too + // late. Moreover, there's no guarantee that file modification time and wall + // clock times come from the same source. + // + // Instead, the time at which the first notification carrying the current + // |last_notified_| time stamp is recorded. Later notifications that find + // the same file modification time only need to be forwarded until wall + // clock has advanced one second from the initial notification. After that + // interval, client code is guaranteed to having seen the current revision + // of the file. + if (base::Time::Now() - first_notification_ > + base::TimeDelta::FromSeconds(1)) { + // Stop further notifications for this |last_modification_| time stamp. + first_notification_ = base::Time(); + } + delegate_->OnFilePathChanged(target_); + } else if (!file_exists && !last_modified_.is_null()) { + last_modified_ = base::Time(); + delegate_->OnFilePathChanged(target_); + } + + // The watch may have been cancelled by the callback. + if (handle_ != INVALID_HANDLE_VALUE) + watcher_.StartWatching(handle_, this); +} + +FilePathWatcherImpl::~FilePathWatcherImpl() { + if (handle_ != INVALID_HANDLE_VALUE) + DestroyWatch(); +} + +// static +bool FilePathWatcherImpl::SetupWatchHandle(const FilePath& dir, + HANDLE* handle) { + *handle = FindFirstChangeNotification( + dir.value().c_str(), + false, // Don't watch subtrees + FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE | + FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_DIR_NAME | + FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SECURITY); + if (*handle != INVALID_HANDLE_VALUE) { + // Make sure the handle we got points to an existing directory. It seems + // that windows sometimes hands out watches to direectories that are + // about to go away, but doesn't sent notifications if that happens. + if (!file_util::DirectoryExists(dir)) { + FindCloseChangeNotification(*handle); + *handle = INVALID_HANDLE_VALUE; + } + return true; + } + + // If FindFirstChangeNotification failed because the target directory + // doesn't exist, access is denied (happens if the file is already gone but + // there are still handles open), or the target is not a directory, try the + // immediate parent directory instead. + DWORD error_code = GetLastError(); + if (error_code != ERROR_FILE_NOT_FOUND && + error_code != ERROR_PATH_NOT_FOUND && + error_code != ERROR_ACCESS_DENIED && + error_code != ERROR_SHARING_VIOLATION && + error_code != ERROR_DIRECTORY) { + PLOG(ERROR) << "FindFirstChangeNotification failed for " + << dir.value(); + return false; + } + + return true; +} + +bool FilePathWatcherImpl::UpdateWatch() { + if (handle_ != INVALID_HANDLE_VALUE) + DestroyWatch(); + + base::PlatformFileInfo file_info; + if (file_util::GetFileInfo(target_, &file_info)) { + last_modified_ = file_info.last_modified; + first_notification_ = base::Time::Now(); + } + + // Start at the target and walk up the directory chain until we succesfully + // create a watch handle in |handle_|. |child_dirs| keeps a stack of child + // directories stripped from target, in reverse order. + std::vector<FilePath> child_dirs; + FilePath watched_path(target_); + while (true) { + if (!SetupWatchHandle(watched_path, &handle_)) + return false; + + // Break if a valid handle is returned. Try the parent directory otherwise. + if (handle_ != INVALID_HANDLE_VALUE) + break; + + // Abort if we hit the root directory. + child_dirs.push_back(watched_path.BaseName()); + FilePath parent(watched_path.DirName()); + if (parent == watched_path) { + LOG(ERROR) << "Reached the root directory"; + return false; + } + watched_path = parent; + } + + // At this point, handle_ is valid. However, the bottom-up search that the + // above code performs races against directory creation. So try to walk back + // down and see whether any children appeared in the mean time. + while (!child_dirs.empty()) { + watched_path = watched_path.Append(child_dirs.back()); + child_dirs.pop_back(); + HANDLE temp_handle = INVALID_HANDLE_VALUE; + if (!SetupWatchHandle(watched_path, &temp_handle)) + return false; + if (temp_handle == INVALID_HANDLE_VALUE) + break; + FindCloseChangeNotification(handle_); + handle_ = temp_handle; + } + + return true; +} + +void FilePathWatcherImpl::DestroyWatch() { + watcher_.StopWatching(); + FindCloseChangeNotification(handle_); + handle_ = INVALID_HANDLE_VALUE; +} + +} // namespace + +FilePathWatcher::FilePathWatcher() { + impl_ = new FilePathWatcherImpl(); +} |